DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: c84b03ca0210247768ff1967f3f336c2c4070f3a deck-builder/.archived/sdbapi/auth/auth.go -rw-r--r-- 1.7 KiB
c84b03caJonni Liljamo Merge branch 'dev' 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
 * 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 auth

import (
	"api/db"
	"errors"
	"os"
	"time"

	"github.com/golang-jwt/jwt/v4"
)

var JWTSecret = []byte(os.Getenv("SDBAPI_JWT_SECRET"))

type JWTClaims struct {
	Username string `json:"username"`
	Email    string `json:"email"`
	jwt.RegisteredClaims
}

func NewJWTToken(username string, email string) (token string, err error) {
	claims := JWTClaims{
		Username: username,
		Email:    email,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
		},
	}
	jwtClaims := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
	token, err = jwtClaims.SignedString(JWTSecret)
	return
}

func ValidateJWTToken(userToken string) (claims *JWTClaims, err error) {
	token, err := jwt.ParseWithClaims(
		userToken,
		&JWTClaims{},
		func(token *jwt.Token) (interface{}, error) {
			return []byte(JWTSecret), nil
		},
	)

	if err != nil {
		return
	}

	if !token.Valid {
		err = errors.New("token not valid")
		return
	}

	claims, ok := token.Claims.(*JWTClaims)
	if !ok {
		err = errors.New("could not parse JWT claims")
		return
	}

	if claims.ExpiresAt.Unix() < time.Now().Local().Unix() {
		err = errors.New("token is expired")
		return
	}

	// Auth should match a registered user
	// NOTE: Technically auth should always match a registered user, but just in-case.
	// TOFIX: Or, now that I think about it, I should run some tests to see if this
	//        truly is just dumb to check.
	_, uerr := db.GetUserByEmail(claims.Email)
	if uerr != nil {
		err = errors.New("user does not exist")
		return
	}

	return
}