Exemple #1
0
// Authenticate authenticates and returns a user object
func Authenticate(email string, password string, w http.ResponseWriter, r *http.Request) (*User, error) {
	hash := crypto.PasswordHash(password)
	user, err := repo.GetWithPassword(email, hash)
	if err != nil {
		return nil, err
	}

	// Update session
	// TODO: Should just save the entire User object here
	if w != nil && r != nil {
		session, _ := store.Get(r, "authenticated-user")
		session.Values["key"] = user.Key
		session.Save(r, w)
	}

	return user, nil
}
Exemple #2
0
// RegisterHandler registers a new user
func RegisterHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		name := strings.TrimSpace(r.FormValue("name"))
		email := strings.TrimSpace(r.FormValue("email"))
		password := r.FormValue("password")

		// If email or password are blank then redirect to register page
		// TODO: provide a sensible error to people so they understand what
		// they did wrong.
		if email == "" || password == "" {
			render.Redirect(w, r, "/register")
			return
		}

		// Check to see if person already exists by attempting to log them in.
		passwordHash := crypto.PasswordHash(password)
		user, err := Authenticate(email, password, w, r)

		// If they do exist, redirect them home else create a new user and
		// log them into the site.
		if user != nil {
			render.Redirect(w, r, "/")
			return
		}

		key := crypto.UniqueHash(name)
		user = &User{Key: key, Name: name, Email: email, Password: passwordHash}
		err = repo.Insert(user)
		render.Check(err, w)

		// Auth user and redirect them
		user, _ = Authenticate(email, password, w, r)
		render.Redirect(w, r, "/")
		return
	}

	render.Render(w, r, "auth_register", nil)
}