aboutsummaryrefslogtreecommitdiff
path: root/backend/middleware/auth.go
blob: ccd9c2256efef29bce9d6fb959f84f544c1d7437 (plain) (blame)
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
package middleware

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
	"github.com/pektezol/leastportals/backend/database"
	"github.com/pektezol/leastportals/backend/models"
)

func RequireAuth(c *gin.Context) {
	// Get auth cookie
	tokenString, err := c.Cookie("auth")
	if err != nil {
		log.Println("RequireAuth: Err getting cookie")
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}
	// Validate token
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(os.Getenv("SECRET_KEY")), nil
	})
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		// Check exp
		if float64(time.Now().Unix()) > claims["exp"].(float64) {
			log.Println("RequireAuth: Token expired")
			c.AbortWithStatus(http.StatusUnauthorized) // Expired
			return
		}
		// Get user from DB
		var user models.User
		database.DB.QueryRow(`SELECT * FROM users WHERE steam_id = $1;`, claims["sub"]).Scan(
			&user.SteamID, &user.Username, &user.AvatarLink, &user.CountryCode,
			&user.CreatedAt, &user.UpdatedAt, &user.UserType)
		if user.SteamID == 0 {
			log.Println("RequireAuth: No user found on database")
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		// Attach user to request
		c.Set("user", user)
		c.Next()
	} else {
		log.Println("RequireAuth: Invalid token")
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}
}