pomme/internal/api/users.go

101 lines
2.2 KiB
Go

package api
import (
"crypto/rand"
"encoding/json"
"fmt"
"math/big"
"net/http"
"time"
"git.freecumextremist.com/grumbulon/pomme/internal"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
// NewUser takes a POST request and user form and creates a user in the database.
func NewUser(w http.ResponseWriter, r *http.Request) {
db, ok := r.Context().Value(keyPrincipalContextID).(*gorm.DB)
if !ok {
http.Error(w, "internal server error", http.StatusInternalServerError)
}
var result internal.User
err := r.ParseForm()
if err != nil {
http.Error(w, "Unable to parse request", http.StatusInternalServerError)
return
}
username := r.Form.Get("username")
if username == "" {
username = autoUname()
}
password := r.Form.Get("password")
if password == "" {
http.Error(w, "No password entered", http.StatusInternalServerError)
return
}
db.Where("username = ?", username).First(&result)
if result.Username != "" {
http.Error(w, "User already exists", http.StatusInternalServerError)
return
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
db.Create(&internal.User{Username: username, HashedPassword: string(hashedPassword)})
token := makeToken(username)
http.SetCookie(w, &http.Cookie{
HttpOnly: true,
Expires: time.Now().Add(1 * time.Hour),
MaxAge: 3600,
SameSite: http.SameSiteLaxMode,
// Uncomment below for HTTPS:
// Secure: true,
Name: "jwt", // Must be named "jwt" or else the token cannot be searched for by jwtauth.Verifier.
Value: token,
})
w.WriteHeader(http.StatusCreated)
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(
internal.Response{
Username: username,
HTTPResponse: http.StatusCreated,
Message: "Successfully created account and logged in",
})
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func autoUname() string {
n, err := rand.Int(rand.Reader, big.NewInt(1000))
if err != nil {
return ""
}
return fmt.Sprintf("user%d", n.Int64())
}