feat: add admin auth middleware
This commit is contained in:
@@ -16,10 +16,14 @@ type AuthBody struct {
|
||||
Password string `json:"password" validate:"required"`
|
||||
}
|
||||
|
||||
type TokenResponse struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// Login
|
||||
// @Router /v1/admin/auth [post]
|
||||
// @Bind body body
|
||||
func (ctl *auth) Login(ctx fiber.Ctx, body *AuthBody) (string, error) {
|
||||
func (ctl *auth) Login(ctx fiber.Ctx, body *AuthBody) (*TokenResponse, error) {
|
||||
if body.Username == "admin" && body.Password == "xixi@0202" {
|
||||
claim := ctl.jwt.CreateClaims(jwt.BaseClaims{
|
||||
UserID: 1,
|
||||
@@ -27,9 +31,9 @@ func (ctl *auth) Login(ctx fiber.Ctx, body *AuthBody) (string, error) {
|
||||
|
||||
token, err := ctl.jwt.CreateToken(claim)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return nil, err
|
||||
}
|
||||
return token, nil
|
||||
return &TokenResponse{Token: token}, nil
|
||||
}
|
||||
return "", fiber.ErrUnauthorized
|
||||
return nil, fiber.ErrUnauthorized
|
||||
}
|
||||
|
||||
@@ -16,6 +16,18 @@ func (f *Middlewares) Auth(ctx fiber.Ctx) error {
|
||||
}
|
||||
|
||||
if strings.HasPrefix(ctx.Path(), "/v1/admin/") {
|
||||
token := ctx.Get("Authorization")
|
||||
if token == "" {
|
||||
return ctx.Status(fiber.StatusUnauthorized).SendString("Unauthorized")
|
||||
}
|
||||
jwt, err := f.jwt.Parse(token)
|
||||
if err != nil {
|
||||
return ctx.Status(fiber.StatusUnauthorized).SendString("Unauthorized")
|
||||
}
|
||||
if jwt.UserID != 1 {
|
||||
return ctx.Status(fiber.StatusForbidden).SendString("Forbidden")
|
||||
}
|
||||
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user