当前位置: 首页>>代码示例>>Golang>>正文


Golang Session.Set方法代码示例

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


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

示例1: 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

示例2: 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

示例3: 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

示例4: UserLogin

func UserLogin(r *http.Request, db *sql.DB, s sessions.Session, rw http.ResponseWriter) (int, string) {
	var id string
	var pass string

	email, password := r.FormValue("email"), r.FormValue("password")
	err := db.QueryRow("select id, password from appuser where email=$1", email).Scan(&id, &pass)

	if err != nil || bcrypt.CompareHashAndPassword([]byte(pass), []byte(password)) != nil {
		//return 401, "Not Authorized. Buuuurn!"
		http.Redirect(rw, r, "/wrong", http.StatusFound)
	}

	//set the user id in the session
	s.Set("userId", id)

	//return user
	if returnUrl, ok := s.Get("returnUrl").(string); ok {
		s.Delete("returnUrl")
		http.Redirect(rw, r, returnUrl, http.StatusFound)
	} else {
		http.Redirect(rw, r, "/", http.StatusFound)
	}

	return 200, "User id is " + id
}
开发者ID:qapi,项目名称:goblog-playground,代码行数:25,代码来源:main.go

示例5: inner_GET_authorize

func inner_GET_authorize(c martini.Context, sess sessions.Session, r *http.Request, ar *osin.AuthorizeRequest) bool {
	var (
		identity = ActiveIdentity(c)
		source   = current_url(r)
		handler  martini.Handler
	)

	if identity != nil {
		ar.UserData = identity
		sess.Delete("flow")
		return true
	} else {
		sess.Set("flow", FlowState{
			Type:    AuthorizeFlow,
			Source:  source,
			StartAt: time.Now(),
		})

		if provider := r.URL.Query().Get("p"); provider == "" {
			handler = show_provider_chooser()
		} else {
			handler = redirect_to_provider(provider)
		}
	}

	c.Invoke(handler)
	return false
}
开发者ID:rogeriomarques,项目名称:oapx,代码行数:28,代码来源:flow.go

示例6: 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

示例7: userSiginCheck

func userSiginCheck(info SiginIfo, session sessions.Session) string {
	var result bool
	info.UserName, result = check.CheckUserName(info.UserName)
	if result != true {
		return "-1"
	}

	info.UserNumber, result = check.CheckNumber(info.UserNumber)
	if result != true {
		return "-2"
	}

	isSelected := model.CheckSelected(info.UserNumber)
	if isSelected == false {
		return "-3"
	}

	resultSigin := model.Sigin(info.UserName, info.UserNumber)
	if resultSigin != true {
		return "-4"
	} else {
		session.Set("user_name", info.UserName)
		session.Set("user_number", info.UserNumber)

		return "1"
	}
}
开发者ID:cwen-coder,项目名称:youth,代码行数:27,代码来源:youth.go

示例8: Login

func Login(session sessions.Session, re render.Render, r *http.Request) {
	client_id := common.Config.OAuth2Client_ID

	letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

	b := make([]rune, 10)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}
	session.AddFlash(string(b), "state")

	redirectBack := r.URL.Query().Get("redirect_back")
	ref := r.Referer()

	if redirectBack == "true" && ref != "" {
		session.Set("redirect_to", ref)
	} else {
		session.Set("redirect_to", nil)
	}

	query := url.Values{}
	query.Set("client_id", client_id)
	query.Set("state", string(b))
	query.Set("scope", "repo")

	dest := url.URL{
		Scheme:   "https",
		Host:     "github.com",
		Path:     "/login/oauth/authorize",
		RawQuery: query.Encode(),
	}
	re.Redirect(dest.String())
}
开发者ID:SemQuery,项目名称:web,代码行数:33,代码来源:session.go

示例9: 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

示例10: GetPollHandler

// GetPollHandler attempts to find the requested poll and responds with a json representation
func GetPollHandler(w http.ResponseWriter, r *http.Request, s sessions.Session, params martini.Params, ctx pollr.ApplicationContext) {
	// If this is the first time we've seen this user
	// create a new voter entry for them in the table and
	// send them their voter id
	if s.Get("voterId") == nil {
		voter := pollr.NewVoter()
		ctx.CreateVoter(voter)
		s.Options(sessions.Options{
			Domain:   r.Host,
			Path:     "/",
			MaxAge:   0,
			HttpOnly: false,
			Secure:   false,
		})
		s.Set("voterId", voter.Id.Hex())
	}
	id := params["id"]
	poll, err := ctx.FindPoll(id)
	if err != nil {
		log.Print(err)
		http.Error(w, fmt.Sprintf("Poll %s not found", id), 404)
		return
	}
	JsonPollResponse(w, poll)
}
开发者ID:jshrake,项目名称:pollr,代码行数:26,代码来源:get_poll.go

示例11: 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

示例12: apiAuthorize

func (api *dialogueApi) apiAuthorize(r *http.Request, session sessions.Session, rndr render.Render) {
	// check authorization headers
	username := r.Header.Get("X-Auth-User")
	token := r.Header.Get("X-Auth-Token")
	if username == "" || token == "" {
		e := ApiError{
			Error: "username and token must be present",
		}
		rndr.JSON(401, e)
		return
	}
	// verify token
	auth, err := api.rdb.GetAuthorization(username)
	if err != nil {
		e := ApiError{
			Error: fmt.Sprintf("error verifying token: %s", err),
		}
		rndr.JSON(401, e)
		return
	}
	if auth == nil || auth.Token != token {
		e := ApiError{
			Error: "invalid username/token",
		}
		rndr.JSON(401, e)
		return
	}
	// all is well, set session
	session.Set("username", username)
}
开发者ID:carriercomm,项目名称:dialogue-1,代码行数:30,代码来源:api.go

示例13: 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

示例14: 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

示例15: Login

func Login(session sessions.Session, su models.User, r render.Render, p *models.Page) {

	// Check if we are already logged in
	if su.Id > 0 {
		r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "albums"}, "/"), http.StatusFound)
		return
	}

	session.Set("loggedin", "false")

	// Init error holder
	errs := make(map[string]string)

	err_flash := session.Get("flash")
	if err_flash != nil {
		errs["flash"] = err_flash.(string)
		session.Set("flash", nil)
	}

	genform := utils.GenerateForm(&forms.Login{}, "/login", "POST", errs)

	p.SetUser(su)
	p.SetTitle("Login")
	p.Data = LoginVars{Form: genform}

	encoder.Render(p.Encoding, 200, "login", p, r)
}
开发者ID:szwork2013,项目名称:gopixelrelay,代码行数:27,代码来源:login.go


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