diff --git a/internal/context/context.go b/internal/context/context.go index b3c46ae..9c25f07 100644 --- a/internal/context/context.go +++ b/internal/context/context.go @@ -3,11 +3,13 @@ package context import ( "git.supernets.org/perp/gopay/internal/config" "git.supernets.org/perp/gopay/internal/database" + "git.supernets.org/perp/gopay/internal/database/account" "github.com/gin-gonic/gin" ) type Context struct { *gin.Context + Account *account.Model Config *config.Config Database *database.Database } diff --git a/internal/context/middleware.go b/internal/context/middleware.go new file mode 100644 index 0000000..f472941 --- /dev/null +++ b/internal/context/middleware.go @@ -0,0 +1,39 @@ +package context + +import ( + "strings" + + "git.supernets.org/perp/gopay/internal/jwt" +) + +// Get an account from token header +func (ctx *Context) GetAccount() { + // Get header + header := ctx.GetHeader("Authorization") + + // Split value + split := strings.Split(header, " ") + + // No bearer found + if len(split) != 2 { + ctx.Error(400, "MissingToken") + return + } + + // Decode token + token, err := jwt.Decode(split[1]) + if err != nil { + ctx.Error(400, "InvalidToken") + return + } + + // Select account + account, err := ctx.Database.Account.SelectByID(token.ID) + if err != nil { + ctx.Error(500, "InternalServerError") + return + } + + // Set account + ctx.Account = account +}