示例#1
0
// SetSessionUser sets the session user in the context and template data.
func (m *Middleware) SetSessionUser(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		templateData := context.TemplateData(r)

		us := session.NewUserSession(m.App.Store)
		userID, ok := us.SessionUserID(r)
		if !ok {
			templateData["SessionUser"] = &models.User{}
			next.ServeHTTP(w, r)
			return
		}

		um := models.NewUserModel(m.App.DB)
		user, err := um.FindOne(nil, squirrel.Eq{"users.id": userID})
		if err != nil {
			us.Delete(w, r)
			http.Redirect(w, r, "/", http.StatusFound)
			return
		}
		context.SetSessionUser(r, user)
		templateData["SessionUser"] = user
		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}
示例#2
0
func getLogout(a *application.App, w http.ResponseWriter, r *http.Request) error {
	us := session.NewUserSession(a.Store)
	if err := us.Delete(w, r); err != nil {
		return errors.Wrap(err, "user session delete error")
	}

	http.Redirect(w, r, "/", http.StatusFound)
	return nil
}
示例#3
0
func loginUser(a *application.App, w http.ResponseWriter, r *http.Request, email, name string) error {
	um := models.NewUserModel(a.DB)
	user, err := um.FindOne(nil, squirrel.Eq{"users.email": email})
	if err == sql.ErrNoRows {
		// user not found so must be logging in for first time, add the user
		user = &models.User{Email: email, Name: name}
		err = um.Add(nil, user)
	}
	if err != nil && err != sql.ErrNoRows {
		return errors.Wrap(err, "login error")
	}

	us := session.NewUserSession(a.Store)
	err = us.SaveSessionUserID(w, r, user.ID)
	if err != nil {
		return errors.Wrap(err, "save session user error")
	}

	http.Redirect(w, r, "/", http.StatusFound)
	return nil
}