本文整理汇总了Golang中github.com/martini-contrib/sessions.Session类的典型用法代码示例。如果您正苦于以下问题:Golang Session类的具体用法?Golang Session怎么用?Golang Session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Session类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
}
示例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)
}
示例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)
}
示例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)
}
}
示例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
}
}
示例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()
}
示例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)
}
示例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)
}
示例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)
}
示例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)
}
示例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)
}
示例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"
}
示例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)
}
示例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))
}
示例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
}
}