Skip to content

Commit

Permalink
soc
Browse files Browse the repository at this point in the history
  • Loading branch information
garrettladley committed May 25, 2024
1 parent 29e49c1 commit 1187dc9
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 46 deletions.
46 changes: 0 additions & 46 deletions backend/auth/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

"github.com/GenerateNU/sac/backend/config"
"github.com/GenerateNU/sac/backend/constants"
"github.com/google/uuid"

"github.com/GenerateNU/sac/backend/utilities"
m "github.com/garrettladley/mattress"
Expand All @@ -19,51 +18,6 @@ type CustomClaims struct {
Role string `json:"role"`
}

type localsKey byte

const (
claimsKey localsKey = 0
userIDKey localsKey = 1
)

// CustomClaimsFrom extracts the CustomClaims from the fiber context
// Returns nil if the claims are not present
func CustomClaimsFrom(c *fiber.Ctx) (*CustomClaims, error) {
rawClaims := c.Locals(claimsKey)
if rawClaims == nil {
return nil, utilities.Forbidden()
}

claims, ok := rawClaims.(*CustomClaims)
if !ok {
return nil, fmt.Errorf("claims are not of type CustomClaims. got: %T", rawClaims)
}

return claims, nil
}

func SetClaims(c *fiber.Ctx, claims *CustomClaims) {
c.Locals(claimsKey, claims)
}

func UserIDFrom(c *fiber.Ctx) (*uuid.UUID, error) {
userID := c.Locals(userIDKey)
if userID == nil {
return nil, utilities.Forbidden()
}

id, ok := userID.(*uuid.UUID)
if !ok {
return nil, fmt.Errorf("userID is not of type uuid.UUID. got: %T", userID)
}

return id, nil
}

func SetUserID(c *fiber.Ctx, id *uuid.UUID) {
c.Locals(userIDKey, id)
}

type JWTType string

const (
Expand Down
52 changes: 52 additions & 0 deletions backend/auth/locals.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package auth

import (
"fmt"

"github.com/GenerateNU/sac/backend/utilities"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)

type localsKey byte

const (
claimsKey localsKey = 0
userIDKey localsKey = 1
)

func CustomClaimsFrom(c *fiber.Ctx) (*CustomClaims, error) {
rawClaims := c.Locals(claimsKey)
if rawClaims == nil {
return nil, utilities.Forbidden()
}

claims, ok := rawClaims.(*CustomClaims)
if !ok {
return nil, fmt.Errorf("claims are not of type CustomClaims. got: %T", rawClaims)
}

return claims, nil
}

func SetClaims(c *fiber.Ctx, claims *CustomClaims) {
c.Locals(claimsKey, claims)
}

func UserIDFrom(c *fiber.Ctx) (*uuid.UUID, error) {
userID := c.Locals(userIDKey)
if userID == nil {
return nil, utilities.Forbidden()
}

id, ok := userID.(*uuid.UUID)
if !ok {
return nil, fmt.Errorf("userID is not of type uuid.UUID. got: %T", userID)
}

return id, nil
}

func SetUserID(c *fiber.Ctx, id *uuid.UUID) {
c.Locals(userIDKey, id)
}

0 comments on commit 1187dc9

Please sign in to comment.