From 318d8658039df55c479083ad29edcdf7b765b475 Mon Sep 17 00:00:00 2001 From: Rupin Raveendra Nath Date: Mon, 28 Oct 2024 22:02:59 +0100 Subject: [PATCH] better error handling --- auth/auth.go | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/auth/auth.go b/auth/auth.go index 35a0a15..77056ed 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -2,6 +2,7 @@ package auth import ( "crypto/rsa" + "errors" "fmt" "net/http" "news-master/app" @@ -67,39 +68,48 @@ func loadPublicKey() (*rsa.PublicKey, error) { return jwt.ParseRSAPublicKeyFromPEM(publicKeyData) } -func (token *Token) validateAdminToken() *DecodedUser { +func (token *Token) validateAdminToken() (*DecodedUser, error) { user := defaultDecodedUser() if token.Value == app.Config.AdminToken { user.Admin = true user.Valid = true + return user, nil + } else { + return nil, errors.New("invalid admin token") } - return user + } -func (token *Token) validateSubscriberToken() *DecodedUser { - user, _ := ValidateJWT(token.Value) - return user +func (token *Token) validateSubscriberToken() (*DecodedUser, error) { + user, error := ValidateJWT(token.Value) + return user, error } -func ValidateAdminToken(token Token) *DecodedUser { +func ValidateAdminToken(token Token) (*DecodedUser, error) { return token.validateAdminToken() } -func ValidateSubscriberToken(token Token) *DecodedUser { +func ValidateSubscriberToken(token Token) (*DecodedUser, error) { return token.validateSubscriberToken() } -func AuthMiddleware(validateToken func(Token) *DecodedUser) gin.HandlerFunc { +func AuthMiddleware(validateToken func(Token) (*DecodedUser, error)) gin.HandlerFunc { return func(c *gin.Context) { token := Token{Value: c.Request.Header.Get("Authorization")} - user := validateToken(token) - if token.Value == "" { c.JSON(http.StatusUnauthorized, gin.H{"error": "Missing token"}) c.Abort() return } + user, err := validateToken(token) + + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"}) + c.Abort() + return + } + if !user.Valid { c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"}) c.Abort()