Skip to content

Commit

Permalink
refactor midlleware
Browse files Browse the repository at this point in the history
  • Loading branch information
zelhat committed Jan 6, 2024
1 parent dda553f commit aee74e1
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 38 deletions.
45 changes: 45 additions & 0 deletions internal/handler/checkauth.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
38 changes: 0 additions & 38 deletions internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@ import (
"io"
"net/http"
"sort"
"strings"
"time"

"github.com/golang-jwt/jwt/v4"

"github.com/OlegVankov/fantastic-engine/internal/util"
)

Expand Down Expand Up @@ -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)
})
}

0 comments on commit aee74e1

Please sign in to comment.