go-mongo/app/app-context.go

64 lines
1.5 KiB
Go

package app
import (
"context"
"fmt"
"net/http"
"git.farahty.com/nimer/go-mongo/models"
)
type contextKey struct {
name string
}
var (
UserKey = &contextKey{"user"}
StatusKey = &contextKey{"status"}
ExpiryKey = &contextKey{"expiry"}
LoadersKey = &contextKey{"dataloaders"}
WriterKye = &contextKey{"writer"}
)
func WriterFor(ctx context.Context) (*http.ResponseWriter, error) {
if writer, ok := ctx.Value(WriterKye).(*http.ResponseWriter); ok {
return writer, nil
}
return nil, fmt.Errorf("no writer found in context")
}
// 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)
}