[feature/backend] implement /auth/logout handling + overall enhancement
This commit is contained in:
parent
d8d8e4b0d7
commit
e5fc8691bf
12 changed files with 420 additions and 64 deletions
57
backend/internal/service/auth.go
Normal file
57
backend/internal/service/auth.go
Normal file
|
@ -0,0 +1,57 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// TokenBlacklist 用于存储已失效的 token
|
||||
type TokenBlacklist struct {
|
||||
tokens sync.Map
|
||||
}
|
||||
|
||||
// NewTokenBlacklist 创建一个新的 token 黑名单
|
||||
func NewTokenBlacklist() *TokenBlacklist {
|
||||
bl := &TokenBlacklist{}
|
||||
// 启动定期清理过期 token 的 goroutine
|
||||
go bl.cleanupExpiredTokens()
|
||||
return bl
|
||||
}
|
||||
|
||||
// AddToBlacklist 将 token 添加到黑名单
|
||||
func (bl *TokenBlacklist) AddToBlacklist(tokenStr string, claims jwt.MapClaims) {
|
||||
// 获取 token 的过期时间
|
||||
exp, ok := claims["exp"].(float64)
|
||||
if !ok {
|
||||
log.Error().Msg("Failed to get token expiration time")
|
||||
return
|
||||
}
|
||||
|
||||
// 存储 token 和其过期时间
|
||||
bl.tokens.Store(tokenStr, time.Unix(int64(exp), 0))
|
||||
}
|
||||
|
||||
// IsBlacklisted 检查 token 是否在黑名单中
|
||||
func (bl *TokenBlacklist) IsBlacklisted(tokenStr string) bool {
|
||||
_, exists := bl.tokens.Load(tokenStr)
|
||||
return exists
|
||||
}
|
||||
|
||||
// cleanupExpiredTokens 定期清理过期的 token
|
||||
func (bl *TokenBlacklist) cleanupExpiredTokens() {
|
||||
ticker := time.NewTicker(1 * time.Hour)
|
||||
for range ticker.C {
|
||||
now := time.Now()
|
||||
bl.tokens.Range(func(key, value interface{}) bool {
|
||||
if expTime, ok := value.(time.Time); ok {
|
||||
if now.After(expTime) {
|
||||
bl.tokens.Delete(key)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
|
@ -18,12 +18,14 @@ import (
|
|||
"tss-rocks-be/ent/contributorsociallink"
|
||||
"tss-rocks-be/ent/daily"
|
||||
"tss-rocks-be/ent/dailycontent"
|
||||
"tss-rocks-be/ent/media"
|
||||
"tss-rocks-be/ent/permission"
|
||||
"tss-rocks-be/ent/post"
|
||||
"tss-rocks-be/ent/postcontent"
|
||||
"tss-rocks-be/ent/role"
|
||||
"tss-rocks-be/ent/user"
|
||||
"tss-rocks-be/internal/storage"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
@ -40,18 +42,25 @@ var openFile func(fh *multipart.FileHeader) (multipart.File, error) = func(fh *m
|
|||
}
|
||||
|
||||
type serviceImpl struct {
|
||||
client *ent.Client
|
||||
storage storage.Storage
|
||||
client *ent.Client
|
||||
storage storage.Storage
|
||||
tokenBlacklist *TokenBlacklist
|
||||
}
|
||||
|
||||
// NewService creates a new Service instance
|
||||
func NewService(client *ent.Client, storage storage.Storage) Service {
|
||||
return &serviceImpl{
|
||||
client: client,
|
||||
storage: storage,
|
||||
client: client,
|
||||
storage: storage,
|
||||
tokenBlacklist: NewTokenBlacklist(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetTokenBlacklist returns the token blacklist
|
||||
func (s *serviceImpl) GetTokenBlacklist() *TokenBlacklist {
|
||||
return s.tokenBlacklist
|
||||
}
|
||||
|
||||
// User operations
|
||||
func (s *serviceImpl) CreateUser(ctx context.Context, username, email, password string, roleStr string) (*ent.User, error) {
|
||||
// 验证邮箱格式
|
||||
|
@ -451,12 +460,14 @@ func (s *serviceImpl) DeleteMedia(ctx context.Context, id int, userID int) error
|
|||
}
|
||||
|
||||
// Check ownership
|
||||
if media.CreatedBy != strconv.Itoa(userID) {
|
||||
isOwner := media.CreatedBy == strconv.Itoa(userID)
|
||||
if !isOwner {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
|
||||
// Delete from storage
|
||||
if err := s.storage.Delete(ctx, media.StorageID); err != nil {
|
||||
err = s.storage.Delete(ctx, media.StorageID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
@ -904,3 +915,138 @@ func (s *serviceImpl) HasPermission(ctx context.Context, userID int, permission
|
|||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (s *serviceImpl) Delete(ctx context.Context, id int, currentUserID int) error {
|
||||
// Check if the entity exists and get its type
|
||||
var entityExists bool
|
||||
var err error
|
||||
|
||||
// Try to find the entity in different tables
|
||||
if entityExists, err = s.client.User.Query().Where(user.ID(id)).Exist(ctx); err == nil && entityExists {
|
||||
// Check if user has permission to delete users
|
||||
hasPermission, err := s.HasPermission(ctx, currentUserID, "users:delete")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check permission: %v", err)
|
||||
}
|
||||
if !hasPermission {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
|
||||
// Cannot delete yourself
|
||||
if id == currentUserID {
|
||||
return fmt.Errorf("cannot delete your own account")
|
||||
}
|
||||
|
||||
return s.client.User.DeleteOneID(id).Exec(ctx)
|
||||
}
|
||||
|
||||
if entityExists, err = s.client.Post.Query().Where(post.ID(id)).Exist(ctx); err == nil && entityExists {
|
||||
// Check if user has permission to delete posts
|
||||
hasPermission, err := s.HasPermission(ctx, currentUserID, "posts:delete")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check permission: %v", err)
|
||||
}
|
||||
if !hasPermission {
|
||||
// Check if the user is the author of the post
|
||||
isAuthor, err := s.client.Post.Query().
|
||||
Where(post.ID(id)).
|
||||
QueryContributors().
|
||||
QueryContributor().
|
||||
QueryUser().
|
||||
Where(user.ID(currentUserID)).
|
||||
Exist(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check post author: %v", err)
|
||||
}
|
||||
if !isAuthor {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
}
|
||||
|
||||
return s.client.Post.DeleteOneID(id).Exec(ctx)
|
||||
}
|
||||
|
||||
if entityExists, err = s.client.Category.Query().Where(category.ID(id)).Exist(ctx); err == nil && entityExists {
|
||||
// Check if user has permission to delete categories
|
||||
hasPermission, err := s.HasPermission(ctx, currentUserID, "categories:delete")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check permission: %v", err)
|
||||
}
|
||||
if !hasPermission {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
|
||||
return s.client.Category.DeleteOneID(id).Exec(ctx)
|
||||
}
|
||||
|
||||
if entityExists, err = s.client.Contributor.Query().Where(contributor.ID(id)).Exist(ctx); err == nil && entityExists {
|
||||
// Check if user has permission to delete contributors
|
||||
hasPermission, err := s.HasPermission(ctx, currentUserID, "contributors:delete")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check permission: %v", err)
|
||||
}
|
||||
if !hasPermission {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
|
||||
return s.client.Contributor.DeleteOneID(id).Exec(ctx)
|
||||
}
|
||||
|
||||
if entityExists, err = s.client.Media.Query().Where(media.ID(id)).Exist(ctx); err == nil && entityExists {
|
||||
// Check if user has permission to delete media
|
||||
hasPermission, err := s.HasPermission(ctx, currentUserID, "media:delete")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check permission: %v", err)
|
||||
}
|
||||
if !hasPermission {
|
||||
// Check if the user is the uploader of the media
|
||||
mediaItem, err := s.client.Media.Query().
|
||||
Where(media.ID(id)).
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get media: %v", err)
|
||||
}
|
||||
isOwner := mediaItem.CreatedBy == strconv.Itoa(currentUserID)
|
||||
if !isOwner {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
}
|
||||
|
||||
// Get media item for path
|
||||
mediaItem, err := s.client.Media.Get(ctx, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get media: %v", err)
|
||||
}
|
||||
|
||||
// Delete from storage first
|
||||
if err := s.storage.Delete(ctx, mediaItem.StorageID); err != nil {
|
||||
return fmt.Errorf("failed to delete media file: %v", err)
|
||||
}
|
||||
|
||||
// Then delete from database
|
||||
return s.client.Media.DeleteOneID(id).Exec(ctx)
|
||||
}
|
||||
|
||||
return fmt.Errorf("entity with id %d not found or delete operation not supported for this entity type", id)
|
||||
}
|
||||
|
||||
func (s *serviceImpl) DeleteDaily(ctx context.Context, id string, currentUserID int) error {
|
||||
// Check if user has permission to delete daily content
|
||||
hasPermission, err := s.HasPermission(ctx, currentUserID, "daily:delete")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check permission: %v", err)
|
||||
}
|
||||
if !hasPermission {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
|
||||
exists, err := s.client.Daily.Query().Where(daily.ID(id)).Exist(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check daily existence: %v", err)
|
||||
}
|
||||
if !exists {
|
||||
return fmt.Errorf("daily with id %s not found", id)
|
||||
}
|
||||
|
||||
return s.client.Daily.DeleteOneID(id).Exec(ctx)
|
||||
}
|
||||
|
|
|
@ -39,6 +39,13 @@ type Service interface {
|
|||
GetPostBySlug(ctx context.Context, langCode, slug string) (*ent.Post, error)
|
||||
ListPosts(ctx context.Context, langCode string, categoryID *int, limit, offset int) ([]*ent.Post, error)
|
||||
|
||||
// Media operations
|
||||
ListMedia(ctx context.Context, limit, offset int) ([]*ent.Media, error)
|
||||
Upload(ctx context.Context, file *multipart.FileHeader, userID int) (*ent.Media, error)
|
||||
GetMedia(ctx context.Context, id int) (*ent.Media, error)
|
||||
GetFile(ctx context.Context, id int) (io.ReadCloser, *storage.FileInfo, error)
|
||||
DeleteMedia(ctx context.Context, id int, userID int) error
|
||||
|
||||
// Contributor operations
|
||||
CreateContributor(ctx context.Context, name string, avatarURL, bio *string) (*ent.Contributor, error)
|
||||
AddContributorSocialLink(ctx context.Context, contributorID int, linkType, name, value string) (*ent.ContributorSocialLink, error)
|
||||
|
@ -51,16 +58,16 @@ type Service interface {
|
|||
GetDailyByID(ctx context.Context, id string) (*ent.Daily, error)
|
||||
ListDailies(ctx context.Context, langCode string, categoryID *int, limit, offset int) ([]*ent.Daily, error)
|
||||
|
||||
// Media operations
|
||||
ListMedia(ctx context.Context, limit, offset int) ([]*ent.Media, error)
|
||||
Upload(ctx context.Context, file *multipart.FileHeader, userID int) (*ent.Media, error)
|
||||
GetMedia(ctx context.Context, id int) (*ent.Media, error)
|
||||
GetFile(ctx context.Context, id int) (io.ReadCloser, *storage.FileInfo, error)
|
||||
DeleteMedia(ctx context.Context, id int, userID int) error
|
||||
|
||||
// RBAC operations
|
||||
InitializeRBAC(ctx context.Context) error
|
||||
AssignRole(ctx context.Context, userID int, role string) error
|
||||
RemoveRole(ctx context.Context, userID int, role string) error
|
||||
HasPermission(ctx context.Context, userID int, permission string) (bool, error)
|
||||
|
||||
// Token blacklist
|
||||
GetTokenBlacklist() *TokenBlacklist
|
||||
|
||||
// Generic operations
|
||||
Delete(ctx context.Context, id int, currentUserID int) error
|
||||
DeleteDaily(ctx context.Context, id string, currentUserID int) error
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue