DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: ea466a600aca8e1271271e1bca531edeb5c391e5 deck-builder/api/handlers/usertoken.go -rw-r--r-- 1.3 KiB
ea466a60Jonni Liljamo feat(client): RollForPlays, and some log stuff 1 year, 4 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
/*
 * This file is part of laurelin_api
 * Copyright (C) 2023 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,
		"created_at": user.CreatedAt,
		"updated_at": user.UpdatedAt,
		"username": user.Username,
	})
}