55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/farahty/go-mongo/models"
|
|
)
|
|
|
|
type contextKey struct {
|
|
name string
|
|
}
|
|
|
|
var (
|
|
UserKey = &contextKey{"user"}
|
|
StatusKey = &contextKey{"status"}
|
|
ExpiryKey = &contextKey{"expiry"}
|
|
LoadersKey = &contextKey{"dataloaders"}
|
|
)
|
|
|
|
// Retrieves the current user from the context
|
|
func CurrentUser(ctx context.Context) (*models.UserJWT, error) {
|
|
user, _ := ctx.Value(UserKey).(*models.UserJWT)
|
|
status, _ := ctx.Value(StatusKey).(string)
|
|
|
|
if status != "ok" {
|
|
return nil, fmt.Errorf("%s", status)
|
|
}
|
|
|
|
return user, nil
|
|
}
|
|
|
|
// Check if the token was marked as expired
|
|
func IsTokenExpired(ctx context.Context) bool {
|
|
if expired, ok := ctx.Value(ExpiryKey).(bool); ok {
|
|
return expired
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Sets the status in context (e.g., "ok" or error message)
|
|
func SetStatus(ctx context.Context, data any) context.Context {
|
|
return context.WithValue(ctx, StatusKey, data)
|
|
}
|
|
|
|
// Sets the authenticated user into the context
|
|
func SetCurrentUser(ctx context.Context, user *models.UserJWT) context.Context {
|
|
return context.WithValue(ctx, UserKey, user)
|
|
}
|
|
|
|
// Marks the token as expired in the context
|
|
func SetTokenExpired(ctx context.Context, expiry bool) context.Context {
|
|
return context.WithValue(ctx, ExpiryKey, expiry)
|
|
}
|