Example #1
0
// signUpHandler is the route for creating a user and signing up.
func (s *server) signUpHandler(w http.ResponseWriter, r *http.Request, params url.Values) {

	paramData, err := helm.ValidateParams(params, []helm.Param{{"email", true}, {"username", true}, {"password", true}})
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
	} else {
		// Generate a hashed password from bcrypt.
		hashedPass, err := bcrypt.GenerateFromPassword([]byte(paramData["password"]), bcrypt.MinCost)
		if err != nil {
			http.Error(w, "[ERROR] hashing password", http.StatusInternalServerError)
			return
		}
		count := 16
		b := make([]byte, count)
		rand.Seed(time.Now().UTC().UnixNano())
		for i := 0; i < count; i++ {
			b[i] = byte(rand.Intn(count))
		}
		token := hex.EncodeToString(b)

		now := time.Now()
		if _, err := s.db.Exec("INSERT INTO users(email, name, password_digest, auth_token, created_at, updated_at) VALUES($1,$2,$3,$4,$5,$6)", strings.ToLower(paramData["email"]), strings.ToLower(paramData["username"]), hashedPass, token, now, now); err != nil {
			http.Error(w, "[ERROR] can't connect to db", http.StatusInternalServerError)
			fmt.Println(err)
			return
		}
		var u user
		if err := s.db.Get(&u, "SELECT * FROM users WHERE name=$1", strings.ToLower(paramData["username"])); err != nil {
			http.Error(w, "[ERROR] can't connect to db", http.StatusInternalServerError)
			fmt.Println(err)
			return
		}
		helm.RespondWithJSON(w, &u, http.StatusOK)
	}
}
Example #2
0
func (s *server) authHandler(w http.ResponseWriter, r *http.Request, params url.Values) bool {

	paramData, err := helm.ValidateParams(params, []helm.Param{{"auth_token", true}})
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return false
	} else {
		var u user
		s.db.Get(&u, "SELECT * FROM users WHERE auth_token=$1", paramData["auth_token"])
		if u.Id == 0 {
			http.Error(w, "Not authorized", http.StatusForbidden)
			return false
		}
		helm.Set(r, kuser, &u)
		return true
	}
}
Example #3
0
// loginHandler
func (s *server) loginHandler(w http.ResponseWriter, r *http.Request, params url.Values) {

	paramData, err := helm.ValidateParams(params, []helm.Param{{"username", true}, {"password", true}})
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
	} else {
		var u user
		if err := s.db.Get(&u, "SELECT * FROM users WHERE name=$1", strings.ToLower(paramData["username"])); err != nil {
			http.Error(w, "[ERROR] can't connect to db", http.StatusInternalServerError)
			fmt.Println(err)
			return
		}
		if err := bcrypt.CompareHashAndPassword([]byte(u.PasswordDigest), []byte(paramData["password"])); err != nil {
			http.Error(w, "Not authorized", http.StatusUnauthorized)
			return
		}
		helm.RespondWithJSON(w, &u, http.StatusOK)
	}
}