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
/*
* 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 user models.User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": apierror.InvalidInput})
c.Abort()
return
}
// check username
if len(user.Username) < 3 {
c.JSON(http.StatusBadRequest, gin.H{"error": apierror.UsernameTooShort})
c.Abort()
return
}
// check email
_, mailErr := mail.ParseAddress(user.Email)
if mailErr != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": apierror.EmailInvalid})
c.Abort()
return
}
// check password
if len(user.Password) < 8 {
c.JSON(http.StatusBadRequest, gin.H{"error": apierror.PasswordTooShort})
c.Abort()
return
}
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, gin.H{"id": user.ID, "username": user.Username, "email": user.Email})
}