green_dot Context (ctx)
The context object (ctx
) is a fundamental part of Green Dot that stores contextual information about a request. It’s scoped to a request and is carried throughout the request’s lifetime in the backend.
Basic Usage
Section titled “Basic Usage”async main(ctx, input) { // User information ctx.user // Current user object ctx.role // User's role ctx.permissions // User's permissions
// Database access ctx.db // Database instance ctx.dbs.myDb // Access specific database
// Error handling ctx.error // Error factory
// Get full user object const user = await ctx.getUser()
// Throw errors with context if(!user.isAdmin) throw ctx.error.myCustomError({ userId: user._id })
// API information ctx.api // Request information}
Context Properties
Section titled “Context Properties”User Information
Section titled “User Information”_id
: User ID (or public/system ID for anonymous users)role
: User’s role (e.g., ‘admin’, ‘user’, ‘public’)permissions
: User’s permissions object ({ isAdmin, hasEmailValidated...}
)authenticationMethod
: Array of authentication methods used. Eg: one or multiple of['accessToken', '2FA', 'biometricAuthToken', 'pincode', 'apiKey']
isPublic
: Boolean indicating if user is not logged inisSystem
: Boolean indicating if context has system privilegesplatform
: Platform identifier (e.g., ‘web’, ‘mobile’)
Access and permissions
Section titled “Access and permissions”GM
(god mode) ctx.GM returns a system ctx with all privileges
Database Access
Section titled “Database Access”db
: Default database instancedbs
: Object containing all database instancestransactionSession
: MongoDB transaction session (if active)
API Information
Section titled “API Information”api.params
: Route parametersapi.body
: Request bodyapi.query
: Query parametersapi.originalUrl
: Original request URLapi.ipAdress
: Client IP addressapi.req
: Express request objectapi.res
: Express response objectapi.outputType
: Response output type configuration
Environment
Section titled “Environment”env
: Current environment (dev, prod, preprod)debugMode
: Debug mode flag
Context Methods
Section titled “Context Methods”User Management
Section titled “User Management”// Get full user object (cached)const user = await ctx.getUser({ refreshCache: false, // Whether to bypass cache errorIfNotSet: true // Whether to throw error if user not found})
// Clear user cachectx.clearUserCache()
// Check if user is anonymous (login via apiKey for example or public)const isAnonymous = ctx.isAnonymousUser()
Role Management
Section titled “Role Management”// Check if user has specific roleconst isAdmin = ctx.hasRole('admin')
// Use different rolectx.useRole('admin', { // Additional permissions canManageUsers: true})
// Create context from userctx.fromUser('admin', userObject)
Error Handling
Section titled “Error Handling”// Throw errors with contextthrow ctx.error.notFound({ resource: 'user' })throw ctx.error.forbidden({ action: 'delete' })throw ctx.error.myCustomError(anyHelpfulContextualInformations)
See error handling doc for how to create custom errors
NOTE: Be carreful when sending extra infos in errors because those information may leak in frontend
Context Cloning
Section titled “Context Cloning”// Clone context with modificationsconst newCtx = ctx.clone({ role: 'admin', permissions: { canManageUsers: true }})
Security Features
Section titled “Security Features”User Banning and warning
Section titled “User Banning and warning”// add user warning. At some configured number of warnings,// user will automatcally be banned for a configured period of time// (gd.app.config.ts)await ctx.addWarning()// Ban user for a configured period of time (gd.app.config.ts)await ctx.banUser()
Authentication Methods
Section titled “Authentication Methods”// This array will be filled with request authentication that have succeededconst methods = ctx.authenticationMethod // ['accessToken', '2FA', 'biometricAuthToken', 'pincode', 'apiKey']
Example Use Cases
Section titled “Example Use Cases”Role-Based Access Control
Section titled “Role-Based Access Control”async function deleteUser(ctx, userId) { if (!ctx.hasRole('admin')) { throw ctx.error.forbidden({ action: 'delete_user' }) } // Delete user logic}
User Management
Section titled “User Management”async function updateUserProfile(ctx, data) { const user = await ctx.getUser() if (user._id !== data.userId && !ctx.hasRole('admin')) { throw ctx.error.forbidden({ action: 'update_other_user' }) } // Update user logic}