Private
Public Access
65 lines
1.4 KiB
Go
65 lines
1.4 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"repuestera_back/dto"
|
|
"repuestera_back/jwtutils"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func Me(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "authorization header required"})
|
|
return
|
|
}
|
|
|
|
parts := strings.Split(authHeader, " ")
|
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header format"})
|
|
return
|
|
}
|
|
|
|
tokenString := parts[1]
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, jwt.ErrSignatureInvalid
|
|
}
|
|
return jwtutils.JWTSecret, nil
|
|
})
|
|
|
|
if err != nil || !token.Valid {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
return
|
|
}
|
|
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
|
return
|
|
}
|
|
|
|
sub, ok := claims["sub"].(string)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
|
return
|
|
}
|
|
userID, _ := strconv.ParseUint(sub, 10, 32)
|
|
user, err := usuarioRepo.ObtenerPorID(uint(userID))
|
|
if err != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, dto.MeResponse{
|
|
ID: user.ID,
|
|
Email: user.Email,
|
|
Name: user.Name,
|
|
})
|
|
}
|