Brijesh's Git Server — identity @ 8c36e39b8c6eda064ffa45901a976c3ebf028d97

authentication service

core/internal/auth/jwt_validate.go (view raw)

 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
package auth

import (
	"errors"
	"fmt"

	"github.com/golang-jwt/jwt/v5"
	"github.com/wbrijesh/identity/internal/models"
)

func ValidateAdminJWT(tokenString string) (string, error) {
	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 jwtSecret, nil
	})

	if err != nil {
		return "", err
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		if claims["role"] != "admin" {
			return "", errors.New("token is not for an admin")
		}

		admin := &models.Admin{
			ID:    claims["id"].(string),
			Email: claims["email"].(string),
		}
		return admin.ID, nil
	}

	return "", errors.New("invalid token")
}

func ValidateUserJWT(tokenString string) (string, error) {
	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 jwtSecret, nil
	})

	if err != nil {
		return "", err
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		if claims["role"] != "user" {
			return "", errors.New("token is not for a user")
		}

		user := &models.User{
			ID:            claims["id"].(string),
			Email:         claims["email"].(string),
			ApplicationID: claims["application_id"].(string),
		}
		return user.ID, nil
	}

	return "", errors.New("invalid token")
}