chore: merge backend repo history into monorepo at backend/
git-subtree-dir: backend git-subtree-mainline:dc11190527git-subtree-split:acae976622
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"dating-app/internal/models"
|
||||
"dating-app/internal/repository"
|
||||
"dating-app/internal/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
ContextUserKey = "current_user"
|
||||
)
|
||||
|
||||
// AuthRequired توکن access رو از هدر Authorization میخونه، اعتبارسنجی میکنه
|
||||
// و کاربر مربوطه رو توی context قرار میده.
|
||||
func AuthRequired(jwtManager *utils.JWTManager, userRepo *repository.UserRepository) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
header := c.GetHeader("Authorization")
|
||||
if header == "" || !strings.HasPrefix(header, "Bearer ") {
|
||||
utils.Fail(c, http.StatusUnauthorized, "توکن احراز هویت ارسال نشده است", nil)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
tokenStr := strings.TrimPrefix(header, "Bearer ")
|
||||
claims, err := jwtManager.ParseAccessToken(tokenStr)
|
||||
if err != nil {
|
||||
utils.Fail(c, http.StatusUnauthorized, "توکن نامعتبر یا منقضی شده است", nil)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
user, err := userRepo.FindByID(claims.UserID)
|
||||
if err != nil {
|
||||
utils.Fail(c, http.StatusUnauthorized, "کاربر یافت نشد", nil)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if !user.IsActive {
|
||||
utils.Fail(c, http.StatusForbidden, "حساب کاربری غیرفعال است", nil)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
// اگه کاربر بعد از صادر شدن access token فعلی بلاک شده باشه، نباید تا
|
||||
// انقضای طبیعی همون توکن بتونه درخواست بزنه؛ این چک همون لحظه قطعش میکنه.
|
||||
if user.State == models.UserStateBlocked {
|
||||
utils.Fail(c, http.StatusForbidden, "حساب کاربری مسدود شده است", nil)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(ContextUserKey, user)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user