Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion internal/api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ func NewRouter(log *zap.Logger, db *sql.DB, userService *service.UserService, ro
engine.Use(middleware.Zap(log), middleware.Recovery(log))

handler := NewHandler(db, userService, roomService, reservationService)
gen.RegisterHandlers(engine, handler)
gen.RegisterHandlersWithOptions(engine, handler, gen.GinServerOptions{
Middlewares: []gen.MiddlewareFunc{gen.MiddlewareFunc(middleware.AuthByRoute())},
})

return engine
}
84 changes: 84 additions & 0 deletions internal/middleware/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package middleware

import (
"context"
"net/http"
"strings"

"github.com/QSCTech/SRTP-Backend/pkg/response"
"github.com/gin-gonic/gin"
)

type contextKey string

const AuthUIDKey contextKey = "auth_uid"

const authUIDHeader = "X-Auth-UID"

func RequireAuth() gin.HandlerFunc {
return func(c *gin.Context) {
authUID := extractAuthUID(c)
if authUID == "" {
response.Error(c, http.StatusUnauthorized, "unauthorized")
c.Abort()
return
}
setAuthUID(c, authUID)
c.Next()
}
}

func CurrentUser() gin.HandlerFunc {
return func(c *gin.Context) {
setAuthUID(c, extractAuthUID(c))
c.Next()
}
}

func AuthByRoute() gin.HandlerFunc {
requireAuth := RequireAuth()
currentUser := CurrentUser()

return func(c *gin.Context) {
switch {
case routeNeedsAuth(c.Request.Method, c.FullPath()):
requireAuth(c)
case routeAllowsCurrentUser(c.Request.Method, c.FullPath()):
currentUser(c)
default:
c.Next()
}
}
}

func routeNeedsAuth(method, path string) bool {
switch {
case method == http.MethodPost && path == "/auth/logout":
return true
case strings.HasPrefix(path, "/me"):
return true
case method == http.MethodPost && path == "/rooms":
return true
case method == http.MethodPost && path == "/rooms/join-by-code":
return true
case path == "/rooms/:roomId" && method == http.MethodPut:
return true
case strings.HasPrefix(path, "/rooms/:roomId/") && method == http.MethodPost:
return true
default:
return false
}
}

func routeAllowsCurrentUser(method, path string) bool {
return method == http.MethodGet && path == "/rooms/:roomId"
}

func extractAuthUID(c *gin.Context) string {
return strings.TrimSpace(c.GetHeader(authUIDHeader))
}

func setAuthUID(c *gin.Context, authUID string) {
ctx := context.WithValue(c.Request.Context(), AuthUIDKey, authUID)
c.Request = c.Request.WithContext(ctx)
}
35 changes: 35 additions & 0 deletions internal/repository/room_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,19 @@ func (r *RoomRepository) Create(ctx context.Context, room *models.Room) error {
return r.db.WithContext(ctx).Create(room).Error
}

func (r *RoomRepository) CreateRoomWithOwner(ctx context.Context, room *models.Room, ownerMember *models.RoomMember) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Create(room).Error; err != nil {
return err
}
ownerMember.RoomID = room.ID
if err := tx.Create(ownerMember).Error; err != nil {
return err
}
return nil
})
}

func (r *RoomRepository) Update(ctx context.Context, room *models.Room) error {
return r.db.WithContext(ctx).Save(room).Error
}
Expand Down Expand Up @@ -237,6 +250,28 @@ func (r *RoomRepository) CountPendingJoinRequestsByUser(ctx context.Context, use
return count, nil
}

func (r *RoomRepository) DeleteMember(ctx context.Context, roomID, userID uint) error {
return r.db.WithContext(ctx).
Where("room_id = ? AND user_id = ?", roomID, userID).
Delete(&models.RoomMember{}).Error
}

func (r *RoomRepository) GetPendingJoinRequestByRoomAndUser(ctx context.Context, roomID, userID uint) (*models.JoinRequest, error) {
var req models.JoinRequest
if err := r.db.WithContext(ctx).Where("room_id = ? AND user_id = ? AND status = ?", roomID, userID, "pending").First(&req).Error; err != nil {
return nil, err
}
return &req, nil
}

func (r *RoomRepository) GetJoinRequestsByRoomID(ctx context.Context, roomID uint) ([]models.JoinRequest, error) {
var requests []models.JoinRequest
if err := r.db.WithContext(ctx).Preload("User").Where("room_id = ?", roomID).Order("created_at DESC").Find(&requests).Error; err != nil {
return nil, err
}
return requests, nil
}

/*为了避免多次查询数据库*/
func (r *RoomRepository) CountMembersByRoomIDs(ctx context.Context, roomIDs []uint) (map[uint]int64, error) {
var results []struct {
Expand Down
13 changes: 13 additions & 0 deletions internal/repository/user_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,16 @@ func (r *UserRepository) GetFirst(ctx context.Context) (*models.User, error) {
func (r *UserRepository) Update(ctx context.Context, user *models.User) error {
return r.db.WithContext(ctx).Save(user).Error
}

func (r *UserRepository) CreateProfileAudit(ctx context.Context, audit *models.UserProfileAudit) error {
return r.db.WithContext(ctx).Create(audit).Error
}

func (r *UserRepository) UpdateProfileWithAudit(ctx context.Context, user *models.User, audit *models.UserProfileAudit) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Save(user).Error; err != nil {
return err
}
return tx.Create(audit).Error
})
}
Loading