Example #1
0
func getUser(a *application.App, w http.ResponseWriter, r *http.Request) error {
	vars := mux.Vars(r)
	email := strings.ToLower(vars["email"])

	um := models.NewUserModel(a.DB)
	user, err := um.FindOne(nil, squirrel.Eq{"users.email": email})
	if err != nil {
		return errors.Wrap(err, "find one error")
	}

	pm := models.NewPostModel(a.DB)
	createdPosts, err := pm.Find(nil, squirrel.Eq{"posts.creator_user_id": user.ID})
	if err != nil {
		return err
	}

	data := context.TemplateData(r)
	data["User"] = user
	data["CreatedPosts"] = createdPosts
	if err = addUserUpvotedPostIDsToData(r, pm, data); err != nil {
		return errors.Wrap(err, "add upvoted post ids to data error")
	}
	err = libtemplate.Render(w, a.Templates, "user.html", data)
	return errors.Wrap(err, "render template error")
}
Example #2
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)
}
Example #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
}