pomme/internal/api/users.go

106 lines
2.1 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 {
internalServerError(w, "internal server error")
}
var result internal.User
err := r.ParseForm()
if err != nil {
internalServerError(w, "unable to parse request")
return
}
username := r.Form.Get("username")
if username == "" {
username = autoUname()
}
password := r.Form.Get("password")
if password == "" {
internalServerError(w, "no password provided")
return
}
db.Where("username = ?", username).First(&result)
if result.Username != "" {
internalServerError(w, "user already exists")
return
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
authFailed(w, "login")
return
}
db.Create(&internal.User{Username: username, HashedPassword: string(hashedPassword)})
token, err := makeToken(username)
if err != nil {
internalServerError(w, "internal server error")
return
}
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 {
internalServerError(w, "internal server error")
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())
}