pomme/internal/api/users.go

60 lines
1.3 KiB
Go

package api
import (
"encoding/json"
"fmt"
"math/rand"
"net/http"
"time"
"git.freecumextremist.com/grumbulon/pomme/internal"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
func NewUser(w http.ResponseWriter, r *http.Request) {
db, ok := r.Context().Value("DB").(*gorm.DB)
if !ok {
http.Error(w, "internal server error", http.StatusInternalServerError)
}
var result internal.User
r.ParseForm()
username := r.Form.Get("username")
if username == "" {
username = autoUname()
}
password := r.Form.Get("password")
if password == "" {
http.Error(w, "No password entered", http.StatusInternalServerError)
}
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)
}
db.Create(&internal.User{Username: username, HashedPassword: string(hashedPassword)})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(
internal.Response{
Username: username,
HTTPResponse: http.StatusCreated,
})
}
func autoUname() string {
rand.Seed(time.Now().UnixNano())
return fmt.Sprintf("user%d", rand.Intn(99999-00000))
}