DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: dbf17ad9d8eeb86bb698a8bba892ff00ca6eb0ff deck-builder/.archived/sdbapi/handlers/usertoken.go -rw-r--r-- 1.2 KiB
dbf17ad9Jonni Liljamo chore: generalize mold 1 year, 9 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
/*
 * 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/auth"
	"api/db"
	"api/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

type TokenRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

func GenerateToken(c *gin.Context) {
	var req TokenRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": apierror.InvalidInput})
		c.Abort()
		return
	}

	var user models.User
	record := db.DbConn.Where("email = ?", req.Email).First(&user)
	if record.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": apierror.UserNotFound})
		c.Abort()
		return
	}

	credErr := user.VerifyPwd(req.Password)
	if credErr != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": apierror.InvalidCred})
		c.Abort()
		return
	}

	token, err := auth.NewJWTToken(user.Username, user.Email)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": apierror.NewJWTError})
		c.Abort()
		return
	}

	c.JSON(http.StatusOK, gin.H{"token": token, "id": user.ID})
}