feature: sending invitation link for newly created staff implemented.

This commit is contained in:
2026-04-30 12:55:39 +03:30
parent c39bd872bd
commit 1b8856f64e
10 changed files with 527 additions and 64 deletions

View File

@@ -135,7 +135,7 @@ export class AuthService {
});
// Transform memberships to include organization info and permissions
const organizations = user.memberships?.map(membership => ({
const organizations = this.toActiveOrganizations(user.memberships).map(membership => ({
id: membership.organization.id,
name: membership.organization.name,
type: membership.organization.type.name, // 'CLINIC' or 'LAB'
@@ -149,7 +149,7 @@ export class AuthService {
maxUsers: membership.organization.plan.maxUsers,
}
: undefined,
})) || [];
}));
return {
success: true,
@@ -342,7 +342,7 @@ export class AuthService {
const { passwordHash, ...result } = user;
// Transform memberships for frontend consumption
const organizations = user.memberships?.map(membership => ({
const organizations = this.toActiveOrganizations(user.memberships).map(membership => ({
id: membership.organization.id,
name: membership.organization.name,
type: membership.organization.type.name,
@@ -356,7 +356,7 @@ export class AuthService {
maxUsers: membership.organization.plan.maxUsers,
}
: undefined,
})) || [];
}));
return {
success: true,
@@ -462,7 +462,7 @@ export class AuthService {
});
// Transform memberships for response
const organizations = session.user.memberships?.map(membership => ({
const organizations = this.toActiveOrganizations(session.user.memberships).map(membership => ({
id: membership.organization.id,
name: membership.organization.name,
type: membership.organization.type.name,
@@ -476,7 +476,7 @@ export class AuthService {
maxUsers: membership.organization.plan.maxUsers,
}
: undefined,
})) || [];
}));
return {
success: true,
@@ -668,7 +668,7 @@ export class AuthService {
const { passwordHash, ...user } = session.user;
const organizations = session.user.memberships?.map(membership => ({
const organizations = this.toActiveOrganizations(session.user.memberships).map(membership => ({
id: membership.organization.id,
name: membership.organization.name,
type: membership.organization.type.name,
@@ -682,7 +682,7 @@ export class AuthService {
maxUsers: membership.organization.plan.maxUsers,
}
: undefined,
})) || [];
}));
return {
success: true,
@@ -722,6 +722,9 @@ export class AuthService {
if (!membership) {
throw new UnauthorizedException('Access denied to this organization');
}
if (!membership.isOwner && !membership.isActive) {
throw new UnauthorizedException('Your invitation is still pending activation');
}
// 2. Build payload WITH org context
const payload = {
@@ -763,6 +766,17 @@ export class AuthService {
};
}
private toActiveOrganizations(
memberships: Array<{
isOwner: boolean;
isActive: boolean;
organization: { id: string; name: string; type: { name: string }; plan?: { name: string; maxUsers: number } | null };
permissions?: Array<{ permission: { name: string } }>;
}> = [],
) {
return memberships.filter((m) => m.isOwner || m.isActive);
}
/**
* Owner-only subscription / seat alerts for the current org (from JWT).
* Used for a subtle warning indicator in the app shell (not staff-facing banners).
@@ -805,7 +819,10 @@ export class AuthService {
const plan = org.plan;
const maxUsers = plan.maxUsers;
const seatsUsed = await this.prisma.membership.count({
where: { organizationId: org.id },
where: {
organizationId: org.id,
OR: [{ isOwner: true }, { isActive: true }],
},
});
const unlimited = maxUsers >= 999999;

View File

@@ -0,0 +1,14 @@
import { IsString, MinLength } from 'class-validator';
export class AcceptStaffInviteDto {
@IsString()
token: string;
@IsString()
@MinLength(8)
password: string;
@IsString()
@MinLength(1)
name: string;
}

View File

@@ -0,0 +1,6 @@
import { IsString } from 'class-validator';
export class PreviewStaffInviteDto {
@IsString()
token: string;
}

View File

@@ -6,23 +6,38 @@ import {
Param,
Patch,
Post,
Query,
Req,
UseGuards,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { AcceptStaffInviteDto } from './dto/accept-staff-invite.dto';
import { InviteStaffDto } from './dto/invite-staff.dto';
import { PreviewStaffInviteDto } from './dto/preview-staff-invite.dto';
import { UpdateStaffMemberDto } from './dto/update-staff-member.dto';
import { StaffService } from './staff.service';
@ApiTags('staff')
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard)
@Controller('staff')
export class StaffController {
constructor(private readonly staffService: StaffService) {}
@Get('invitations/preview')
@ApiOperation({ summary: 'Preview invite info by token (public)' })
previewInvite(@Query() query: PreviewStaffInviteDto) {
return this.staffService.previewInvite(query.token);
}
@Post('invitations/accept')
@ApiOperation({ summary: 'Accept invite and activate account (public)' })
acceptInvite(@Body() dto: AcceptStaffInviteDto) {
return this.staffService.acceptInvite(dto);
}
@Get()
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'List organization members (requires TAB_STAFF_READ or owner)' })
list(@Req() req: { user: { id: string; organizationId?: string } }) {
const organizationId = this.staffService.getOrganizationIdFromUser(req.user);
@@ -30,6 +45,7 @@ export class StaffController {
}
@Post('invite')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Invite staff (requires TAB_STAFF_EDIT or owner)' })
invite(
@Req() req: { user: { id: string; organizationId?: string } },
@@ -40,6 +56,7 @@ export class StaffController {
}
@Patch('members/:membershipId')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Update staff member name and/or permissions' })
updateMember(
@Req() req: { user: { id: string; organizationId?: string } },
@@ -51,6 +68,7 @@ export class StaffController {
}
@Delete('members/:membershipId')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Remove staff member from organization' })
removeMember(
@Req() req: { user: { id: string; organizationId?: string } },

View File

@@ -6,8 +6,9 @@ import {
NotFoundException,
} from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { randomBytes } from 'crypto';
import { createHash, randomBytes } from 'crypto';
import { PrismaService } from '../../../prisma/prisma.service';
import { AcceptStaffInviteDto } from './dto/accept-staff-invite.dto';
import { isUnlimitedSeats, normalizeTabPermissions } from '../../common/permissions';
import { InviteStaffDto } from './dto/invite-staff.dto';
import { UpdateStaffMemberDto } from './dto/update-staff-member.dto';
@@ -43,10 +44,19 @@ export class StaffService {
include: {
user: { select: { id: true, email: true, name: true } },
permissions: { include: { permission: true } },
invitations: {
orderBy: { createdAt: 'desc' },
take: 1,
},
},
orderBy: [{ isOwner: 'desc' }, { createdAt: 'asc' }],
}),
this.prisma.membership.count({ where: { organizationId } }),
this.prisma.membership.count({
where: {
organizationId,
OR: [{ isOwner: true }, { isActive: true }],
},
}),
]);
const maxUsers = org.plan.maxUsers;
@@ -61,6 +71,10 @@ export class StaffService {
email: m.user.email,
name: m.user.name,
isOwner: m.isOwner,
isActive: m.isOwner ? true : m.isActive,
invitationStatus: this.getInvitationStatus(m),
invitedAt: m.invitations[0]?.createdAt?.toISOString() || null,
acceptedAt: m.invitations[0]?.acceptedAt?.toISOString() || null,
permissions: m.isOwner
? null
: m.permissions.map((p) => p.permission.name),
@@ -93,7 +107,8 @@ export class StaffService {
throw new BadRequestException(`Unknown or invalid permissions: ${missing.join(', ')}`);
}
let temporaryPassword: string | null = null;
const plainToken = this.generateInviteToken();
const tokenHash = this.hashInviteToken(plainToken);
const result = await this.prisma.$transaction(async (tx) => {
const org = await tx.organization.findUnique({
@@ -105,7 +120,12 @@ export class StaffService {
}
const maxUsers = org.plan.maxUsers;
const seatsUsed = await tx.membership.count({ where: { organizationId } });
const seatsUsed = await tx.membership.count({
where: {
organizationId,
OR: [{ isOwner: true }, { isActive: true }],
},
});
if (!isUnlimitedSeats(maxUsers) && seatsUsed >= maxUsers) {
throw new BadRequestException(
`Your plan allows ${maxUsers} team members. Remove a member or upgrade to add more.`,
@@ -132,13 +152,11 @@ export class StaffService {
}
targetUserId = existingUser.id;
} else {
temporaryPassword = randomBytes(18).toString('base64url').slice(0, 20);
const passwordHash = await bcrypt.hash(temporaryPassword, 10);
const created = await tx.user.create({
data: {
email,
name: dto.name.trim(),
passwordHash,
passwordHash: null,
},
});
targetUserId = created.id;
@@ -149,6 +167,7 @@ export class StaffService {
userId: targetUserId,
organizationId,
isOwner: false,
isActive: existingUser ? true : false,
},
});
@@ -161,7 +180,29 @@ export class StaffService {
});
}
return { membershipId: membership.id, userId: targetUserId };
let inviteUrl: string | null = null;
let invitationId: string | null = null;
if (!existingUser) {
const invitation = await tx.staffInvitation.create({
data: {
membershipId: membership.id,
invitedById: userId,
tokenHash,
expiresAt: this.getInviteExpiryDate(),
},
});
invitationId = invitation.id;
inviteUrl = this.buildInviteUrl(plainToken);
}
return {
membershipId: membership.id,
userId: targetUserId,
invitationId,
inviteUrl,
isPending: !existingUser,
};
});
return {
@@ -170,11 +211,69 @@ export class StaffService {
membershipId: result.membershipId,
userId: result.userId,
email,
temporaryPassword,
invitationId: result.invitationId,
invitationUrl: result.inviteUrl,
invitationStatus: result.isPending ? 'PENDING' : 'ACCEPTED',
},
};
}
async previewInvite(token: string) {
const invitation = await this.findValidInvitation(token);
const org = invitation.membership.organization;
const user = invitation.membership.user;
return {
success: true,
data: {
email: user.email,
name: user.name,
organizationName: org.name,
expiresAt: invitation.expiresAt.toISOString(),
status: invitation.acceptedAt ? 'ACCEPTED' : 'PENDING',
},
};
}
async acceptInvite(dto: AcceptStaffInviteDto) {
const invitation = await this.findValidInvitation(dto.token);
if (invitation.acceptedAt) {
throw new BadRequestException('This invitation has already been accepted');
}
const passwordHash = await bcrypt.hash(dto.password, 10);
const now = new Date();
await this.prisma.$transaction(async (tx) => {
await tx.user.update({
where: { id: invitation.membership.userId },
data: {
passwordHash,
name: dto.name.trim(),
},
});
await tx.membership.update({
where: { id: invitation.membershipId },
data: { isActive: true },
});
await tx.staffInvitation.update({
where: { id: invitation.id },
data: { acceptedAt: now },
});
});
return {
success: true,
data: {
email: invitation.membership.user.email,
},
message: 'Invitation accepted. You can now log in.',
};
}
async updateMember(
actorUserId: string,
organizationId: string,
@@ -267,6 +366,62 @@ export class StaffService {
});
}
private getInvitationStatus(m: {
isOwner: boolean;
isActive: boolean;
invitations: { acceptedAt: Date | null; revokedAt: Date | null; expiresAt: Date }[];
}): 'ACTIVE' | 'PENDING' | 'EXPIRED' {
if (m.isOwner || m.isActive) return 'ACTIVE';
const invitation = m.invitations[0];
if (!invitation) return 'EXPIRED';
if (invitation.acceptedAt || invitation.revokedAt) return 'ACTIVE';
return invitation.expiresAt.getTime() > Date.now() ? 'PENDING' : 'EXPIRED';
}
private generateInviteToken(): string {
return randomBytes(32).toString('hex');
}
private hashInviteToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
private getInviteExpiryDate(): Date {
const d = new Date();
d.setDate(d.getDate() + 7);
return d;
}
private buildInviteUrl(token: string): string {
const appUrl = process.env.FRONTEND_URL || 'http://localhost:3001';
return `${appUrl}/accept-invite?token=${encodeURIComponent(token)}`;
}
private async findValidInvitation(token: string) {
const invitation = await this.prisma.staffInvitation.findUnique({
where: { tokenHash: this.hashInviteToken(token) },
include: {
membership: {
include: {
user: { select: { id: true, email: true, name: true } },
organization: { select: { id: true, name: true } },
},
},
},
});
if (!invitation) {
throw new NotFoundException('Invitation not found');
}
if (invitation.revokedAt) {
throw new BadRequestException('Invitation has been revoked');
}
if (invitation.expiresAt.getTime() <= Date.now()) {
throw new BadRequestException('Invitation has expired');
}
return invitation;
}
private canViewStaff(m: {
isOwner: boolean;
permissions: { permission: { name: string } }[];