本文整理汇总了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"
}
示例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)
}
示例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)
}
示例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
}
示例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
}
示例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
}
}
示例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"
}
}
示例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())
}
示例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)
}
示例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)
}
示例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)
}
示例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)
}
示例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)
}
}
}
示例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)
}
示例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)
}