also looking at this
Deploy: uniform auth session model (main → production)
#7
282 files
+3028
-64856
| @@ -1,617 +0,0 @@ | ||
| 1 | # Manage Team | |
| 2 | ||
| 3 | This guide covers team collaboration features in Stacks, including user management, access control, role-based permissions, and team communication. | |
| 4 | ||
| 5 | ## Getting Started | |
| 6 | ||
| 7 | Import the team management functionality: | |
| 8 | ||
| 9 | ```ts | |
| 10 | import { Team, TeamMember, User } from '@stacksjs/orm' | |
| 11 | ``` | |
| 12 | ||
| 13 | ## User Management | |
| 14 | ||
| 15 | ### Inviting Team Members | |
| 16 | ||
| 17 | ```ts | |
| 18 | import { TeamInvitation } from '@stacksjs/orm' | |
| 19 | import { randomUUIDv7 } from 'bun' | |
| 20 | ||
| 21 | async function inviteTeamMember( | |
| 22 | teamId: number, | |
| 23 | email: string, | |
| 24 | role: string, | |
| 25 | invitedBy: number | |
| 26 | ) { | |
| 27 | // Check if already a member | |
| 28 | const existingMember = await TeamMember | |
| 29 | .where('team_id', '=', teamId) | |
| 30 | .where('email', '=', email) | |
| 31 | .first() | |
| 32 | ||
| 33 | if (existingMember) { | |
| 34 | throw new Error('User is already a team member') | |
| 35 | } | |
| 36 | ||
| 37 | // Check for pending invitation | |
| 38 | const existingInvite = await TeamInvitation | |
| 39 | .where('team_id', '=', teamId) | |
| 40 | .where('email', '=', email) | |
| 41 | .where('status', '=', 'pending') | |
| 42 | .first() | |
| 43 | ||
| 44 | if (existingInvite) { | |
| 45 | throw new Error('Invitation already sent to this email') | |
| 46 | } | |
| 47 | ||
| 48 | // Create invitation | |
| 49 | const invitation = await TeamInvitation.create({ | |
| 50 | team_id: teamId, | |
| 51 | email, | |
| 52 | role, | |
| 53 | invited_by: invitedBy, | |
| 54 | token: randomUUIDv7(), | |
| 55 | status: 'pending', | |
| 56 | expires_at: new Date(Date.now() + 7 _ 24 _ 60 _ 60 _ 1000).toISOString(), | |
| 57 | }) | |
| 58 | ||
| 59 | // Send invitation email | |
| 60 | await sendInvitationEmail({ | |
| 61 | to: email, | |
| 62 | inviteUrl: `${process.env.APP_URL}/invitations/${invitation.token}`, | |
| 63 | teamName: (await Team.find(teamId))?.name, | |
| 64 | inviterName: (await User.find(invitedBy))?.name, | |
| 65 | }) | |
| 66 | ||
| 67 | return invitation | |
| 68 | } | |
| 69 | ``` | |
| 70 | ||
| 71 | ### Accepting Invitations | |
| 72 | ||
| 73 | ```ts | |
| 74 | async function acceptInvitation(token: string, userId: number) { | |
| 75 | const invitation = await TeamInvitation | |
| 76 | .where('token', '=', token) | |
| 77 | .where('status', '=', 'pending') | |
| 78 | .first() | |
| 79 | ||
| 80 | if (!invitation) { | |
| 81 | throw new Error('Invalid or expired invitation') | |
| 82 | } | |
| 83 | ||
| 84 | // Check expiry | |
| 85 | if (new Date(invitation.expires_at) < new Date()) { | |
| 86 | await invitation.update({ status: 'expired' }) | |
| 87 | throw new Error('Invitation has expired') | |
| 88 | } | |
| 89 | ||
| 90 | // Get user | |
| 91 | const user = await User.find(userId) | |
| 92 | ||
| 93 | if (!user) { | |
| 94 | throw new Error('User not found') | |
| 95 | } | |
| 96 | ||
| 97 | // Add to team | |
| 98 | await TeamMember.create({ | |
| 99 | team_id: invitation.team_id, | |
| 100 | user_id: userId, | |
| 101 | role: invitation.role, | |
| 102 | joined_at: new Date().toISOString(), | |
| 103 | }) | |
| 104 | ||
| 105 | // Update invitation status | |
| 106 | await invitation.update({ status: 'accepted' }) | |
| 107 | ||
| 108 | return { | |
| 109 | team: await Team.find(invitation.team_id), | |
| 110 | role: invitation.role, | |
| 111 | } | |
| 112 | } | |
| 113 | ``` | |
| 114 | ||
| 115 | ### Removing Team Members | |
| 116 | ||
| 117 | ```ts | |
| 118 | async function removeTeamMember( | |
| 119 | teamId: number, | |
| 120 | userId: number, | |
| 121 | removedBy: number | |
| 122 | ) { | |
| 123 | // Check if remover has permission | |
| 124 | const remover = await TeamMember | |
| 125 | .where('team_id', '=', teamId) | |
| 126 | .where('user_id', '=', removedBy) | |
| 127 | .first() | |
| 128 | ||
| 129 | if (!remover || !['owner', 'admin'].includes(remover.role)) { | |
| 130 | throw new Error('You do not have permission to remove team members') | |
| 131 | } | |
| 132 | ||
| 133 | // Cannot remove owner | |
| 134 | const memberToRemove = await TeamMember | |
| 135 | .where('team_id', '=', teamId) | |
| 136 | .where('user_id', '=', userId) | |
| 137 | .first() | |
| 138 | ||
| 139 | if (memberToRemove?.role === 'owner') { | |
| 140 | throw new Error('Cannot remove the team owner') | |
| 141 | } | |
| 142 | ||
| 143 | // Remove member | |
| 144 | await TeamMember | |
| 145 | .where('team_id', '=', teamId) | |
| 146 | .where('user_id', '=', userId) | |
| 147 | .delete() | |
| 148 | ||
| 149 | // Notify the removed user | |
| 150 | await sendNotification({ | |
| 151 | userId, | |
| 152 | type: 'team_removed', | |
| 153 | message: `You have been removed from the team`, | |
| 154 | }) | |
| 155 | ||
| 156 | return { success: true } | |
| 157 | } | |
| 158 | ``` | |
| 159 | ||
| 160 | ## Access Control | |
| 161 | ||
| 162 | ### Role-Based Permissions | |
| 163 | ||
| 164 | ```ts | |
| 165 | // config/team.ts | |
| 166 | export default { | |
| 167 | roles: { | |
| 168 | owner: { | |
| 169 | name: 'Owner', | |
| 170 | permissions: ['_'], | |
| 171 | canBeRemoved: false, | |
| 172 | canBeChanged: false, | |
| 173 | }, | |
| 174 | admin: { | |
| 175 | name: 'Administrator', | |
| 176 | permissions: [ | |
| 177 | 'team:manage', | |
| 178 | 'members:invite', | |
| 179 | 'members:remove', | |
| 180 | 'members:update', | |
| 181 | 'projects:manage', | |
| 182 | 'billing:view', | |
| 183 | 'billing:manage', | |
| 184 | 'settings:manage', | |
| 185 | ], | |
| 186 | }, | |
| 187 | manager: { | |
| 188 | name: 'Manager', | |
| 189 | permissions: [ | |
| 190 | 'team:view', | |
| 191 | 'members:invite', | |
| 192 | 'projects:manage', | |
| 193 | 'billing:view', | |
| 194 | ], | |
| 195 | }, | |
| 196 | member: { | |
| 197 | name: 'Member', | |
| 198 | permissions: [ | |
| 199 | 'team:view', | |
| 200 | 'projects:view', | |
| 201 | 'projects:create', | |
| 202 | 'projects:edit', | |
| 203 | ], | |
| 204 | }, | |
| 205 | viewer: { | |
| 206 | name: 'Viewer', | |
| 207 | permissions: [ | |
| 208 | 'team:view', | |
| 209 | 'projects:view', | |
| 210 | ], | |
| 211 | }, | |
| 212 | }, | |
| 213 | } | |
| 214 | ``` | |
| 215 | ||
| 216 | ### Permission Checking | |
| 217 | ||
| 218 | ```ts | |
| 219 | import { config } from '@stacksjs/config' | |
| 220 | ||
| 221 | async function hasPermission( | |
| 222 | userId: number, | |
| 223 | teamId: number, | |
| 224 | permission: string | |
| 225 | ): Promise<boolean> { | |
| 226 | const member = await TeamMember | |
| 227 | .where('team_id', '=', teamId) | |
| 228 | .where('user_id', '=', userId) | |
| 229 | .first() | |
| 230 | ||
| 231 | if (!member) return false | |
| 232 | ||
| 233 | const roleConfig = config.team.roles[member.role] | |
| 234 | if (!roleConfig) return false | |
| 235 | ||
| 236 | // Wildcard permission (owner) | |
| 237 | if (roleConfig.permissions.includes('_')) return true | |
| 238 | ||
| 239 | // Check specific permission | |
| 240 | if (roleConfig.permissions.includes(permission)) return true | |
| 241 | ||
| 242 | // Check permission prefix (e.g., 'projects:_' matches 'projects:create') | |
| 243 | const [resource] = permission.split(':') | |
| 244 | if (roleConfig.permissions.includes(`${resource}:_`)) return true | |
| 245 | ||
| 246 | return false | |
| 247 | } | |
| 248 | ||
| 249 | // Usage in actions | |
| 250 | async function updateProject(userId: number, teamId: number, projectId: number, data: any) { | |
| 251 | const canEdit = await hasPermission(userId, teamId, 'projects:edit') | |
| 252 | ||
| 253 | if (!canEdit) { | |
| 254 | throw new Error('You do not have permission to edit projects') | |
| 255 | } | |
| 256 | ||
| 257 | return Project.where('id', '=', projectId).update(data) | |
| 258 | } | |
| 259 | ``` | |
| 260 | ||
| 261 | ### Permission Middleware | |
| 262 | ||
| 263 | ```ts | |
| 264 | // middleware/TeamPermission.ts | |
| 265 | export function requirePermission(permission: string) { | |
| 266 | return async (request: Request, next: Function) => { | |
| 267 | const user = request.user | |
| 268 | const teamId = request.params.teamId || request.body.team_id | |
| 269 | ||
| 270 | if (!teamId) { | |
| 271 | return Response.json({ error: 'Team ID required' }, { status: 400 }) | |
| 272 | } | |
| 273 | ||
| 274 | const allowed = await hasPermission(user.id, parseInt(teamId), permission) | |
| 275 | ||
| 276 | if (!allowed) { | |
| 277 | return Response.json({ error: 'Permission denied' }, { status: 403 }) | |
| 278 | } | |
| 279 | ||
| 280 | return next() | |
| 281 | } | |
| 282 | } | |
| 283 | ||
| 284 | // Usage in routes | |
| 285 | router.put( | |
| 286 | '/teams/:teamId/settings', | |
| 287 | requirePermission('settings:manage'), | |
| 288 | updateTeamSettings | |
| 289 | ) | |
| 290 | ``` | |
| 291 | ||
| 292 | ## Team Settings | |
| 293 | ||
| 294 | ### Updating Team Information | |
| 295 | ||
| 296 | ```ts | |
| 297 | async function updateTeamSettings( | |
| 298 | teamId: number, | |
| 299 | userId: number, | |
| 300 | settings: { | |
| 301 | name?: string | |
| 302 | description?: string | |
| 303 | logo?: string | |
| 304 | timezone?: string | |
| 305 | settings?: Record<string, any> | |
| 306 | } | |
| 307 | ) { | |
| 308 | // Check permission | |
| 309 | const canManage = await hasPermission(userId, teamId, 'settings:manage') | |
| 310 | ||
| 311 | if (!canManage) { | |
| 312 | throw new Error('You do not have permission to manage team settings') | |
| 313 | } | |
| 314 | ||
| 315 | const team = await Team.find(teamId) | |
| 316 | ||
| 317 | if (!team) { | |
| 318 | throw new Error('Team not found') | |
| 319 | } | |
| 320 | ||
| 321 | await team.update({ | |
| 322 | name: settings.name || team.name, | |
| 323 | description: settings.description || team.description, | |
| 324 | logo: settings.logo || team.logo, | |
| 325 | timezone: settings.timezone || team.timezone, | |
| 326 | settings: JSON.stringify({ | |
| 327 | ...JSON.parse(team.settings || '{}'), | |
| 328 | ...settings.settings, | |
| 329 | }), | |
| 330 | }) | |
| 331 | ||
| 332 | return team | |
| 333 | } | |
| 334 | ``` | |
| 335 | ||
| 336 | ### Team Preferences | |
| 337 | ||
| 338 | ```ts | |
| 339 | async function getTeamPreferences(teamId: number) { | |
| 340 | const team = await Team.find(teamId) | |
| 341 | ||
| 342 | if (!team) throw new Error('Team not found') | |
| 343 | ||
| 344 | return JSON.parse(team.settings || '{}') | |
| 345 | } | |
| 346 | ||
| 347 | async function updateTeamPreference( | |
| 348 | teamId: number, | |
| 349 | key: string, | |
| 350 | value: any | |
| 351 | ) { | |
| 352 | const team = await Team.find(teamId) | |
| 353 | ||
| 354 | if (!team) throw new Error('Team not found') | |
| 355 | ||
| 356 | const settings = JSON.parse(team.settings || '{}') | |
| 357 | settings[key] = value | |
| 358 | ||
| 359 | await team.update({ settings: JSON.stringify(settings) }) | |
| 360 | ||
| 361 | return settings | |
| 362 | } | |
| 363 | ``` | |
| 364 | ||
| 365 | ## Role Management | |
| 366 | ||
| 367 | ### Updating Member Roles | |
| 368 | ||
| 369 | ```ts | |
| 370 | async function updateMemberRole( | |
| 371 | teamId: number, | |
| 372 | memberId: number, | |
| 373 | newRole: string, | |
| 374 | updatedBy: number | |
| 375 | ) { | |
| 376 | // Check permission | |
| 377 | const canUpdate = await hasPermission(updatedBy, teamId, 'members:update') | |
| 378 | ||
| 379 | if (!canUpdate) { | |
| 380 | throw new Error('You do not have permission to update member roles') | |
| 381 | } | |
| 382 | ||
| 383 | // Get member to update | |
| 384 | const member = await TeamMember | |
| 385 | .where('team_id', '=', teamId) | |
| 386 | .where('user_id', '=', memberId) | |
| 387 | .first() | |
| 388 | ||
| 389 | if (!member) { | |
| 390 | throw new Error('Team member not found') | |
| 391 | } | |
| 392 | ||
| 393 | // Cannot change owner role | |
| 394 | if (member.role === 'owner') { | |
| 395 | throw new Error('Cannot change the owner role') | |
| 396 | } | |
| 397 | ||
| 398 | // Validate new role exists | |
| 399 | if (!config.team.roles[newRole]) { | |
| 400 | throw new Error('Invalid role') | |
| 401 | } | |
| 402 | ||
| 403 | // Cannot promote to owner | |
| 404 | if (newRole === 'owner') { | |
| 405 | throw new Error('Cannot promote to owner') | |
| 406 | } | |
| 407 | ||
| 408 | await member.update({ role: newRole }) | |
| 409 | ||
| 410 | // Notify member of role change | |
| 411 | await sendNotification({ | |
| 412 | userId: memberId, | |
| 413 | type: 'role_changed', | |
| 414 | message: `Your role has been changed to ${config.team.roles[newRole].name}`, | |
| 415 | }) | |
| 416 | ||
| 417 | return member | |
| 418 | } | |
| 419 | ``` | |
| 420 | ||
| 421 | ### Transferring Ownership | |
| 422 | ||
| 423 | ```ts | |
| 424 | async function transferOwnership( | |
| 425 | teamId: number, | |
| 426 | newOwnerId: number, | |
| 427 | currentOwnerId: number | |
| 428 | ) { | |
| 429 | // Verify current owner | |
| 430 | const currentOwner = await TeamMember | |
| 431 | .where('team_id', '=', teamId) | |
| 432 | .where('user_id', '=', currentOwnerId) | |
| 433 | .where('role', '=', 'owner') | |
| 434 | .first() | |
| 435 | ||
| 436 | if (!currentOwner) { | |
| 437 | throw new Error('You are not the team owner') | |
| 438 | } | |
| 439 | ||
| 440 | // Verify new owner is a team member | |
| 441 | const newOwner = await TeamMember | |
| 442 | .where('team_id', '=', teamId) | |
| 443 | .where('user_id', '=', newOwnerId) | |
| 444 | .first() | |
| 445 | ||
| 446 | if (!newOwner) { | |
| 447 | throw new Error('New owner must be a team member') | |
| 448 | } | |
| 449 | ||
| 450 | // Transfer ownership | |
| 451 | await currentOwner.update({ role: 'admin' }) | |
| 452 | await newOwner.update({ role: 'owner' }) | |
| 453 | ||
| 454 | // Notify both users | |
| 455 | await sendNotification({ | |
| 456 | userId: newOwnerId, | |
| 457 | type: 'ownership_received', | |
| 458 | message: 'You are now the team owner', | |
| 459 | }) | |
| 460 | ||
| 461 | await sendNotification({ | |
| 462 | userId: currentOwnerId, | |
| 463 | type: 'ownership_transferred', | |
| 464 | message: 'You have transferred team ownership', | |
| 465 | }) | |
| 466 | ||
| 467 | return { success: true } | |
| 468 | } | |
| 469 | ``` | |
| 470 | ||
| 471 | ## Activity Logging | |
| 472 | ||
| 473 | ### Logging Team Activities | |
| 474 | ||
| 475 | ```ts | |
| 476 | async function logTeamActivity( | |
| 477 | teamId: number, | |
| 478 | userId: number, | |
| 479 | action: string, | |
| 480 | details?: Record<string, any> | |
| 481 | ) { | |
| 482 | await TeamActivity.create({ | |
| 483 | team_id: teamId, | |
| 484 | user_id: userId, | |
| 485 | action, | |
| 486 | details: JSON.stringify(details || {}), | |
| 487 | ip_address: request.ip, | |
| 488 | user_agent: request.headers.get('user-agent'), | |
| 489 | created_at: new Date().toISOString(), | |
| 490 | }) | |
| 491 | } | |
| 492 | ||
| 493 | // Usage | |
| 494 | await logTeamActivity(teamId, userId, 'member.invited', { | |
| 495 | invitedEmail: email, | |
| 496 | role: role, | |
| 497 | }) | |
| 498 | ||
| 499 | await logTeamActivity(teamId, userId, 'settings.updated', { | |
| 500 | changes: ['name', 'description'], | |
| 501 | }) | |
| 502 | ``` | |
| 503 | ||
| 504 | ### Viewing Activity Log | |
| 505 | ||
| 506 | ```ts | |
| 507 | async function getTeamActivityLog( | |
| 508 | teamId: number, | |
| 509 | options: { | |
| 510 | limit?: number | |
| 511 | offset?: number | |
| 512 | userId?: number | |
| 513 | action?: string | |
| 514 | } = {} | |
| 515 | ) { | |
| 516 | let query = TeamActivity | |
| 517 | .with(['user']) | |
| 518 | .where('team_id', '=', teamId) | |
| 519 | .orderBy('created_at', 'desc') | |
| 520 | ||
| 521 | if (options.userId) { | |
| 522 | query = query.where('user_id', '=', options.userId) | |
| 523 | } | |
| 524 | ||
| 525 | if (options.action) { | |
| 526 | query = query.where('action', 'like', `${options.action}%`) | |
| 527 | } | |
| 528 | ||
| 529 | const activities = await query | |
| 530 | .limit(options.limit || 50) | |
| 531 | .offset(options.offset || 0) | |
| 532 | .get() | |
| 533 | ||
| 534 | return activities.map(activity => ({ | |
| 535 | id: activity.id, | |
| 536 | user: activity.user?.name, | |
| 537 | action: activity.action, | |
| 538 | details: JSON.parse(activity.details || '{}'), | |
| 539 | createdAt: activity.created_at, | |
| 540 | })) | |
| 541 | } | |
| 542 | ``` | |
| 543 | ||
| 544 | ## API Endpoints | |
| 545 | ||
| 546 | ``` | |
| 547 | GET /api/teams/:teamId/members # List team members | |
| 548 | POST /api/teams/:teamId/members # Invite member | |
| 549 | DELETE /api/teams/:teamId/members/:userId # Remove member | |
| 550 | PATCH /api/teams/:teamId/members/:userId # Update member role | |
| 551 | ||
| 552 | GET /api/teams/:teamId/invitations # List pending invitations | |
| 553 | POST /api/teams/:teamId/invitations # Send invitation | |
| 554 | DELETE /api/teams/:teamId/invitations/:id # Cancel invitation | |
| 555 | POST /api/invitations/:token/accept # Accept invitation | |
| 556 | ||
| 557 | GET /api/teams/:teamId/settings # Get team settings | |
| 558 | PATCH /api/teams/:teamId/settings # Update team settings | |
| 559 | ||
| 560 | GET /api/teams/:teamId/activity # Get activity log | |
| 561 | ``` | |
| 562 | ||
| 563 | ### Example API Usage | |
| 564 | ||
| 565 | ```ts | |
| 566 | // Invite team member | |
| 567 | const response = await fetch(`/api/teams/${teamId}/members`, { | |
| 568 | method: 'POST', | |
| 569 | headers: { | |
| 570 | 'Content-Type': 'application/json', | |
| 571 | 'Authorization': `Bearer ${token}`, | |
| 572 | }, | |
| 573 | body: JSON.stringify({ | |
| 574 | email: 'newmember@example.com', | |
| 575 | role: 'member', | |
| 576 | }), | |
| 577 | }) | |
| 578 | ||
| 579 | // Update member role | |
| 580 | const response = await fetch(`/api/teams/${teamId}/members/${userId}`, { | |
| 581 | method: 'PATCH', | |
| 582 | headers: { | |
| 583 | 'Content-Type': 'application/json', | |
| 584 | 'Authorization': `Bearer ${token}`, | |
| 585 | }, | |
| 586 | body: JSON.stringify({ | |
| 587 | role: 'admin', | |
| 588 | }), | |
| 589 | }) | |
| 590 | ||
| 591 | // Get activity log | |
| 592 | const response = await fetch(`/api/teams/${teamId}/activity?limit=20`, { | |
| 593 | headers: { | |
| 594 | 'Authorization': `Bearer ${token}`, | |
| 595 | }, | |
| 596 | }) | |
| 597 | ``` | |
| 598 | ||
| 599 | ## Error Handling | |
| 600 | ||
| 601 | ```ts | |
| 602 | try { | |
| 603 | await inviteTeamMember(teamId, email, role, userId) | |
| 604 | } catch (error) { | |
| 605 | if (error.message.includes('already a team member')) { | |
| 606 | showError('This user is already on your team') | |
| 607 | } else if (error.message.includes('Invitation already sent')) { | |
| 608 | showError('An invitation has already been sent to this email') | |
| 609 | } else if (error.message.includes('permission')) { | |
| 610 | showError('You do not have permission to invite members') | |
| 611 | } else { | |
| 612 | showError('Failed to send invitation') | |
| 613 | } | |
| 614 | } | |
| 615 | ``` | |
| 616 | ||
| 617 | This documentation covers team collaboration and access control functionality. Each function is designed for secure and flexible team management. | |