DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: fae2a3f74f5ef8b5e29bb1ecda41d84e4519dfe3 deck-builder/api/middlewares/auth.go -rw-r--r-- 1.1 KiB
fae2a3f7Jonni Liljamo feat(client): add bevy_mod_picking 1 year, 7 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
/*
 * 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 middlewares

import (
	"api/auth"
	"api/apierror"
	"net/http"

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

// JWT authorization middleware
func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// get the authorization header and check if it exists
		token := c.Request.Header.Get("Authorization")
		if token == "" {
			// no authorization header
			c.JSON(http.StatusUnauthorized, gin.H{"error": apierror.MissingAuth})
			c.Abort()
			return
		}

		// check if the token is valid
		claims, err := auth.ValidateJWTToken(token)
		if err != nil {
			// something is wrong with the token, error out
			jwterror := apierror.APIError{apierror.GenericJWTError.ID, apierror.GenericJWTError.Name, err.Error()}
			c.JSON(http.StatusUnauthorized, gin.H{"error": jwterror})
			c.Abort()
			return
		}

		// save the email so we can use it for fetching the user from the database in the handlers
		c.Set("email", claims.Email)

		// continue to the next handler
		c.Next()
	}
}