init
This commit is contained in:
86
internal/contextutil/context.go
Normal file
86
internal/contextutil/context.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package contextutil
|
||||
|
||||
//Helpers for injecting and extracting data from request context
|
||||
//TODO : Make a bit more generic when a contextKey is added and magically there are functions for it
|
||||
|
||||
import "context"
|
||||
|
||||
type contextKey string
|
||||
|
||||
const IsAuthenticatedCtxKey = contextKey("isAuthenticated")
|
||||
const IsAdminCtxKey = contextKey("isAdmin")
|
||||
const AuthenticateUserIDCtxKey = contextKey("authenticatedUserID")
|
||||
const AuthenticatedUserNameCtxKey = contextKey("authenticatedUserName")
|
||||
const CSRFTokenCtxKey = contextKey("CSRFToken")
|
||||
|
||||
func IsAuth(ctx context.Context) bool {
|
||||
isAuthenticate, ok := ctx.Value(IsAuthenticatedCtxKey).(bool)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
return isAuthenticate
|
||||
}
|
||||
|
||||
func IsAdmin(ctx context.Context) bool {
|
||||
isAdmin, ok := ctx.Value(IsAdminCtxKey).(bool)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
return isAdmin
|
||||
}
|
||||
|
||||
// Extract userName from ctx
|
||||
func UserName(ctx context.Context) string {
|
||||
userName, ok := ctx.Value(AuthenticatedUserNameCtxKey).(string)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
return userName
|
||||
}
|
||||
|
||||
// Extract userID from ctx
|
||||
func UserID(ctx context.Context) int {
|
||||
userID, ok := ctx.Value(AuthenticateUserIDCtxKey).(int)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
|
||||
return userID
|
||||
}
|
||||
|
||||
func CSRFToken(ctx context.Context) string {
|
||||
csrfToken, ok := ctx.Value(CSRFTokenCtxKey).(string)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
return csrfToken
|
||||
}
|
||||
|
||||
// Add isAuth to ctx and return
|
||||
func WithIsAuth(ctx context.Context, isAuth bool) context.Context {
|
||||
return context.WithValue(ctx, IsAuthenticatedCtxKey, isAuth)
|
||||
}
|
||||
|
||||
// Add isAdmin to ctx and return
|
||||
func WithIsAdmin(ctx context.Context, isAdmin bool) context.Context {
|
||||
return context.WithValue(ctx, IsAdminCtxKey, isAdmin)
|
||||
}
|
||||
|
||||
// Add CSRFTokent to ctx and return
|
||||
func WithCSRFToken(ctx context.Context, token string) context.Context {
|
||||
return context.WithValue(ctx, CSRFTokenCtxKey, token)
|
||||
}
|
||||
|
||||
// Add AuthUserName to ctx and return
|
||||
func WithAuthUserName(ctx context.Context, userName string) context.Context {
|
||||
return context.WithValue(ctx, AuthenticatedUserNameCtxKey, userName)
|
||||
}
|
||||
|
||||
// Add AuthUserID to ctx and return
|
||||
func WithAuthUserID(ctx context.Context, userID int) context.Context {
|
||||
return context.WithValue(ctx, AuthenticateUserIDCtxKey, userID)
|
||||
}
|
||||
Reference in New Issue
Block a user