File size: 2,846 Bytes
3f70c4e
 
 
 
 
 
 
 
8b40e41
 
3f70c4e
8b40e41
3f70c4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c991d6d
3f70c4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b40e41
 
3f70c4e
 
 
 
 
 
 
 
 
 
8b40e41
 
3f70c4e
 
 
8b40e41
 
3f70c4e
 
 
8b40e41
3f70c4e
 
 
 
 
 
8b40e41
3f70c4e
 
8b40e41
3f70c4e
 
 
 
 
 
8b40e41
3f70c4e
 
 
 
 
 
 
 
 
 
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// auth/auth.go

package middleware

import (
	"errors"
	"time"

	"api.qobiltu.id/config"
	"api.qobiltu.id/models"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"golang.org/x/crypto/bcrypt"
)

// Define a secret key for signing the JWT token
var salt = config.Salt
var secretKey = []byte(salt)

// GenerateToken generates a JWT token for the given user
func GenerateToken(user *models.Account) (string, error) {

	// Create a new token
	token := jwt.New(jwt.SigningMethodHS256)

	// Set claims
	claims := token.Claims.(jwt.MapClaims)
	claims["id"] = user.Id
	claims["exp"] = time.Now().Add(time.Hour * 24).Unix() // Token expires in 24 hours

	// Sign the token with the secret key
	tokenString, err := token.SignedString(secretKey)
	if err != nil {
		return "", err
	}

	return tokenString, nil
}

// VerifyPassword verifies if the provided password matches the hashed password
func VerifyPassword(hashedPassword, password string) error {
	err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
	if err != nil {
		return errors.New("invalid password")
	}
	return nil
}
func HashPassword(password string) (string, error) {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
	return string(bytes), err
}

type CustomClaims struct {
	jwt.RegisteredClaims
	UserID int `json:"id"`
}

func VerifyToken(bearer_token string) (int, string, error) {
	// fmt.Println(bearer_token)
	token, err := jwt.ParseWithClaims(bearer_token, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return secretKey, nil
	})
	if err != nil {
		return 0, "invalid-token", err
	}

	// Extract the claims
	claims, ok := token.Claims.(*CustomClaims)
	if !ok || !token.Valid {
		return 0, "invalid-token", err
	}
	if claims.ExpiresAt != nil && claims.ExpiresAt.Time.Before(time.Now()) {
		return 0, "expired", err
	}

	return claims.UserID, "valid", err
}

func AuthUser(c *gin.Context) {
	var currAccData models.AccountData
	if c.Request.Header["Auth-Bearer-Token"] != nil {
		token := c.Request.Header["Auth-Bearer-Token"]
		currAccData.UserID, currAccData.VerifyStatus, currAccData.ErrVerif = VerifyToken(token[0])
		// fmt.Println("Verify Status :", currAccData.verifyStatus)
		if currAccData.VerifyStatus == "invalid-token" || currAccData.VerifyStatus == "expired" {
			currAccData.UserID = 0
			message := "Your session is expired, Please re-Login!"
			SendJSON401(c, &currAccData.VerifyStatus, &message)
			c.Abort()
			return
		}
	} else {
		currAccData.UserID = 0
		currAccData.VerifyStatus = "no-token"
		currAccData.ErrVerif = nil
		message := "You have to Login First!"
		SendJSON401(c, &currAccData.VerifyStatus, &message)
		c.Abort()
		return
	}

	c.Set("accountData", currAccData)
	c.Next()
}