diff --git a/internal/handler/checkauth.go b/internal/handler/checkauth.go new file mode 100644 index 0000000..a014ca9 --- /dev/null +++ b/internal/handler/checkauth.go @@ -0,0 +1,45 @@ +package handler + +import ( + "net/http" + "strings" + + "github.com/golang-jwt/jwt/v4" + + "github.com/OlegVankov/fantastic-engine/internal/util" +) + +func Auth(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + auth := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + + if auth == "" { + w.WriteHeader(http.StatusUnauthorized) + return + } + + userClaim := util.UserClaim{} + + token, err := jwt.ParseWithClaims(auth, &userClaim, func(token *jwt.Token) (interface{}, error) { + return []byte("secret_key"), nil + }) + + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + + if !token.Valid { + w.WriteHeader(http.StatusUnauthorized) + return + } + + if _, ok := Users2[userClaim.Username]; !ok { + w.WriteHeader(http.StatusUnauthorized) + return + } + + r.Header.Add("username", userClaim.Username) + h.ServeHTTP(w, r) + }) +} diff --git a/internal/handler/handler.go b/internal/handler/handler.go index 542eb30..cf3186b 100644 --- a/internal/handler/handler.go +++ b/internal/handler/handler.go @@ -6,11 +6,8 @@ import ( "io" "net/http" "sort" - "strings" "time" - "github.com/golang-jwt/jwt/v4" - "github.com/OlegVankov/fantastic-engine/internal/util" ) @@ -228,38 +225,3 @@ func Withdrawals(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(withdrawals) } - -func Auth(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - auth := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") - - if auth == "" { - w.WriteHeader(http.StatusUnauthorized) - return - } - - userClaim := util.UserClaim{} - - token, err := jwt.ParseWithClaims(auth, &userClaim, func(token *jwt.Token) (interface{}, error) { - return []byte("secret_key"), nil - }) - - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - - if !token.Valid { - w.WriteHeader(http.StatusUnauthorized) - return - } - - if _, ok := Users2[userClaim.Username]; !ok { - w.WriteHeader(http.StatusUnauthorized) - return - } - - r.Header.Add("username", userClaim.Username) - h.ServeHTTP(w, r) - }) -}