/*
* This file is part of sdbapi
* Copyright (C) 2022 Jonni Liljamo <jonni@liljamo.com>
*
* Licensed under GPL-3.0-only.
* See LICENSE for licensing information.
*/
package handlers
import (
"api/db"
"api/errors"
"api/models"
"net/http"
"net/mail"
"github.com/gin-gonic/gin"
)
func CreateUser(c *gin.Context) {
var user models.User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": errors.InvalidInput})
c.Abort()
return
}
// check username
if len(user.Username) < 3 {
c.JSON(http.StatusBadRequest, gin.H{"error": errors.UsernameTooShort})
c.Abort()
return
}
// check email
_, mailErr := mail.ParseAddress(user.Email)
if mailErr != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": errors.EmailInvalid})
c.Abort()
return
}
// check password
if len(user.Password) < 8 {
c.JSON(http.StatusBadRequest, gin.H{"error": errors.PasswordTooShort})
c.Abort()
return
}
if err := user.HashPwd(user.Password); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": errors.PasswordHashFailed})
c.Abort()
return
}
entry := db.DbConn.Create(&user)
if entry.Error != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": errors.UserCreationFailed})
c.Abort()
return
}
c.JSON(http.StatusCreated, gin.H{"id": user.ID, "username": user.Username})
}