Example #1
0
// Remember the user session by saving to the session cookie.
func Remember(w http.ResponseWriter, r *http.Request, user *models.User) error {
	err := user.Remember()
	if err != nil {
		return err
	}

	// NOTE: do not error here - invalid request cookies will be reset below
	session, err := models.Store.Get(r, models.SessionName)
	if err != nil {
		log.Println(err)
	}

	session.Values["ID"] = user.ID
	session.Values["RememberToken"] = user.RememberToken

	if err := session.Save(r, w); err != nil {
		return err
	}

	err = models.DB.Update(user)
	if err != nil {
		return err
	}

	return nil
}
Example #2
0
func TestUser_TableName(t *testing.T) {
	user := new(models.User)

	It("should override Auditable's TableName", func() {
		assert.Equal(t, "users", user.TableName())
	})
}
Example #3
0
func TestUser_Remember(t *testing.T) {
	user := new(models.User)

	err := user.Remember()
	if err != nil {
		t.Fatal(err)
	}

	It("should have a 44 byte token", func() {
		assert.Len(t, user.RememberToken, 44)
	})

	It("should have a valid digest", func() {
		assert.True(t, user.Authenticate())
	})
}
Example #4
0
func (_ User) Create(w http.ResponseWriter, r *http.Request) {
	user := new(models.User)
	if err := models.Decoder.Decode(user, r.PostForm); err != nil {
		ctx := models.NewUserCtx(r, user, []string{"bad request"}, nil)
		views.Error(w, http.StatusBadRequest, "user_new", ctx)
		return
	}

	id, err := models.DB.WithCreate(user).Exec()
	if err != nil {
		if verr, ok := err.(models.ValidationError); ok {
			views.Error(w, 422, "user_new", models.NewUserCtx(r, user, verr, nil))
			return
		}

		if perr, ok := err.(*pq.Error); ok && perr.Code.Class() == "23" {
			ctx := models.NewUserCtx(r, user, []string{"email is taken"}, nil)
			views.Error(w, http.StatusConflict, "user_new", ctx)
			return
		}

		log.Println(err)
	}

	user.ID = id
	if err := Remember(w, r, user); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := AddFlash(w, r, fmt.Sprintf("welcome %s!", user.Name)); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := Redirect(w, r, "user:show", "id", strconv.Itoa(int(id))); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}