pomme/internal/api/users.go

84 lines
1.7 KiB
Go

package api
import (
"crypto/rand"
"encoding/json"
"fmt"
"math/big"
"net/http"
"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)})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
err = json.NewEncoder(w).Encode(
internal.Response{
Username: username,
HTTPResponse: http.StatusCreated,
})
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
}
func autoUname() string {
n, err := rand.Int(rand.Reader, big.NewInt(1000))
if err != nil {
return ""
}
return fmt.Sprintf("user%d", n.Int64())
}