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
+5 -1
View File
@@ -50,7 +50,11 @@ func InitChiRouting() {
r.Group(func(r chi.Router) {
r.Use(auth.AuthMiddleware)
r.Get("/profile", prf.Profile)
r.Get("/allUsers", admin.GetAllUser) // all users get
r.Get("/allUsersAdm", admin.GetAllUser)
r.Route("/admin", func(r chi.Router) {
r.Use(auth.AuthAdminMiddleware)
r.Get("/allUsersAdm", admin.GetAllUser) // all users get
})
})
// up server on os.Getenv("SERVER_PORT") port on gorutin
+1
View File
@@ -15,4 +15,5 @@ type Claims struct {
jwt.RegisteredClaims
Email string `json:"email"`
Phone string `json:"phone"`
Role string `json:"role"`
}
-9
View File
@@ -1,9 +0,0 @@
package admin
import "net/http"
func AuthAdminMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
})
}
+1 -1
View File
@@ -24,4 +24,4 @@ func GetAllUser(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(jsData))
}
}
+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))
})
}