first commit
This commit is contained in:
42
backend/internal/auth/bootstrap.go
Normal file
42
backend/internal/auth/bootstrap.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"mira/backend/internal/config"
|
||||
"mira/backend/internal/users"
|
||||
)
|
||||
|
||||
func BootstrapSuperAdmin(ctx context.Context, cfg config.Config, store users.Store, logger *slog.Logger) error {
|
||||
email := strings.TrimSpace(cfg.SuperAdminEmail)
|
||||
password := cfg.SuperAdminPassword
|
||||
|
||||
if email == "" || password == "" {
|
||||
if cfg.AppEnv == "production" {
|
||||
return errors.New("SUPER_ADMIN_EMAIL and SUPER_ADMIN_PASSWORD are required in production")
|
||||
}
|
||||
logger.Warn("super admin bootstrap skipped because credentials are not configured")
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(password) < 12 {
|
||||
return fmt.Errorf("SUPER_ADMIN_PASSWORD must have at least 12 characters")
|
||||
}
|
||||
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hash super admin password: %w", err)
|
||||
}
|
||||
|
||||
user, err := store.UpsertSuperAdmin(ctx, email, hash)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert super admin: %w", err)
|
||||
}
|
||||
|
||||
logger.Info("super admin bootstrapped", "user_id", user.ID, "email", user.Email)
|
||||
return nil
|
||||
}
|
||||
43
backend/internal/auth/middleware.go
Normal file
43
backend/internal/auth/middleware.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const ContextClaimsKey = "auth_claims"
|
||||
const ContextUserIDKey = "auth_user_id"
|
||||
const ContextRoleKey = "auth_role"
|
||||
|
||||
func RequireAuth(tokens TokenService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
header := c.GetHeader("Authorization")
|
||||
if header == "" || !strings.HasPrefix(header, "Bearer ") {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := tokens.ParseAccessToken(strings.TrimPrefix(header, "Bearer "))
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "Sessao invalida ou expirada."})
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(ContextClaimsKey, claims)
|
||||
c.Set(ContextUserIDKey, claims.UserID)
|
||||
c.Set(ContextRoleKey, claims.Role)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func ClaimsFromContext(c *gin.Context) (Claims, bool) {
|
||||
value, ok := c.Get(ContextClaimsKey)
|
||||
if !ok {
|
||||
return Claims{}, false
|
||||
}
|
||||
|
||||
claims, ok := value.(Claims)
|
||||
return claims, ok
|
||||
}
|
||||
12
backend/internal/auth/password.go
Normal file
12
backend/internal/auth/password.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package auth
|
||||
|
||||
import "golang.org/x/crypto/bcrypt"
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
return string(hash), err
|
||||
}
|
||||
|
||||
func CheckPassword(password string, hash string) bool {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
||||
}
|
||||
134
backend/internal/auth/routes.go
Normal file
134
backend/internal/auth/routes.go
Normal file
@@ -0,0 +1,134 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mira/backend/internal/users"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Routes struct {
|
||||
users users.Store
|
||||
tokens TokenService
|
||||
}
|
||||
|
||||
func NewRoutes(users users.Store, tokens TokenService) Routes {
|
||||
return Routes{
|
||||
users: users,
|
||||
tokens: tokens,
|
||||
}
|
||||
}
|
||||
|
||||
func (r Routes) Register(router *gin.RouterGroup) {
|
||||
router.POST("/login", r.login)
|
||||
router.POST("/invitations/accept", r.acceptInvitation)
|
||||
|
||||
router.POST("/logout", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Sessao encerrada."})
|
||||
})
|
||||
|
||||
router.POST("/refresh", func(c *gin.Context) {
|
||||
c.JSON(http.StatusNotImplemented, gin.H{"message": "Renovacao de sessao ainda nao implementada."})
|
||||
})
|
||||
}
|
||||
|
||||
type loginRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
func (r Routes) login(c *gin.Context) {
|
||||
var input loginRequest
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"message": "Informe e-mail e senha validos."})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := r.users.FindByEmail(c.Request.Context(), strings.TrimSpace(input.Email))
|
||||
if errors.Is(err, users.ErrNotFound) {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"message": "E-mail ou senha invalidos."})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel fazer login."})
|
||||
return
|
||||
}
|
||||
if !CheckPassword(input.Password, user.PasswordHash) || user.Status != "active" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"message": "E-mail ou senha invalidos."})
|
||||
return
|
||||
}
|
||||
|
||||
token, err := r.tokens.IssueAccessToken(user.ID, user.Email, user.Role)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel criar a sessao."})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"access_token": token,
|
||||
"token_type": "Bearer",
|
||||
"user": gin.H{
|
||||
"id": user.ID,
|
||||
"email": user.Email,
|
||||
"name": user.Name,
|
||||
"role": user.Role,
|
||||
"status": user.Status,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type acceptInvitationRequest struct {
|
||||
Token string `json:"token" binding:"required"`
|
||||
Name string `json:"name" binding:"required,min=2"`
|
||||
Password string `json:"password" binding:"required,min=12"`
|
||||
}
|
||||
|
||||
func (r Routes) acceptInvitation(c *gin.Context) {
|
||||
var input acceptInvitationRequest
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"message": "Informe nome, senha e token validos."})
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := HashPassword(input.Password)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel proteger a senha."})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := r.users.AcceptInvitation(
|
||||
c.Request.Context(),
|
||||
users.HashInvitationToken(strings.TrimSpace(input.Token)),
|
||||
strings.TrimSpace(input.Name),
|
||||
passwordHash,
|
||||
)
|
||||
if errors.Is(err, users.ErrInvitationNotFound) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"message": "Convite invalido ou expirado."})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel aceitar o convite."})
|
||||
return
|
||||
}
|
||||
|
||||
token, err := r.tokens.IssueAccessToken(user.ID, user.Email, user.Role)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel criar a sessao."})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"access_token": token,
|
||||
"token_type": "Bearer",
|
||||
"user": gin.H{
|
||||
"id": user.ID,
|
||||
"email": user.Email,
|
||||
"name": user.Name,
|
||||
"role": user.Role,
|
||||
"status": user.Status,
|
||||
},
|
||||
})
|
||||
}
|
||||
70
backend/internal/auth/tokens.go
Normal file
70
backend/internal/auth/tokens.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type Claims struct {
|
||||
UserID string `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Role string `json:"role"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
type TokenService struct {
|
||||
secret []byte
|
||||
accessTTL time.Duration
|
||||
}
|
||||
|
||||
func NewTokenService(secret string, accessTTL time.Duration) TokenService {
|
||||
return TokenService{
|
||||
secret: []byte(secret),
|
||||
accessTTL: accessTTL,
|
||||
}
|
||||
}
|
||||
|
||||
func (s TokenService) IssueAccessToken(userID string, email string, role string) (string, error) {
|
||||
if len(s.secret) == 0 {
|
||||
return "", errors.New("jwt secret is not configured")
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
claims := Claims{
|
||||
UserID: userID,
|
||||
Email: email,
|
||||
Role: role,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: userID,
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(s.accessTTL)),
|
||||
},
|
||||
}
|
||||
|
||||
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(s.secret)
|
||||
}
|
||||
|
||||
func (s TokenService) ParseAccessToken(tokenValue string) (Claims, error) {
|
||||
if len(s.secret) == 0 {
|
||||
return Claims{}, errors.New("jwt secret is not configured")
|
||||
}
|
||||
|
||||
token, err := jwt.ParseWithClaims(tokenValue, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
if token.Method != jwt.SigningMethodHS256 {
|
||||
return nil, errors.New("unexpected signing method")
|
||||
}
|
||||
return s.secret, nil
|
||||
})
|
||||
if err != nil {
|
||||
return Claims{}, err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*Claims)
|
||||
if !ok || !token.Valid {
|
||||
return Claims{}, errors.New("invalid token")
|
||||
}
|
||||
|
||||
return *claims, nil
|
||||
}
|
||||
Reference in New Issue
Block a user