• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang sessions.Session类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/martini-contrib/sessions.Session的典型用法代码示例。如果您正苦于以下问题:Golang Session类的具体用法?Golang Session怎么用?Golang Session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Session类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: GET_callback_AC

func GET_callback_AC(c martini.Context, sess sessions.Session) {
	flow := sess.Get("flow").(FlowState)

	c.Invoke(update_account)
	c.Invoke(activate_session)
	c.Invoke(redirect_to(flow.Source))
}
开发者ID:rogeriomarques,项目名称:oapx,代码行数:7,代码来源:flow.go


示例2: PostTopicsPosts

func (api *dialogueApi) PostTopicsPosts(w http.ResponseWriter, r *http.Request, session sessions.Session, params martini.Params, rndr render.Render) {
	content := r.FormValue("content")
	topicId := params["topicId"]
	author := session.Get("username")
	// check for content
	if content == "" {
		e := ApiError{
			Error: "content must be specified",
		}
		rndr.JSON(500, e)
		return
	}
	// new post
	post := &dialogue.Post{
		Content: content,
		TopicId: topicId,
		Author:  author.(string),
	}
	if err := api.rdb.SavePost(post); err != nil {
		e := ApiError{
			Error: fmt.Sprintf("Error saving post: %s", err),
		}
		rndr.JSON(500, e)
		return
	}
	w.WriteHeader(204)
}
开发者ID:carriercomm,项目名称:dialogue-1,代码行数:27,代码来源:api.go


示例3: SearchPage

func SearchPage(user common.User, session sessions.Session, r render.Render, req *http.Request) {
	src, err := handleSearch(req.URL.Query())

	if err != nil {
		r.Error(400)
	}

	status := common.GetCodeSourceStatus(src)

	id := rand.Int63()
	params := req.URL.Query()
	usr := params.Get("user")
	repo := params.Get("repo")
	session.Set(id, usr+"/"+repo)

	data := struct {
		common.User
		Pagename     string
		Theme        string
		SourceStatus string
		WS_ID        int64

		Source *common.CodeSource
	}{user, "search", "standard", string(status), id, src}

	r.HTML(200, "search", data)
}
开发者ID:SemQuery,项目名称:web,代码行数:27,代码来源:query.go


示例4: handleSubmission

func handleSubmission(req *http.Request, r render.Render, db *mgo.Database, session sessions.Session, backends []Backend) {
	template := make(map[string]string)
	template["contactUrl"] = os.Getenv("CONTACT_URL")
	template["contactValue"] = os.Getenv("CONTACT_VALUE")
	template["message"] = "Something went wrong :'("
	err := req.ParseForm()
	if err != nil {
		r.HTML(http.StatusBadRequest, "error", template)
	}
	user := session.Get("user").(string)
	err = userHasSubmitted(db, user)

	if err != nil {
		log.Println(err)
		r.HTML(http.StatusInternalServerError, "error", template)
	} else {
		submission := &Submission{
			Name:    req.PostForm.Get("name"),
			Address: req.PostForm.Get("address"),
			Email:   req.PostForm.Get("email"),
			Size:    req.PostForm.Get("size"),
		}
		for i := 0; i < len(backends); i++ {
			go backends[i](submission)
		}
		r.HTML(http.StatusOK, "success", nil)
	}
}
开发者ID:nquinlan,项目名称:contribot,代码行数:28,代码来源:github.go


示例5: getSignin

func getSignin(s sessions.Session, w http.ResponseWriter, r *http.Request) {
	s.Delete("username")
	if !oauthEnabled() {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}

	body, err := Asset("templates/signin.html")
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("ERROR: %s", err)
		return
	}

	tmpl, err := template.New("config.js").Parse(string(body))
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("ERROR: %s", err)
		return
	}

	err = tmpl.Execute(w, struct {
		Error  string
		Google bool
	}{
		Error:  r.FormValue("error"),
		Google: googleOauthEnabled(),
	})
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("ERROR: %s", err)
		return
	}
}
开发者ID:carriercomm,项目名称:gofana,代码行数:34,代码来源:main.go


示例6: HandlePostQuestion

func (s *AEServer) HandlePostQuestion(w http.ResponseWriter, r *http.Request, session sessions.Session) (int, string) {
	//Verify user account or something
	login := session.Get("Login")
	if login == nil {
		return 404, Message("Not Logged In!")
	}
	tok := login.(string)
	user := s.syncGetUser(tok)
	if user == nil {
		return http.StatusBadRequest, Message("Invalid Cookie!")
	}

	q := QuestionFromJson(r.Body)
	if q == nil {
		return 404, Message("Poorly Formatted JSON.")
	}
	//Assign question an ID
	q.ID = bson.NewObjectId()
	q.Author = user.Username
	q.Timestamp = time.Now()

	err := s.questions.Save(q)
	if err != nil {
		log.Print(err)
		return http.StatusInternalServerError, Message("Failed to save question")
	}
	return 200, q.GetIdHex()
}
开发者ID:boreys,项目名称:askeecs,代码行数:28,代码来源:routing.go


示例7: authMidware

func (mgr *Manager) authMidware(c martini.Context, w http.ResponseWriter, r *http.Request, ss sessions.Session) {
	if !strings.HasPrefix(r.URL.Path, API_PREFIX) {
		return
	}

	if !mgr.authRequired(r) {
		return
	}

	uid_ := ss.Get("uid")
	if uid_ == nil {
		w.WriteHeader(403)
		return
	}
	uid, ok := uid_.(int)
	if !ok {
		w.WriteHeader(403)
		return
	}

	exists := 0
	mgr.db.QueryRow("select 1 from admins where id == ?", uid).Scan(&exists)
	if exists == 1 {
		return
	}
	w.WriteHeader(403)
}
开发者ID:CoolCloud,项目名称:docker-bastion,代码行数:27,代码来源:api.go


示例8: LoginPost

func LoginPost(lu forms.Login, session sessions.Session, r render.Render, dbh *db.Dbh) {
	errs := ValidateLogin(&lu)
	if len(errs) > 0 {
		log.Printf("errors: %+v\n", errs)
	}

	user := dbh.GetUserByEmail(lu.Email)

	match := auth.MatchPassword(lu.Password, user.Password, user.Salt)

	if match {
		sessionkey := SessionKey(user.Email, user.Password, user.Salt)

		session.Set("loggedin", "true")
		session.Set("uid", user.Id)
		session.Set("email", user.Email)
		session.Set("key", sessionkey)

		dbh.CreateSession(models.UserSession{UserId: user.Id, SessionKey: sessionkey, Active: true, Timestamp: time.Now().Unix()})

		r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "albums"}, "/"), http.StatusFound)
		return
	}

	session.Set("flash", "Invalid Email or Password")

	r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "login"}, "/"), http.StatusFound)
}
开发者ID:szwork2013,项目名称:gopixelrelay,代码行数:28,代码来源:login.go


示例9: PollVoteHandler

/* Handle requests to vote in a poll
Expects the following json request.
{
	choiceId: 0
}
Response: json response of the created poll
*/
func PollVoteHandler(w http.ResponseWriter, r *http.Request, s sessions.Session,
	params martini.Params, ctx pollr.ApplicationContext) {
	// Find the requested poll and return a 404 if not found
	voterId := s.Get("voterId")
	if voterId == nil {
		fmt.Println("Can't find voterId!")
		http.Error(w, "Cheater", 404)
		return
	}
	poll, err := ctx.FindPoll(params["id"])
	if err != nil {
		log.Printf("Poll %s not found", params["id"])
		http.Error(w, "Poll not found", 404)
		return
	}
	// Decode the json request body to find the choiceId
	votePollEvent := &VotePollEvent{}
	if err := json.NewDecoder(r.Body).Decode(&votePollEvent); err != nil {
		fmt.Printf("VOTE: ERROR DECODING VOTEPOLLEVENT %s", r.Body)
		http.Error(w, "Bad vote data", 404)
		return
	}
	if votePollEvent.ChoiceId > uint(len(poll.Choices)) {
		fmt.Println("VOTE: ERROR CHOICEID OUT OF RANGE")
		http.Error(w, "Bad vote data", 404)
		return
	}
	ctx.Vote(voterId.(string), params["id"], votePollEvent.ChoiceId)
}
开发者ID:jshrake,项目名称:pollr,代码行数:36,代码来源:vote_poll.go


示例10: LtiProblemSets

// LtiProblemSets handles /lti/problem_set requests.
// It creates the user/course if necessary, creates a session,
// and redirects the user to the problem set picker UI URL.
func LtiProblemSets(w http.ResponseWriter, r *http.Request, tx *sql.Tx, form LTIRequest, render render.Render, session sessions.Session) {
	now := time.Now()

	// load the coarse
	if _, err := getUpdateCourse(tx, &form, now); err != nil {
		loggedHTTPErrorf(w, http.StatusInternalServerError, "db error: %v", err)
		return
	}

	// load the user
	user, err := getUpdateUser(tx, &form, now)
	if err != nil {
		loggedHTTPErrorf(w, http.StatusInternalServerError, "db error: %v", err)
		return
	}

	// sign the user in
	session.Set("id", user.ID)

	u := &url.URL{
		Path: "/",
		Fragment: fmt.Sprintf("/problem_sets/%s/%s",
			url.QueryEscape(form.OAuthConsumerKey),
			url.QueryEscape(form.LaunchPresentationReturnURL)),
	}

	log.Printf("problem set picker redirecting to %s", u.String())
	//http.Redirect(w, r, u.String(), http.StatusSeeOther)
	http.Redirect(w, r, "/v2/users/me/cookie", http.StatusSeeOther)
}
开发者ID:RidleyLarsen,项目名称:codegrinder,代码行数:33,代码来源:lti.go


示例11: Index

func Index(session sessions.Session, r render.Render, auth core.AuthData) {

	var session_data = struct {
		Username  string
		PostsData Posts
	}{}

	v := session.Get("username")

	if v != nil {
		session_data.Username = v.(string)
	}

	req, _ := http.NewRequest("GET", "http://foojr.com/blog/posts", nil) //XXX handle error
	resp, _ := auth.CheckRequest(req)

	defer resp.Body.Close()
	data, _ := ioutil.ReadAll(resp.Body) //XXX handle error

	var posts Posts
	json.Unmarshal(data, &posts) //XXX handle error
	session_data.PostsData = posts

	r.HTML(200, "index", session_data)
}
开发者ID:viliamjr,项目名称:microblog,代码行数:25,代码来源:login.go


示例12: LoginHandler

func LoginHandler(w http.ResponseWriter, r *http.Request, session sessions.Session, log *log.Logger) string {
	c, err := config.ReadDefault("users.cfg")

	if err != nil {
		return "Can't login. Problems reading user and password."
	}

	username := r.FormValue("username")
	password := r.FormValue("password")

	allowedUsername, _ := c.RawStringDefault("user")
	allowedPassword, _ := c.RawStringDefault("password")

	if username == allowedUsername && password == allowedPassword {

		log.Print("User WAS logged in.")

		session.Set("username", username)
		session.Set("password", password)
		http.Redirect(w, r, "/home", http.StatusFound)
		return "OK"
	}

	log.Print("User wasn't logged in. User " + username + " and password " + password)

	http.Redirect(w, r, "/login", http.StatusFound)
	return "Username or password incorrect"
}
开发者ID:patrickdappollonio,项目名称:projects,代码行数:28,代码来源:handlers.go


示例13: SetupAdmin

func SetupAdmin(args martini.Params, session sessions.Session, r render.Render) {
	form := &forms.SetupAdmin{}
	session.Set("setup", "true")

	genform := utils.GenerateForm(form, "/setup", "POST", nil)
	r.HTML(200, "setup", genform)
}
开发者ID:szwork2013,项目名称:gopixelrelay,代码行数:7,代码来源:setup.go


示例14: GET_callback_BB

func GET_callback_BB(c martini.Context, sess sessions.Session) {
	flow := sess.Get("flow").(FlowState)

	c.Invoke(match_session_identity_with_flow)
	c.Invoke(create_account)
	c.Invoke(redirect_to(flow.Source))
}
开发者ID:rogeriomarques,项目名称:oapx,代码行数:7,代码来源:flow.go


示例15: ReadUser

// ReadUser is a route which fetches user according to parameter "id" on API side and according to retrieved
// session cookie on frontend side.
// Returns user struct with all posts merged to object on API call. Frontend call will render user "home" page, "user/index.tmpl".
func ReadUser(req *http.Request, params martini.Params, res render.Render, s sessions.Session) {
	var user User
	switch Root(req) {
	case "api":
		id, err := strconv.Atoi(params["id"])
		if err != nil {
			log.Println(err)
			res.JSON(400, map[string]interface{}{"error": "The user ID could not be parsed from the request URL."})
			return
		}
		user.ID = int64(id)
		user, err := user.Get()
		if err != nil {
			log.Println(err)
			if err.Error() == "not found" {
				res.JSON(404, NotFound())
				return
			}
			res.JSON(500, map[string]interface{}{"error": "Internal server error"})
			return
		}
		res.JSON(200, user)
		return
	case "user":
		user, err := user.Session(s)
		if err != nil {
			log.Println(err)
			s.Set("user", -1)
			res.HTML(500, "error", err)
			return
		}
		res.HTML(200, "user/index", user)
		return
	}
}
开发者ID:freeformz,项目名称:vertigo,代码行数:38,代码来源:users.go


示例16: Login

func Login(session sessions.Session, db *mgo.Database, r render.Render, req *http.Request, writer http.ResponseWriter) string {
	writer.Header().Set("Content-Type", "text/javascript")
	userid := req.FormValue("userid")
	callback := req.FormValue("callback")
	password := req.FormValue("password")
	fmt.Println("userid", userid)
	if userid == "" {
		return util.Jsonp(JsonRet{"login", 401, "请登录", "abc"}, callback)
	} else {
		result := bson.M{}
		err := db.C("auth_user").Find(bson.M{"id": userid}).One(&result)
		fmt.Println(password)
		fmt.Println(result)

		if err == nil {
			values := result
			if values["password"] == password {
				session.Set("userid", values["id"])
				session.Set("username", values["name"])
				values["password"] = nil
				items := []interface{}{}
				db.C("good_shares").Find(bson.M{"acc": userid}).All(&items)
				values["items"] = items
				fmt.Println("登录成功!")
				return util.Jsonp(JsonRet{"login", 200, "登录成功", values}, callback)

			} else {
				return util.Jsonp(JsonRet{"login", 401, "登录失败!密码错误!", nil}, callback)
			}
		} else {
			return util.Jsonp(JsonRet{"login", 401, "登录失败!用户名错误!", nil}, callback)
		}
	}
}
开发者ID:payallmoney,项目名称:sharego,代码行数:34,代码来源:auth.go


示例17: HandleLogin

func (s *AEServer) HandleLogin(r *http.Request, params martini.Params, session sessions.Session) (int, string) {
	a := AuthFromJson(r.Body)
	if a == nil {
		time.Sleep(time.Second)
		return 404, Message("Login Failed")
	}

	sltr := StrResponse{}
	sltr.Arg = a.Username
	sltr.Resp = make(chan string)
	s.ch_getsalt <- sltr
	salt := <-sltr.Resp
	if salt == "" {
		return 401, Message("No login salt registered!")
	}

	user := s.FindUserByName(a.Username)
	salt_pass := DoHash(user.Password, salt)
	if salt_pass != a.Password {
		fmt.Println("Invalid password.")
		time.Sleep(time.Second)
		return http.StatusUnauthorized, Message("Invalid Username or Password.")
	}

	user.login = time.Now()
	tok := s.GetSessionToken()
	s.ch_login <- &Session{tok, user}
	session.Set("Login", tok)

	fmt.Println("Logged in!")
	return 200, Stringify(user)
}
开发者ID:boreys,项目名称:askeecs,代码行数:32,代码来源:routing.go


示例18: DoLogin

func DoLogin(entity models.UserLogin, session sessions.Session, enc Encoder, db gorp.SqlExecutor) (int, string) {

	status := &models.DefaultStruct{
		Id:       http.StatusForbidden,
		Name:     messages.GetLocaleMessage("en", "MSG_LOGIN_INVALID"),
		Lang_key: "en",
	}

	user := GetUserByLogin(entity, db)

	if user.Name != "" {

		err := sessionauth.AuthenticateSession(session, user)
		if err != nil {
			status.Name = messages.GetLocaleMessage("en", "MSG_SESSION_INIT_ERROR")
			return http.StatusForbidden, Must(enc.EncodeOne(status))
		}
		user.Authenticated = true
		user.UpdateLastLogin()
		status.Name = messages.GetLocaleMessage("en", "MSG_SUCCESSFUL_LOGIN")
		return http.StatusOK, Must(enc.EncodeOne(user))

	} else {

		sessionauth.Logout(session, user)
		session.Clear()
		return http.StatusForbidden, Must(enc.EncodeOne(status))

	}

	return http.StatusForbidden, Must(enc.EncodeOne(status))
}
开发者ID:gitter-badger,项目名称:warnabroda-server,代码行数:32,代码来源:user.go


示例19: UserGet

func UserGet(ren render.Render, params martini.Params, dbmap *gorp.DbMap, s sessions.Session) {
	var usr User
	log.Println(params)
	err := dbmap.SelectOne(&usr, "SELECT * from users WHERE id = $1", s.Get("userId"))
	PanicIf(err)
	ren.JSON(200, usr)
}
开发者ID:ukitazume,项目名称:bunkai,代码行数:7,代码来源:server.go


示例20: loginWithNameAndPwd

func loginWithNameAndPwd(r *http.Request, res http.ResponseWriter, params martini.Params, session sessions.Session, render render.Render, l *log.Logger) {
	err := r.ParseForm()
	if err != nil {
		l.Printf("ParseForm error: %v\n", err)
		render.HTML(200, "error", "登录失败!")
		return
	}

	username := r.PostFormValue("username")
	//password := r.PostFormValue("password")

	l.Printf("Start logging in, username = %s \n", username)
	//gitlabClient, err := gogitlab.NewGitlabByLogin(constant.GitLabHost, constant.GitLabApiPath, username, password)
	//if err != nil {
	//	l.Printf("Login error: %v\n", err)
	//	render.HTML(200, "error", "登录失败!")
	//	return
	//}
	//gitUser, err := gitlabClient.CurrentUser()
	//if err != nil {
	//	l.Printf("Get current error: %v\n", err)
	//	render.HTML(200, "error", "登录失败!")
	//	return
	//}
	uInfo := &UserInfo{}
	session.Set(constant.UserInfoKey, uInfo)
	render.HTML(200, "dashboard", uInfo)
}
开发者ID:ahmatjan,项目名称:mycodefactory,代码行数:28,代码来源:webserver.go



注:本文中的github.com/martini-contrib/sessions.Session类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang ut.AssertEqual函数代码示例发布时间:2022-05-23
下一篇:
Golang sessions.Sessions函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap