1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* 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())
}