add authAdminMiddlware into package auth. Need test it

This commit is contained in:
valitovgaziz
2024-08-23 07:53:10 +05:00
parent 3b045c8629
commit d10f4af8e3
6 changed files with 61 additions and 12 deletions
+50
View File
@@ -0,0 +1,50 @@
package auth
import (
"api/src/models"
"context"
"net/http"
"github.com/golang-jwt/jwt/v4"
)
func AuthAdminMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("token")
if err != nil {
if err == http.ErrNoCookie {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
tknStr := c.Value
claims := &models.Claims{}
tkn, err := jwt.ParseWithClaims(tknStr, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
if !tkn.Valid {
w.WriteHeader(http.StatusUnauthorized)
return
}
if claims.Role != "Admin" {
w.WriteHeader(http.StatusNonAuthoritativeInfo)
return
}
ctx := context.WithValue(r.Context(), "email", claims.Email)
next.ServeHTTP(w, r.WithContext(ctx))
})
}