cslms-api/internal/middleware/auth.go
2023-12-29 00:27:12 +09:00

157 lines
3.3 KiB
Go

package middleware
import (
"errors"
"fmt"
"net/http"
"strings"
config "learnsteam/cslms-api/configs"
"learnsteam/cslms-api/internal/database"
"learnsteam/cslms-api/internal/models"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
func Auth(permission string) gin.HandlerFunc {
return func(c *gin.Context) {
sub, err := UserID(c.Request)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
c.Abort()
return
}
role, err := Role(c.Request)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
c.Abort()
return
}
if permission != "member" && *role != permission {
fmt.Println("permission", permission, "role", *role)
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
c.Abort()
return
}
valid := Valid(c.Request)
if !valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "token is not valid"})
c.Abort()
return
}
c.Set("token", Extract(c.Request))
c.Set("sub", sub)
c.Set("role", role)
c.Next()
}
}
func Permission(permission *string) gin.HandlerFunc {
return func(c *gin.Context) {
sub, err := UserID(c.Request)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
c.Abort()
return
}
role, err := Role(c.Request)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
c.Abort()
return
}
if role != permission {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
c.Abort()
return
}
valid := Valid(c.Request)
if !valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "token is not valid"})
c.Abort()
return
}
c.Set("token", Extract(c.Request))
c.Set("sub", sub)
c.Set("role", role)
c.Next()
}
}
func Extract(r *http.Request) string {
authorization := r.Header.Get("Authorization")
strArr := strings.Split(authorization, " ")
if len(strArr) == 2 {
return strArr[1]
}
return ""
}
func Verify(r *http.Request) (*jwt.Token, error) {
tokenString := Extract(r)
jwtToken, err := jwt.Parse(tokenString, func(jwtToken *jwt.Token) (interface{}, error) {
if _, ok := jwtToken.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", jwtToken.Header["alg"])
}
return []byte(config.SECRET_KEY), nil
})
return jwtToken, err
}
func UserID(r *http.Request) (int64, error) {
jwtToken, err := Verify(r)
if err != nil {
fmt.Println(err)
return -1, err
}
claims, ok := jwtToken.Claims.(jwt.MapClaims)
if !ok || !jwtToken.Valid {
return -1, errors.New("refresh token is invalid")
}
sub := claims["sub"].(float64)
user_id := int64(sub)
if err != nil {
return -1, err
}
fmt.Println(user_id)
return user_id, nil
}
func Role(r *http.Request) (*string, error) {
jwtToken, err := Verify(r)
if err != nil {
return nil, err
}
claims, ok := jwtToken.Claims.(jwt.MapClaims)
if !ok || !jwtToken.Valid {
return nil, errors.New("refresh token is invalid")
}
role := claims["role"].(string)
return &role, nil
}
func Valid(r *http.Request) bool {
tokenString := Extract(r)
var token models.Token
fmt.Println(tokenString)
err := database.DB.Where("token = ? AND status = ?", tokenString, "on").First(&token).Error
fmt.Println(&token)
return err == nil
}