Skip to content

Commit

Permalink
Merge pull request #96 from null-channel/feat/error-handler
Browse files Browse the repository at this point in the history
cleaning up middleware
  • Loading branch information
Klaven authored Mar 21, 2024
2 parents ac70654 + 0dda032 commit 4c4d833
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 24 deletions.
33 changes: 33 additions & 0 deletions api/core/core.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package core

import (
"encoding/json"
"net/http"
)

type Error struct {
Code int
Message string
}

func writeError(writer http.ResponseWriter, message string, code int) {
resp := Error{
Code: code,
Message: message,
}
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(code)
json.NewEncoder(writer).Encode(resp)
}

var (
RequestErrorHandler = func(w http.ResponseWriter, err error) {
writeError(w, err.Error(), http.StatusBadRequest)
}
InternalErrorHandler = func(w http.ResponseWriter) {
writeError(w, "An Unexpected Error Occured", http.StatusInternalServerError)
}
UnauthorizedErrorHandler = func(w http.ResponseWriter) {
writeError(w, "Unauthorized", http.StatusUnauthorized)
}
)
37 changes: 15 additions & 22 deletions api/middleware/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,62 +3,55 @@ package middleware
import (
"context"
"fmt"
"log"
"net/http"
"strings"

"github.com/golang-jwt/jwt/v4"
core "github.com/null-channel/eddington/api/core"
)

// save the cookies for any upstream calls to the Ory apis
func withCookies(ctx context.Context, v string) context.Context {
return context.WithValue(ctx, "req.cookies", v)
}
func withUser(ctx context.Context, v string) context.Context {
return context.WithValue(ctx, "user-id", v)
}

func getCookies(ctx context.Context) string {
return ctx.Value("req.cookies").(string)
}

func AddJwtHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {

//TODO: Parse JWT token and get user id
fmt.Println("Authentication Middleware is running")
log.Printf("handling middleware request\n")

// set the cookies on the ory client
var cookies string

ctx := withCookies(request.Context(), cookies)
cookies = request.Header.Get("Cookie")
tokenString := request.Header.Get("Authorization")

if tokenString == "" {
fmt.Println("Missing token in header")
core.UnauthorizedErrorHandler(writer)
return
}
// remove the Bearer prefix
// and parse the token
parser := &jwt.Parser{
ValidMethods: []string{"none"},
UseJSONNumber: true,
SkipClaimsValidation: true,
}
tokenString = strings.Replace(tokenString, "Bearer ", "", 1)
if tokenString == "" {
fmt.Println("Missing token in header")
core.UnauthorizedErrorHandler(writer)
return
}
var claims jwt.MapClaims
// parse the token
_, _, err := parser.ParseUnverified(tokenString, &claims)
if err != nil {
fmt.Println("Error parsing token! but that is ok")
fmt.Println("Error parsing token! ")
fmt.Println(err)
core.UnauthorizedErrorHandler(writer)
return
}
userId := claims["sub"].(string)

ctx = withUser(ctx, userId)
ctx := withUser(request.Context(), userId)

request.Header.Set("user-id", userId)

// continue to the requested page (in our case the Dashboard)
next.ServeHTTP(writer, request.WithContext(ctx))
return
})
}
16 changes: 14 additions & 2 deletions api/middleware/dumbauthz.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,19 @@ import (
"net/http"

"github.com/gorilla/mux"
"github.com/null-channel/eddington/api/core"
user "github.com/null-channel/eddington/api/users/models"
"github.com/uptrace/bun"
)

type UserRegistrationNotCompleteError struct {
UserID string
}

func (userNCE *UserRegistrationNotCompleteError) Error() string {
return fmt.Sprintf("the user %v require additional inforamtion", userNCE.UserID)
}

// NewUserMiddleware is a middleware that checks if the user is new.
type AuthzMiddleware struct {
db *bun.DB
Expand All @@ -25,8 +34,11 @@ func (k *AuthzMiddleware) CheckAuthz(next http.Handler) http.Handler {
userId, ok := r.Context().Value("user-id").(string)
if !ok {
fmt.Println("User is new")
http.Error(w, "User is new, they need to ", http.StatusBadRequest)
w.Header().Set("location", "/newuser")
userErr := UserRegistrationNotCompleteError{
userId,
}
core.RequestErrorHandler(w, &userErr)
// http.Error(w, "User is new, they need to ", http.StatusBadRequest)
return
}
fmt.Println("Checking if user is new...")
Expand Down

0 comments on commit 4c4d833

Please sign in to comment.