|
| 1 | +--- |
| 2 | +title: Basic Examples |
| 3 | +description: Simple examples to get you started with Sequelize Guard. |
| 4 | +--- |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | +```typescript |
| 9 | +import { SequelizeGuard } from 'sequelize-guard'; |
| 10 | + |
| 11 | +async function registerUser( |
| 12 | + guard: SequelizeGuard, |
| 13 | + email: string, |
| 14 | + name: string, |
| 15 | +) { |
| 16 | + // Create user |
| 17 | + const user = await guard.users.createUser(email, { name }); |
| 18 | + |
| 19 | + // Get or create 'user' role |
| 20 | + let userRole = await guard.roles.getRole('user'); |
| 21 | + if (!userRole) { |
| 22 | + userRole = await guard.roles.createRole('user', 'Regular User'); |
| 23 | + } |
| 24 | + |
| 25 | + // Assign role to user |
| 26 | + await guard.users.assignRole(user.id, userRole.id); |
| 27 | + |
| 28 | + return user; |
| 29 | +} |
| 30 | + |
| 31 | +// Usage |
| 32 | +const newUser = await registerUser(guard, 'john@example.com', 'John Doe'); |
| 33 | +``` |
| 34 | + |
| 35 | +## Authorization Middleware |
| 36 | + |
| 37 | +```typescript |
| 38 | +async function requirePermission( |
| 39 | + guard: SequelizeGuard, |
| 40 | + userId: string, |
| 41 | + action: string, |
| 42 | + resource: string, |
| 43 | +) { |
| 44 | + const hasPermission = await guard.authorize.checkPermission( |
| 45 | + userId, |
| 46 | + action, |
| 47 | + resource, |
| 48 | + ); |
| 49 | + |
| 50 | + if (!hasPermission) { |
| 51 | + throw new Error(`User not authorized to ${action} ${resource}`); |
| 52 | + } |
| 53 | + |
| 54 | + return true; |
| 55 | +} |
| 56 | + |
| 57 | +// Usage |
| 58 | +try { |
| 59 | + await requirePermission(guard, userId, 'delete', 'posts'); |
| 60 | + // User is authorized, proceed with deletion |
| 61 | + await deletePost(postId); |
| 62 | +} catch (error) { |
| 63 | + console.error(error.message); |
| 64 | +} |
| 65 | +``` |
| 66 | + |
| 67 | +## Check Multiple Permissions |
| 68 | + |
| 69 | +```typescript |
| 70 | +async function canManagePost( |
| 71 | + guard: SequelizeGuard, |
| 72 | + userId: string, |
| 73 | +): Promise<{ |
| 74 | + canCreate: boolean; |
| 75 | + canUpdate: boolean; |
| 76 | + canDelete: boolean; |
| 77 | +}> { |
| 78 | + const [canCreate, canUpdate, canDelete] = await Promise.all([ |
| 79 | + guard.authorize.checkPermission(userId, 'create', 'posts'), |
| 80 | + guard.authorize.checkPermission(userId, 'update', 'posts'), |
| 81 | + guard.authorize.checkPermission(userId, 'delete', 'posts'), |
| 82 | + ]); |
| 83 | + |
| 84 | + return { canCreate, canUpdate, canDelete }; |
| 85 | +} |
| 86 | + |
| 87 | +// Usage |
| 88 | +const permissions = await canManagePost(guard, userId); |
| 89 | +console.log('User permissions:', permissions); |
| 90 | +``` |
| 91 | + |
| 92 | +## Role-Based Content Filtering |
| 93 | + |
| 94 | +```typescript |
| 95 | +import { Op } from 'sequelize'; |
| 96 | + |
| 97 | +async function getFilteredPosts( |
| 98 | + guard: SequelizeGuard, |
| 99 | + userId: string, |
| 100 | + Post: any, |
| 101 | +) { |
| 102 | + const isAdmin = await guard.authorize.checkRole(userId, 'admin'); |
| 103 | + |
| 104 | + if (isAdmin) { |
| 105 | + // Admin sees all posts |
| 106 | + return Post.findAll(); |
| 107 | + } |
| 108 | + |
| 109 | + const user = await guard.users.getUser(userId); |
| 110 | + |
| 111 | + // Regular users see only their own posts and published posts |
| 112 | + return Post.findAll({ |
| 113 | + where: { |
| 114 | + [Op.or]: [{ authorId: userId }, { status: 'published' }], |
| 115 | + }, |
| 116 | + }); |
| 117 | +} |
| 118 | +``` |
| 119 | + |
| 120 | +## Bulk Role Assignment |
| 121 | + |
| 122 | +```typescript |
| 123 | +async function assignRolesToUsers( |
| 124 | + guard: SequelizeGuard, |
| 125 | + userIds: string[], |
| 126 | + roleName: string, |
| 127 | +) { |
| 128 | + const role = await guard.roles.getRole(roleName); |
| 129 | + |
| 130 | + if (!role) { |
| 131 | + throw new Error(`Role ${roleName} not found`); |
| 132 | + } |
| 133 | + |
| 134 | + const results = await Promise.allSettled( |
| 135 | + userIds.map((userId) => guard.users.assignRole(userId, role.id)), |
| 136 | + ); |
| 137 | + |
| 138 | + const successful = results.filter((r) => r.status === 'fulfilled').length; |
| 139 | + const failed = results.filter((r) => r.status === 'rejected').length; |
| 140 | + |
| 141 | + return { successful, failed, total: userIds.length }; |
| 142 | +} |
| 143 | + |
| 144 | +// Usage |
| 145 | +const result = await assignRolesToUsers( |
| 146 | + guard, |
| 147 | + ['user1', 'user2', 'user3'], |
| 148 | + 'premium', |
| 149 | +); |
| 150 | +console.log(`Assigned role to ${result.successful}/${result.total} users`); |
| 151 | +``` |
| 152 | + |
| 153 | +## Permission Checking Utility |
| 154 | + |
| 155 | +```typescript |
| 156 | +class PermissionChecker { |
| 157 | + constructor(private guard: SequelizeGuard) {} |
| 158 | + |
| 159 | + async requireAll( |
| 160 | + userId: string, |
| 161 | + permissions: Array<{ action: string; resource: string }>, |
| 162 | + ): Promise<boolean> { |
| 163 | + const checks = await Promise.all( |
| 164 | + permissions.map((p) => |
| 165 | + this.guard.authorize.checkPermission(userId, p.action, p.resource), |
| 166 | + ), |
| 167 | + ); |
| 168 | + |
| 169 | + return checks.every((check) => check === true); |
| 170 | + } |
| 171 | + |
| 172 | + async requireAny( |
| 173 | + userId: string, |
| 174 | + permissions: Array<{ action: string; resource: string }>, |
| 175 | + ): Promise<boolean> { |
| 176 | + const checks = await Promise.all( |
| 177 | + permissions.map((p) => |
| 178 | + this.guard.authorize.checkPermission(userId, p.action, p.resource), |
| 179 | + ), |
| 180 | + ); |
| 181 | + |
| 182 | + return checks.some((check) => check === true); |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +// Usage |
| 187 | +const checker = new PermissionChecker(guard); |
| 188 | + |
| 189 | +// User must have ALL permissions |
| 190 | +const canFullyManage = await checker.requireAll(userId, [ |
| 191 | + { action: 'create', resource: 'posts' }, |
| 192 | + { action: 'update', resource: 'posts' }, |
| 193 | + { action: 'delete', resource: 'posts' }, |
| 194 | +]); |
| 195 | + |
| 196 | +// User must have AT LEAST ONE permission |
| 197 | +const canDoSomething = await checker.requireAny(userId, [ |
| 198 | + { action: 'update', resource: 'posts' }, |
| 199 | + { action: 'delete', resource: 'posts' }, |
| 200 | +]); |
| 201 | +``` |
| 202 | + |
| 203 | +## Temporary Role Assignment |
| 204 | + |
| 205 | +```typescript |
| 206 | +async function grantTemporaryRole( |
| 207 | + guard: SequelizeGuard, |
| 208 | + userId: string, |
| 209 | + roleName: string, |
| 210 | + durationMs: number, |
| 211 | +): Promise<() => Promise<void>> { |
| 212 | + const role = await guard.roles.getRole(roleName); |
| 213 | + await guard.users.assignRole(userId, role.id); |
| 214 | + |
| 215 | + // Return cleanup function |
| 216 | + return async () => { |
| 217 | + await guard.users.removeRole(userId, role.id); |
| 218 | + }; |
| 219 | +} |
| 220 | + |
| 221 | +// Usage |
| 222 | +const cleanup = await grantTemporaryRole( |
| 223 | + guard, |
| 224 | + userId, |
| 225 | + 'moderator', |
| 226 | + 24 * 60 * 60 * 1000, // 24 hours |
| 227 | +); |
| 228 | + |
| 229 | +// After some time or on app shutdown |
| 230 | +setTimeout(cleanup, 24 * 60 * 60 * 1000); |
| 231 | +``` |
| 232 | + |
| 233 | +## User Permission Summary |
| 234 | + |
| 235 | +```typescript |
| 236 | +async function getUserPermissionSummary(guard: SequelizeGuard, userId: string) { |
| 237 | + const user = await guard.users.getUserWithRoles(userId); |
| 238 | + |
| 239 | + const allPermissions = new Set<string>(); |
| 240 | + |
| 241 | + for (const role of user.roles) { |
| 242 | + const roleWithPerms = await guard.roles.getRoleWithPermissions(role.name); |
| 243 | + |
| 244 | + for (const permission of roleWithPerms.permissions) { |
| 245 | + allPermissions.add(`${permission.action}:${permission.resource}`); |
| 246 | + } |
| 247 | + } |
| 248 | + |
| 249 | + return { |
| 250 | + userId: user.id, |
| 251 | + email: user.email, |
| 252 | + roles: user.roles.map((r) => r.name), |
| 253 | + permissions: Array.from(allPermissions), |
| 254 | + totalPermissions: allPermissions.size, |
| 255 | + }; |
| 256 | +} |
| 257 | + |
| 258 | +// Usage |
| 259 | +const summary = await getUserPermissionSummary(guard, userId); |
| 260 | +console.log(JSON.stringify(summary, null, 2)); |
| 261 | +``` |
| 262 | + |
| 263 | +## Resource-Specific Authorization |
| 264 | + |
| 265 | +```typescript |
| 266 | +async function authorizeResourceAccess( |
| 267 | + guard: SequelizeGuard, |
| 268 | + userId: string, |
| 269 | + action: string, |
| 270 | + resourceType: string, |
| 271 | + resourceId: string, |
| 272 | + Resource: any, |
| 273 | +) { |
| 274 | + // Check general permission |
| 275 | + const hasGeneralPermission = await guard.authorize.checkPermission( |
| 276 | + userId, |
| 277 | + action, |
| 278 | + resourceType, |
| 279 | + ); |
| 280 | + |
| 281 | + if (!hasGeneralPermission) { |
| 282 | + return false; |
| 283 | + } |
| 284 | + |
| 285 | + // Check resource ownership |
| 286 | + const resource = await Resource.findByPk(resourceId); |
| 287 | + |
| 288 | + if (!resource) { |
| 289 | + throw new Error('Resource not found'); |
| 290 | + } |
| 291 | + |
| 292 | + // Allow if user is owner or admin |
| 293 | + const isAdmin = await guard.authorize.checkRole(userId, 'admin'); |
| 294 | + const isOwner = resource.ownerId === userId; |
| 295 | + |
| 296 | + return isAdmin || isOwner; |
| 297 | +} |
| 298 | + |
| 299 | +// Usage |
| 300 | +const canEdit = await authorizeResourceAccess( |
| 301 | + guard, |
| 302 | + userId, |
| 303 | + 'update', |
| 304 | + 'documents', |
| 305 | + documentId, |
| 306 | + Document, |
| 307 | +); |
| 308 | +``` |
| 309 | + |
| 310 | +## Next Steps |
| 311 | + |
| 312 | +- [Express.js Integration](/examples/express) |
| 313 | +- [NestJS Integration](/examples/nestjs) |
| 314 | +- [Advanced Use Cases](/examples/advanced) |
0 commit comments