/*
* 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/apierror"
"api/db"
"api/models"
"net/http"
"net/mail"
"github.com/gin-gonic/gin"
)
func CreateUser(c *gin.Context) {
var input models.UserCreateInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": apierror.InvalidInput})
c.Abort()
return
}
// check username
if len(input.Username) < 3 {
c.JSON(http.StatusBadRequest, gin.H{"error": apierror.UsernameTooShort})
c.Abort()
return
}
// check email
_, mailErr := mail.ParseAddress(input.Email)
if mailErr != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": apierror.EmailInvalid})
c.Abort()
return
}
// check password
if len(input.Password) < 8 {
c.JSON(http.StatusBadRequest, gin.H{"error": apierror.PasswordTooShort})
c.Abort()
return
}
var user models.User
user.Username = input.Username
user.Email = input.Email
user.Password = input.Password
if err := user.HashPwd(user.Password); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": apierror.PasswordHashFailed})
c.Abort()
return
}
entry := db.DbConn.Create(&user)
if entry.Error != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": apierror.UserCreationFailed})
c.Abort()
return
}
c.JSON(http.StatusCreated, user.ToPub())
}