DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 7ad0cf1d5bed7109f88768a6f65f16fa53dbe449 deck-builder/sdbapi/handlers/usercreate.go -rw-r--r-- 1.4 KiB
7ad0cf1dJonni Liljamo feat(sdbclient): init new game management UIs 1 year, 10 months ago
                                                                                
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})
}