Init Eslogad
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"eslogad-be/internal/contract"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type AuthServiceImpl struct {
|
||||
userProcessor UserProcessor
|
||||
jwtSecret string
|
||||
tokenTTL time.Duration
|
||||
}
|
||||
|
||||
type Claims struct {
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Role string `json:"role"`
|
||||
Roles []string `json:"roles"`
|
||||
Permissions []string `json:"permissions"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func NewAuthService(userProcessor UserProcessor, jwtSecret string) *AuthServiceImpl {
|
||||
return &AuthServiceImpl{
|
||||
userProcessor: userProcessor,
|
||||
jwtSecret: jwtSecret,
|
||||
tokenTTL: 24 * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AuthServiceImpl) Login(ctx context.Context, req *contract.LoginRequest) (*contract.LoginResponse, error) {
|
||||
userResponse, err := s.userProcessor.GetUserByEmail(ctx, req.Email)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid credentials")
|
||||
}
|
||||
|
||||
if !userResponse.IsActive {
|
||||
return nil, fmt.Errorf("user account is deactivated")
|
||||
}
|
||||
|
||||
userEntity, err := s.userProcessor.GetUserEntityByEmail(ctx, req.Email)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid credentials")
|
||||
}
|
||||
|
||||
err = bcrypt.CompareHashAndPassword([]byte(userEntity.PasswordHash), []byte(req.Password))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid credentials")
|
||||
}
|
||||
|
||||
// fetch roles, permissions, positions for response and token
|
||||
roles, _ := s.userProcessor.GetUserRoles(ctx, userResponse.ID)
|
||||
permCodes, _ := s.userProcessor.GetUserPermissionCodes(ctx, userResponse.ID)
|
||||
positions, _ := s.userProcessor.GetUserPositions(ctx, userResponse.ID)
|
||||
|
||||
token, expiresAt, err := s.generateToken(userResponse, roles, permCodes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate token: %w", err)
|
||||
}
|
||||
|
||||
return &contract.LoginResponse{
|
||||
Token: token,
|
||||
ExpiresAt: expiresAt,
|
||||
User: *userResponse,
|
||||
Roles: roles,
|
||||
Permissions: permCodes,
|
||||
Positions: positions,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AuthServiceImpl) ValidateToken(tokenString string) (*contract.UserResponse, error) {
|
||||
claims, err := s.parseToken(tokenString)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid token: %w", err)
|
||||
}
|
||||
|
||||
userResponse, err := s.userProcessor.GetUserByID(context.Background(), claims.UserID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("user not found: %w", err)
|
||||
}
|
||||
|
||||
if !userResponse.IsActive {
|
||||
return nil, fmt.Errorf("user account is deactivated")
|
||||
}
|
||||
|
||||
return userResponse, nil
|
||||
}
|
||||
|
||||
func (s *AuthServiceImpl) RefreshToken(ctx context.Context, tokenString string) (*contract.LoginResponse, error) {
|
||||
claims, err := s.parseToken(tokenString)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid token: %w", err)
|
||||
}
|
||||
|
||||
userResponse, err := s.userProcessor.GetUserByID(ctx, claims.UserID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("user not found: %w", err)
|
||||
}
|
||||
|
||||
if !userResponse.IsActive {
|
||||
return nil, fmt.Errorf("user account is deactivated")
|
||||
}
|
||||
|
||||
roles, _ := s.userProcessor.GetUserRoles(ctx, userResponse.ID)
|
||||
permCodes, _ := s.userProcessor.GetUserPermissionCodes(ctx, userResponse.ID)
|
||||
newToken, expiresAt, err := s.generateToken(userResponse, roles, permCodes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate token: %w", err)
|
||||
}
|
||||
|
||||
positions, _ := s.userProcessor.GetUserPositions(ctx, userResponse.ID)
|
||||
return &contract.LoginResponse{
|
||||
Token: newToken,
|
||||
ExpiresAt: expiresAt,
|
||||
User: *userResponse,
|
||||
Roles: roles,
|
||||
Permissions: permCodes,
|
||||
Positions: positions,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AuthServiceImpl) Logout(ctx context.Context, tokenString string) error {
|
||||
_, err := s.parseToken(tokenString)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid token: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AuthServiceImpl) generateToken(user *contract.UserResponse, roles []contract.RoleResponse, permissionCodes []string) (string, time.Time, error) {
|
||||
expiresAt := time.Now().Add(s.tokenTTL)
|
||||
|
||||
roleCodes := make([]string, 0, len(roles))
|
||||
for _, r := range roles {
|
||||
roleCodes = append(roleCodes, r.Code)
|
||||
}
|
||||
|
||||
claims := &Claims{
|
||||
UserID: user.ID,
|
||||
Email: user.Email,
|
||||
Roles: roleCodes,
|
||||
Permissions: permissionCodes,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(expiresAt),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
NotBefore: jwt.NewNumericDate(time.Now()),
|
||||
Issuer: "eslogad-be",
|
||||
Subject: user.ID.String(),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, err := token.SignedString([]byte(s.jwtSecret))
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
|
||||
return tokenString, expiresAt, nil
|
||||
}
|
||||
|
||||
func (s *AuthServiceImpl) parseToken(tokenString string) (*Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, 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 []byte(s.jwtSecret), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
|
||||
func (s *AuthServiceImpl) ExtractAccess(tokenString string) (roles []string, permissions []string, err error) {
|
||||
claims, err := s.parseToken(tokenString)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return claims.Roles, claims.Permissions, nil
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"eslogad-be/internal/contract"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type FileStorage interface {
|
||||
Upload(ctx context.Context, bucket, key string, content []byte, contentType string) (string, error)
|
||||
EnsureBucket(ctx context.Context, bucket string) error
|
||||
}
|
||||
|
||||
type FileServiceImpl struct {
|
||||
storage FileStorage
|
||||
userProcessor UserProcessor
|
||||
profileBucket string
|
||||
docBucket string
|
||||
}
|
||||
|
||||
func NewFileService(storage FileStorage, userProcessor UserProcessor, profileBucket, docBucket string) *FileServiceImpl {
|
||||
return &FileServiceImpl{storage: storage, userProcessor: userProcessor, profileBucket: profileBucket, docBucket: docBucket}
|
||||
}
|
||||
|
||||
func (s *FileServiceImpl) UploadProfileAvatar(ctx context.Context, userID uuid.UUID, filename string, content []byte, contentType string) (string, error) {
|
||||
if err := s.storage.EnsureBucket(ctx, s.profileBucket); err != nil {
|
||||
return "", err
|
||||
}
|
||||
ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(filename), "."))
|
||||
if ext := mimeExtFromContentType(contentType); ext != "" {
|
||||
ext = ext
|
||||
}
|
||||
key := buildObjectKey("profile", userID, ext)
|
||||
url, err := s.storage.Upload(ctx, s.profileBucket, key, content, contentType)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
_, _ = s.userProcessor.UpdateUserProfile(ctx, userID, &contract.UpdateUserProfileRequest{AvatarURL: &url})
|
||||
return url, nil
|
||||
}
|
||||
|
||||
func (s *FileServiceImpl) UploadDocument(ctx context.Context, userID uuid.UUID, filename string, content []byte, contentType string) (string, string, error) {
|
||||
if err := s.storage.EnsureBucket(ctx, s.docBucket); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(filename), "."))
|
||||
if ext := mimeExtFromContentType(contentType); ext != "" {
|
||||
ext = ext
|
||||
}
|
||||
key := buildObjectKey("documents", userID, ext)
|
||||
url, err := s.storage.Upload(ctx, s.docBucket, key, content, contentType)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return url, key, nil
|
||||
}
|
||||
|
||||
func buildObjectKey(prefix string, userID uuid.UUID, ext string) string {
|
||||
now := time.Now().UTC()
|
||||
parts := []string{
|
||||
prefix,
|
||||
userID.String(),
|
||||
now.Format("2006/01/02"),
|
||||
uuid.New().String(),
|
||||
}
|
||||
key := strings.Join(parts, "/")
|
||||
if ext != "" {
|
||||
key += "." + ext
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
func mimeExtFromContentType(ct string) string {
|
||||
switch strings.ToLower(ct) {
|
||||
case "image/jpeg", "image/jpg":
|
||||
return "jpg"
|
||||
case "image/png":
|
||||
return "png"
|
||||
case "image/webp":
|
||||
return "webp"
|
||||
case "application/pdf":
|
||||
return "pdf"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"eslogad-be/internal/contract"
|
||||
"eslogad-be/internal/entities"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type UserProcessor interface {
|
||||
UpdateUser(ctx context.Context, id uuid.UUID, req *contract.UpdateUserRequest) (*contract.UserResponse, error)
|
||||
CreateUser(ctx context.Context, req *contract.CreateUserRequest) (*contract.UserResponse, error)
|
||||
DeleteUser(ctx context.Context, id uuid.UUID) error
|
||||
GetUserByID(ctx context.Context, id uuid.UUID) (*contract.UserResponse, error)
|
||||
GetUserByEmail(ctx context.Context, email string) (*contract.UserResponse, error)
|
||||
ListUsers(ctx context.Context, page, limit int) ([]contract.UserResponse, int, error)
|
||||
GetUserEntityByEmail(ctx context.Context, email string) (*entities.User, error)
|
||||
ChangePassword(ctx context.Context, userID uuid.UUID, req *contract.ChangePasswordRequest) error
|
||||
|
||||
GetUserRoles(ctx context.Context, userID uuid.UUID) ([]contract.RoleResponse, error)
|
||||
GetUserPermissionCodes(ctx context.Context, userID uuid.UUID) ([]string, error)
|
||||
GetUserPositions(ctx context.Context, userID uuid.UUID) ([]contract.PositionResponse, error)
|
||||
|
||||
GetUserProfile(ctx context.Context, userID uuid.UUID) (*contract.UserProfileResponse, error)
|
||||
UpdateUserProfile(ctx context.Context, userID uuid.UUID, req *contract.UpdateUserProfileRequest) (*contract.UserProfileResponse, error)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"eslogad-be/internal/contract"
|
||||
"eslogad-be/internal/entities"
|
||||
"eslogad-be/internal/transformer"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type UserServiceImpl struct {
|
||||
userProcessor UserProcessor
|
||||
titleRepo TitleRepository
|
||||
}
|
||||
|
||||
type TitleRepository interface {
|
||||
ListAll(ctx context.Context) ([]entities.Title, error)
|
||||
}
|
||||
|
||||
func NewUserService(userProcessor UserProcessor, titleRepo TitleRepository) *UserServiceImpl {
|
||||
return &UserServiceImpl{
|
||||
userProcessor: userProcessor,
|
||||
titleRepo: titleRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *UserServiceImpl) CreateUser(ctx context.Context, req *contract.CreateUserRequest) (*contract.UserResponse, error) {
|
||||
return s.userProcessor.CreateUser(ctx, req)
|
||||
}
|
||||
|
||||
func (s *UserServiceImpl) UpdateUser(ctx context.Context, id uuid.UUID, req *contract.UpdateUserRequest) (*contract.UserResponse, error) {
|
||||
return s.userProcessor.UpdateUser(ctx, id, req)
|
||||
}
|
||||
|
||||
func (s *UserServiceImpl) DeleteUser(ctx context.Context, id uuid.UUID) error {
|
||||
return s.userProcessor.DeleteUser(ctx, id)
|
||||
}
|
||||
|
||||
func (s *UserServiceImpl) GetUserByID(ctx context.Context, id uuid.UUID) (*contract.UserResponse, error) {
|
||||
return s.userProcessor.GetUserByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *UserServiceImpl) GetUserByEmail(ctx context.Context, email string) (*contract.UserResponse, error) {
|
||||
return s.userProcessor.GetUserByEmail(ctx, email)
|
||||
}
|
||||
|
||||
func (s *UserServiceImpl) ListUsers(ctx context.Context, req *contract.ListUsersRequest) (*contract.ListUsersResponse, error) {
|
||||
page := req.Page
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
limit := req.Limit
|
||||
if limit <= 0 {
|
||||
limit = 10
|
||||
}
|
||||
|
||||
userResponses, totalCount, err := s.userProcessor.ListUsers(ctx, page, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &contract.ListUsersResponse{
|
||||
Users: userResponses,
|
||||
Pagination: transformer.CreatePaginationResponse(totalCount, page, limit),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *UserServiceImpl) ChangePassword(ctx context.Context, userID uuid.UUID, req *contract.ChangePasswordRequest) error {
|
||||
return s.userProcessor.ChangePassword(ctx, userID, req)
|
||||
}
|
||||
|
||||
func (s *UserServiceImpl) GetProfile(ctx context.Context, userID uuid.UUID) (*contract.UserProfileResponse, error) {
|
||||
return s.userProcessor.GetUserProfile(ctx, userID)
|
||||
}
|
||||
|
||||
func (s *UserServiceImpl) UpdateProfile(ctx context.Context, userID uuid.UUID, req *contract.UpdateUserProfileRequest) (*contract.UserProfileResponse, error) {
|
||||
return s.userProcessor.UpdateUserProfile(ctx, userID, req)
|
||||
}
|
||||
|
||||
func (s *UserServiceImpl) ListTitles(ctx context.Context) (*contract.ListTitlesResponse, error) {
|
||||
if s.titleRepo == nil {
|
||||
return &contract.ListTitlesResponse{Titles: []contract.TitleResponse{}}, nil
|
||||
}
|
||||
titles, err := s.titleRepo.ListAll(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &contract.ListTitlesResponse{Titles: transformer.TitlesToContract(titles)}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user