Initial commit: Full project structure

- Backend: NestJS with Docker
- Frontend: Next.js with Docker
- Nginx configuration for reverse proxy
- PostgreSQL setup
- Docker compose for orchestration
- Development environment configuration
This commit is contained in:
2026-04-23 15:33:11 +03:30
commit 26bd35ae3c
94 changed files with 5627 additions and 0 deletions

View File

@@ -0,0 +1,109 @@
// backend/src/admin/admin.module.ts
import { DynamicModule, Module } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { componentLoader, Components } from './components';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { Database, Resource, getModelByName } from '@adminjs/prisma'; // 👈 Add getModelByName
import AdminJS from 'adminjs';
// Register the adapter
AdminJS.registerAdapter({ Database, Resource });
@Module({
imports: [ConfigModule],
})
export class AdminModule {
static async forRoot(): Promise<DynamicModule> {
const { AdminModule: AdminJSModule } = await import('@adminjs/nestjs');
const authenticate = async (email: string, password: string) => {
if (email === 'admin@dyolink.com' && password === 'admin123') {
return { email, role: 'admin' };
}
return null;
};
return {
module: AdminModule,
imports: [
await AdminJSModule.createAdminAsync({
imports: [ConfigModule],
inject: [PrismaService, ConfigService],
useFactory: (prisma: PrismaService, config: ConfigService) => {
return {
adminJsOptions: {
rootPath: '/admin',
resources: [
// ✅ Use getModelByName helper
{
resource: {
model: getModelByName('User'),
client: prisma,
},
options: {
properties: {
passwordHash: { isVisible: false },
},
},
},
{
resource: {
model: getModelByName('Organization'),
client: prisma,
},
options: {},
},
{
resource: {
model: getModelByName('OrganizationType'),
client: prisma,
},
options: {},
},
{
resource: {
model: getModelByName('Plan'),
client: prisma,
},
options: {},
},
{
resource: {
model: getModelByName('Membership'),
client: prisma,
},
options: {},
},
{
resource: {
model: getModelByName('Session'),
client: prisma,
},
options: {},
},
],
componentLoader,
dashboard: { component: Components.Dashboard },
branding: {
companyName: 'DyoLink Admin',
logo: false,
softwareBrothers: false,
},
},
auth: {
authenticate,
cookieName: 'dyolink-admin',
cookiePassword: config.get('JWT_SECRET') || 'secret-key-change-this',
},
sessionOptions: {
resave: false,
saveUninitialized: false,
secret: config.get('JWT_SECRET') || 'secret-key-change-this',
},
};
},
}),
],
};
}
}

View File

@@ -0,0 +1,11 @@
// backend/src/admin/components.ts
import { ComponentLoader } from 'adminjs';
const componentLoader = new ComponentLoader();
const Components = {
Dashboard: componentLoader.add('Dashboard', './dashboard'),
// You can add more components here as needed
};
export { componentLoader, Components };

View File

@@ -0,0 +1,32 @@
// backend/src/admin/dashboard-simple.tsx
// @ts-nocheck
import React from 'react';
import { Box, H2, Text, Badge } from '@adminjs/design-system';
const Dashboard = () => {
return (
<Box variant="grey">
<Box variant="white" p="xl">
<H2>Welcome to DyoLink Admin Panel</H2>
<Text>Manage your dental clinics, labs, users, and subscriptions.</Text>
<Box mt="xl" style={{ display: 'flex', gap: '20px' }}>
<Box p="lg" bg="primary20" style={{ flex: 1 }}>
<div style={{ fontSize: '1.5rem' }}>🏥 Clinics</div>
<div style={{ fontSize: '2rem', fontWeight: 'bold' }}>12</div>
</Box>
<Box p="lg" bg="secondary20" style={{ flex: 1 }}>
<div style={{ fontSize: '1.5rem' }}>🔬 Labs</div>
<div style={{ fontSize: '2rem', fontWeight: 'bold' }}>8</div>
</Box>
<Box p="lg" bg="info20" style={{ flex: 1 }}>
<div style={{ fontSize: '1.5rem' }}>👥 Users</div>
<div style={{ fontSize: '2rem', fontWeight: 'bold' }}>45</div>
</Box>
</Box>
</Box>
</Box>
);
};
export default Dashboard;

View File

@@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@@ -0,0 +1,25 @@
// backend/src/app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getRoot() {
return {
message: 'DyoLink API',
version: '1.0',
endpoints: {
auth: '/api/auth',
docs: '/api/docs',
},
};
}
@Get('hello') // This will be at /api/hello
getHello(): string {
return this.appService.getHello();
}
}

23
backend/src/app.module.ts Normal file
View File

@@ -0,0 +1,23 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import configurations from './configs/configurations';
import { AuthModule } from './modules/auth/auth.module';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AdminModule } from './admin/admin.module';
import { PrismaModule } from '../prisma/prisma.module'; // ✅
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [configurations],
}),
PrismaModule, // ✅ ADD THIS
AuthModule,
AdminModule.forRoot(),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

View File

@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@@ -0,0 +1,53 @@
// backend/src/config/configuration.ts
export interface Config {
port: number;
database: {
url: string;
};
jwt: {
secret: string;
expiresIn: string;
};
throttle: {
ttl: number;
limit: number;
};
}
export default (): Config => {
// Helper function to get required env var with type safety
const getEnvVar = (key: string): string => {
const value = process.env[key];
if (!value) {
throw new Error(`❌ Environment variable ${key} is required but not set`);
}
return value;
};
// Helper for optional env vars with defaults
const getEnvVarWithDefault = (key: string, defaultValue: string): string => {
return process.env[key] || defaultValue;
};
const getEnvVarAsNumber = (key: string, defaultValue: number): number => {
const value = process.env[key];
if (!value) return defaultValue;
const parsed = parseInt(value, 10);
return isNaN(parsed) ? defaultValue : parsed;
};
return {
port: getEnvVarAsNumber('PORT', 3000),
database: {
url: getEnvVar('DATABASE_URL'),
},
jwt: {
secret: getEnvVar('JWT_SECRET'),
expiresIn: getEnvVarWithDefault('JWT_EXPIRES_IN', '7d'),
},
throttle: {
ttl: getEnvVarAsNumber('THROTTLE_TTL', 60),
limit: getEnvVarAsNumber('THROTTLE_LIMIT', 100),
},
};
};

81
backend/src/main.ts Normal file
View File

@@ -0,0 +1,81 @@
// backend/src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import cookieParser from 'cookie-parser'; // 👈 Change this line!
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
// At the VERY TOP of main.ts, before anything else
const originalConsoleLog = console.log;
console.log = (...args) => {
// Check if this is the massive Prisma dump (contains _clientVersion)
if (args.some(arg => arg && typeof arg === 'object' && arg._clientVersion)) {
console.error = originalConsoleLog; // Temporarily restore for this message
originalConsoleLog('🔍🔍🔍 PRISMA CLIENT DUMP DETECTED 🔍🔍🔍');
originalConsoleLog('Stack trace:', new Error().stack);
return; // Don't print the actual object
}
originalConsoleLog.apply(console, args);
};
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Global pipes
app.useGlobalPipes(new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}));
// Cookie parser - this is correct for Express
app.use(cookieParser());
// CORS
app.enableCors({
origin: process.env.FRONTEND_URL || 'http://localhost:3001',
credentials: true,
});
// Global prefix
app.setGlobalPrefix('api');
// Swagger configuration
const swaggerConfig = new DocumentBuilder()
.setTitle('Dyolink API')
.setDescription('Dental Clinic & Lab Communication Hub API')
.setVersion('1.0')
.addTag('auth', 'Authentication endpoints')
.addBearerAuth(
{
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
name: 'JWT',
description: 'Enter JWT token',
in: 'header',
},
'JWT-auth',
)
.build();
const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('api/docs', app, document, {
swaggerOptions: {
persistAuthorization: true,
tagsSorter: 'alpha',
operationsSorter: 'alpha',
},
customSiteTitle: 'Dyolink API Documentation',
});
const port = parseInt(process.env.PORT || '', 10) || 3000;
await app.listen(port);
console.log(`🚀 Application is running on: http://localhost:${port}/api`);
console.log(`📚 Swagger documentation: http://localhost:${port}/api/docs`);
console.log(`📚 AdminJS Panel: http://localhost:${port}/admin`);
}
bootstrap();

View File

@@ -0,0 +1,177 @@
// backend/src/modules/auth/auth.controller.ts
import {
Controller,
Post,
Body,
UseGuards,
Req,
Res,
HttpCode,
HttpStatus,
Get
} from '@nestjs/common';
import type { Response } from 'express';
import {
ApiTags,
ApiOperation,
ApiResponse,
ApiBearerAuth,
ApiBody,
ApiUnauthorizedResponse,
ApiBadRequestResponse
} from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { LocalAuthGuard } from './guards/local-auth.guard';
@ApiTags('auth')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
// =========================
// LOGIN
// =========================
@Post('login')
@HttpCode(HttpStatus.OK)
@UseGuards(LocalAuthGuard)
@ApiOperation({ summary: 'Login with email and password' })
@ApiBody({ type: LoginDto })
@ApiResponse({ status: 200, description: 'Login successful' })
@ApiUnauthorizedResponse({ description: 'Invalid credentials' })
@ApiBadRequestResponse({ description: 'Invalid input data' })
async login(
@Body() loginDto: LoginDto,
@Req() req,
@Res({ passthrough: true }) res: Response
) {
console.log('Login endpoint hit');
const result = await this.authService.login(loginDto, req.user);
// ✅ SET COOKIES HERE
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
return {
success: true,
data: {
user: result.data.user,
organizations: result.data.organizations,
},
};
}
// =========================
// REGISTER
// =========================
@Post('register')
@ApiOperation({ summary: 'Register a new user' })
@ApiBody({ type: RegisterDto })
@ApiResponse({ status: 201, description: 'User registered successfully' })
@ApiBadRequestResponse({ description: 'Invalid input data' })
async register(
@Body() registerDto: RegisterDto,
@Res({ passthrough: true }) res: Response
) {
console.log('Register endpoint hit');
const result = await this.authService.register(registerDto);
// ✅ SET COOKIES HERE
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
return {
success: true,
data: {
user: result.data.user,
organizations: result.data.organizations,
},
};
}
// =========================
// SELECT ORGANIZATION
// =========================
@Post('select-organization')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth('JWT-auth')
async selectOrganization(
@Req() req,
@Body('organizationId') organizationId: string,
@Res({ passthrough: true }) res: Response
) {
const result = await this.authService.selectOrganization(
req.user.id,
organizationId
);
// 🔥 Replace access token with org-scoped token
this.setAccessToken(res, result.data.accessToken);
return {
success: true,
data: {
organization: result.data.organization,
},
};
}
// =========================
// PROFILE
// =========================
@Get('profile')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth('JWT-auth')
@ApiOperation({ summary: 'Get user profile' })
@ApiResponse({ status: 200, description: 'Profile retrieved successfully' })
@ApiUnauthorizedResponse({ description: 'Invalid or missing JWT token' })
async getProfile(@Req() req) {
console.log('Profile endpoint hit');
console.log('USER FROM JWT:', req.user);
return this.authService.getProfile(req.user.id);
}
// =========================
// TEST
// =========================
@Get('test')
@ApiOperation({ summary: 'Test endpoint' })
test() {
return { message: 'Auth controller is working!' };
}
// =========================
// 🔥 COOKIE HELPERS
// =========================
private setAuthCookies(
res: Response,
accessToken: string,
refreshToken: string
) {
this.setAccessToken(res, accessToken);
this.setRefreshToken(res, refreshToken);
}
private setAccessToken(res: Response, token: string) {
res.cookie('accessToken', token, {
httpOnly: true,
secure: false, // ⚠️ true in production (HTTPS)
sameSite: 'lax',
path: '/',
});
}
private setRefreshToken(res: Response, token: string) {
res.cookie('refreshToken', token, {
httpOnly: true,
secure: false,
sameSite: 'lax',
path: '/',
});
}
}

View File

@@ -0,0 +1,33 @@
// backend/src/modules/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { PrismaService } from '../../../prisma/prisma.service';
import { LocalStrategy } from './strategies/local.strategy';
import { JwtStrategy } from './strategies/jwt.strategy';
@Module({
imports: [
PassportModule,
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
secret: configService.get('jwt.secret'),
signOptions: { expiresIn: configService.get('jwt.expiresIn') },
}),
inject: [ConfigService],
}),
],
controllers: [AuthController], // THIS MUST BE HERE
providers: [
AuthService,
PrismaService,
LocalStrategy,
JwtStrategy,
],
exports: [AuthService],
})
export class AuthModule {}

View File

@@ -0,0 +1,668 @@
// backend/src/modules/auth/auth.service.ts
import {
Injectable,
UnauthorizedException,
BadRequestException,
ConflictException,
InternalServerErrorException
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import * as bcrypt from 'bcrypt';
import { PrismaService } from '../../../prisma/prisma.service';
import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto';
import { JwtPayload } from './interfaces/jwt-payload.interface';
const ALL_PERMISSIONS = [
'VIEW_PATIENTS',
'CREATE_PATIENTS',
'EDIT_PATIENTS',
'DELETE_PATIENTS',
'VIEW_ORDERS',
'CREATE_ORDERS',
'EDIT_ORDERS',
'DELETE_ORDERS',
'TRACK_ORDERS',
'VIEW_CASES',
'CREATE_CASES',
'EDIT_CASES',
'DELETE_CASES',
'VIEW_REPORTS',
'EXPORT_REPORTS',
'INVITE_USERS',
'REMOVE_USERS',
'MANAGE_PERMISSIONS',
'VIEW_INVOICES',
'CREATE_INVOICES',
'MANAGE_PAYMENTS',
];
@Injectable()
export class AuthService {
constructor(
private prisma: PrismaService,
private jwtService: JwtService,
private configService: ConfigService,
) { }
/**
* Validate user credentials (used by LocalStrategy)
* @param email - User's email
* @param password - User's password
* @returns User object without passwordHash or null if invalid
*/
async validateUser(email: string, password: string): Promise<any> {
try {
const user = await this.prisma.user.findUnique({
where: { email },
include: {
memberships: {
include: {
organization: {
include: {
type: true, // Include organization type (CLINIC/LAB)
}
},
permissions: {
include: {
permission: true, // Include permission details
},
},
},
},
},
});
if (!user) {
return null;
}
// Check if user has a password (might be OAuth only, but we're not using OAuth)
if (!user.passwordHash) {
return null;
}
const isPasswordValid = await bcrypt.compare(password, user.passwordHash);
if (!isPasswordValid) {
return null;
}
// Remove sensitive data
const { passwordHash, ...result } = user;
return result;
} catch (error) {
throw new InternalServerErrorException('Error validating user');
}
}
/**
* Login user and generate tokens
* @param loginDto - Login credentials (email, password)
* @param user - Validated user object from LocalStrategy
* @returns Access token, refresh token, user info, and organizations
*/
async login(loginDto: LoginDto, user: any) {
try {
// Generate access token (short-lived)
const accessPayload: JwtPayload = {
sub: user.id,
email: user.email,
type: 'access'
};
// Generate refresh token (long-lived)
const refreshPayload: JwtPayload = {
sub: user.id,
email: user.email,
type: 'refresh'
};
const [accessToken, refreshToken] = await Promise.all([
this.jwtService.signAsync(accessPayload, {
secret: this.configService.get('JWT_SECRET'),
expiresIn: this.configService.get('JWT_EXPIRES_IN'),
}),
this.jwtService.signAsync(refreshPayload, {
secret: this.configService.get('JWT_REFRESH_SECRET'),
expiresIn: this.configService.get('JWT_REFRESH_EXPIRES_IN'),
}),
]);
// Store session in database
await this.prisma.session.create({
data: {
userId: user.id,
token: accessToken,
refreshToken: refreshToken,
expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
},
});
// Transform memberships to include organization info and permissions
const organizations = user.memberships?.map(membership => ({
id: membership.organization.id,
name: membership.organization.name,
type: membership.organization.type.name, // 'CLINIC' or 'LAB'
isOwner: membership.isOwner,
permissions: membership.isOwner
? ALL_PERMISSIONS
: membership.permissions?.map(p => p.permission.name) || [],
})) || [];
return {
success: true,
data: {
accessToken,
refreshToken,
user: {
id: user.id,
email: user.email,
name: user.name,
},
organizations,
},
};
} catch (error) {
//throw new InternalServerErrorException('Login failed');
console.error('🔥 LOGIN ERROR FULL:', error);
throw error;
}
}
/**
* Register a new user
* @param registerDto - Registration data (email, password, name)
* @returns Created user info without password
*/
async register(registerDto: RegisterDto) {
const { email, password, name, organizationName, organizationType } = registerDto;
// 1. Check existing user
const existingUser = await this.prisma.user.findUnique({
where: { email },
});
if (existingUser) {
throw new ConflictException('User already exists');
}
// 2. Hash password
const hashedPassword = await bcrypt.hash(password, 10);
// 3. Transaction (IMPORTANT)
const result = await this.prisma.$transaction(async (tx) => {
// Create user
const user = await tx.user.create({
data: {
email,
passwordHash: hashedPassword,
name,
},
});
// Create organization
const organization = await tx.organization.create({
data: {
name: registerDto.organizationName,
// REQUIRED FIELDS 👇
email: registerDto.email, // or separate org email if you have one
owner: {
connect: { id: user.id },
},
plan: {
connect: { name: 'trial' }, // make sure this exists in DB
},
type: {
connect: {
name: registerDto.organizationType, // 'CLINIC' | 'LAB'
},
},
},
});
// Create membership (owner)
await tx.membership.create({
data: {
userId: user.id,
organizationId: organization.id,
isOwner: true,
},
});
return { user, organization };
});
// 4. Generate tokens (reuse login logic)
const validatedUser = await this.validateUser(email, password);
if (!validatedUser) {
throw new UnauthorizedException('Auto-login failed');
}
return this.login({ email, password } as any, validatedUser);
}
/**
* Get user profile with all memberships and permissions
* @param userId - User ID from JWT token
* @returns User profile with organizations and permissions
*/
async getProfile(userId: string) {
try {
const user = await this.prisma.user.findUnique({
where: { id: userId },
include: {
memberships: {
include: {
organization: {
include: {
type: true,
},
},
permissions: {
include: {
permission: true,
},
},
},
},
},
});
if (!user) {
throw new UnauthorizedException('User not found');
}
const { passwordHash, ...result } = user;
// Transform memberships for frontend consumption
const organizations = user.memberships?.map(membership => ({
id: membership.organization.id,
name: membership.organization.name,
type: membership.organization.type.name,
isOwner: membership.isOwner,
permissions: membership.permissions?.map(p => p.permission.name) || [],
})) || [];
return {
success: true,
data: {
...result,
organizations,
},
};
} catch (error) {
throw new InternalServerErrorException('Failed to get profile');
}
}
/**
* Logout user by invalidating their session
* @param token - Access token to invalidate
* @returns Success message
*/
async logout(token: string) {
try {
await this.prisma.session.deleteMany({
where: { token },
});
return {
success: true,
message: 'Logged out successfully',
};
} catch (error) {
throw new InternalServerErrorException('Logout failed');
}
}
/**
* Refresh access token using refresh token
* @param refreshToken - Valid refresh token
* @returns New access token
*/
async refreshToken(refreshToken: string) {
try {
// Verify the refresh token
const payload = await this.jwtService.verifyAsync(refreshToken, {
secret: this.configService.get('jwt.refreshSecret'),
});
// Ensure this is a refresh token
if (payload.type !== 'refresh') {
throw new UnauthorizedException('Invalid token type');
}
// Find session with this refresh token
const session = await this.prisma.session.findFirst({
where: {
refreshToken,
expiresAt: { gt: new Date() }
},
include: {
user: {
include: {
memberships: {
include: {
organization: {
include: {
type: true,
},
},
permissions: {
include: {
permission: true,
},
},
},
},
},
},
},
});
if (!session) {
throw new UnauthorizedException('Invalid refresh token');
}
// Generate new access token
const newAccessPayload: JwtPayload = {
sub: session.user.id,
email: session.user.email,
type: 'access',
};
const newAccessToken = await this.jwtService.signAsync(newAccessPayload, {
secret: this.configService.get('jwt.secret'),
expiresIn: this.configService.get('jwt.expiresIn'),
});
// Update session with new access token
await this.prisma.session.update({
where: { id: session.id },
data: {
token: newAccessToken,
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
},
});
// Transform memberships for response
const organizations = session.user.memberships?.map(membership => ({
id: membership.organization.id,
name: membership.organization.name,
type: membership.organization.type.name,
isOwner: membership.isOwner,
permissions: membership.permissions?.map(p => p.permission.name) || [],
})) || [];
return {
success: true,
data: {
accessToken: newAccessToken,
user: {
id: session.user.id,
email: session.user.email,
name: session.user.name,
},
organizations,
},
};
} catch (error) {
if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
throw new UnauthorizedException('Invalid or expired refresh token');
}
throw new UnauthorizedException('Refresh token failed');
}
}
/**
* Change user password
* @param userId - User ID
* @param oldPassword - Current password
* @param newPassword - New password
* @returns Success message
*/
async changePassword(userId: string, oldPassword: string, newPassword: string) {
try {
const user = await this.prisma.user.findUnique({
where: { id: userId },
});
if (!user || !user.passwordHash) {
throw new BadRequestException('User not found or invalid password method');
}
// Verify old password
const isPasswordValid = await bcrypt.compare(oldPassword, user.passwordHash);
if (!isPasswordValid) {
throw new UnauthorizedException('Current password is incorrect');
}
// Hash new password
const hashedPassword = await bcrypt.hash(newPassword, 10);
// Update password
await this.prisma.user.update({
where: { id: userId },
data: { passwordHash: hashedPassword },
});
// Invalidate all sessions for this user (force re-login)
await this.prisma.session.deleteMany({
where: { userId },
});
return {
success: true,
message: 'Password changed successfully. Please login again.',
};
} catch (error) {
if (error instanceof UnauthorizedException || error instanceof BadRequestException) {
throw error;
}
throw new InternalServerErrorException('Failed to change password');
}
}
/**
* Get all active sessions for a user
* @param userId - User ID
* @returns List of active sessions
*/
async getUserSessions(userId: string) {
try {
const sessions = await this.prisma.session.findMany({
where: {
userId,
expiresAt: { gt: new Date() },
},
orderBy: { createdAt: 'desc' },
});
return {
success: true,
data: sessions,
};
} catch (error) {
throw new InternalServerErrorException('Failed to get sessions');
}
}
/**
* Revoke a specific session
* @param userId - User ID
* @param sessionId - Session ID to revoke
* @returns Success message
*/
async revokeSession(userId: string, sessionId: string) {
try {
await this.prisma.session.delete({
where: {
id: sessionId,
userId, // Ensure session belongs to user
},
});
return {
success: true,
message: 'Session revoked successfully',
};
} catch (error) {
throw new InternalServerErrorException('Failed to revoke session');
}
}
/**
* Revoke all sessions for a user (except current)
* @param userId - User ID
* @param currentToken - Current access token to keep
* @returns Success message
*/
async revokeAllSessions(userId: string, currentToken: string) {
try {
await this.prisma.session.deleteMany({
where: {
userId,
token: { not: currentToken }, // Keep current session
},
});
return {
success: true,
message: 'All other sessions revoked successfully',
};
} catch (error) {
throw new InternalServerErrorException('Failed to revoke sessions');
}
}
/**
* Validate token and return user
* @param token - JWT token
* @returns User info if token is valid
*/
async validateToken(token: string) {
try {
const payload = await this.jwtService.verifyAsync(token, {
secret: this.configService.get('jwt.secret'),
});
if (payload.type !== 'access') {
throw new UnauthorizedException('Invalid token type');
}
const session = await this.prisma.session.findFirst({
where: {
token,
expiresAt: { gt: new Date() }
},
include: {
user: {
include: {
memberships: {
include: {
organization: {
include: {
type: true,
},
},
permissions: {
include: {
permission: true,
},
},
},
},
},
},
},
});
if (!session) {
throw new UnauthorizedException('Session not found or expired');
}
const { passwordHash, ...user } = session.user;
const organizations = session.user.memberships?.map(membership => ({
id: membership.organization.id,
name: membership.organization.name,
type: membership.organization.type.name,
isOwner: membership.isOwner,
permissions: membership.permissions?.map(p => p.permission.name) || [],
})) || [];
return {
success: true,
data: {
user,
organizations,
},
};
} catch (error) {
throw new UnauthorizedException('Invalid token');
}
}
async selectOrganization(userId: string, organizationId: string) {
// 1. Verify membership
const membership = await this.prisma.membership.findFirst({
where: {
userId,
organizationId,
},
include: {
organization: {
include: {
type: true,
plan: true,
},
},
permissions: {
include: {
permission: true,
},
},
},
});
if (!membership) {
throw new UnauthorizedException('Access denied to this organization');
}
// 2. Build payload WITH org context
const payload = {
sub: userId,
email: membership.organization.email,
organizationId: membership.organizationId,
type: 'access',
};
// 3. Generate new token
const accessToken = await this.jwtService.signAsync(payload, {
secret: this.configService.get('JWT_SECRET'),
expiresIn: this.configService.get('JWT_EXPIRES_IN'),
});
// 4. Format permissions
const permissions = membership.permissions.map(p => p.permission.name);
return {
success: true,
data: {
accessToken,
organization: {
id: membership.organization.id,
name: membership.organization.name,
type: membership.organization.type.name,
},
permissions,
},
};
}
}

View File

@@ -0,0 +1,23 @@
// backend/src/modules/auth/dto/login.dto.ts
import { IsEmail, IsString, MinLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class LoginDto {
@ApiProperty({
description: 'User email address',
example: 'user@example.com',
required: true,
})
@IsEmail({}, { message: 'Please provide a valid email address' })
email: string;
@ApiProperty({
description: 'User password (min 6 characters)',
example: 'password123',
required: true,
minLength: 6,
})
@IsString()
@MinLength(6, { message: 'Password must be at least 6 characters long' })
password: string;
}

View File

@@ -0,0 +1,6 @@
export class OAuthUserDto {
email: string;
name: string;
googleId?: string;
facebookId?: string;
}

View File

@@ -0,0 +1,19 @@
import { IsEmail, IsString, MinLength, IsEnum } from 'class-validator';
export class RegisterDto {
@IsEmail()
email: string;
@IsString()
@MinLength(8)
password: string;
@IsString()
name: string;
@IsString()
organizationName: string;
@IsEnum(['CLINIC', 'LAB'])
organizationType: 'CLINIC' | 'LAB';
}

View File

@@ -0,0 +1,10 @@
// backend/src/modules/auth/guards/jwt-auth.guard.ts
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
/**
* JwtAuthGuard triggers the JWT passport strategy
* It validates the JWT token from the Authorization header
*/
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

View File

@@ -0,0 +1,10 @@
// backend/src/modules/auth/guards/local-auth.guard.ts
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
/**
* LocalAuthGuard triggers the local passport strategy
* It validates user credentials (email/password) before login
*/
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}

View File

@@ -0,0 +1,7 @@
// backend/src/modules/auth/interfaces/jwt-payload.interface.ts
export interface JwtPayload {
sub: string; // user id
email: string;
type?: 'access' | 'refresh';
}

View File

@@ -0,0 +1,36 @@
// backend/src/modules/auth/strategies/jwt.strategy.ts
import { Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../../../../prisma/prisma.service';
import { Request } from 'express';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private configService: ConfigService,
private prisma: PrismaService,
) {
super({
jwtFromRequest: (req: Request) => {
return req?.cookies?.accessToken; // ✅ READ FROM COOKIE
},
ignoreExpiration: false,
secretOrKey: configService.get('JWT_SECRET'),
});
}
async validate(payload: any) {
const user = await this.prisma.user.findUnique({
where: { id: payload.sub },
});
if (!user) {
throw new UnauthorizedException();
}
const { passwordHash, ...result } = user;
return result;
}
}

View File

@@ -0,0 +1,20 @@
// backend/src/modules/auth/strategies/local.strategy.ts
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from '../auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({ usernameField: 'email' }); // Use 'email' instead of 'username'
}
async validate(email: string, password: string): Promise<any> {
const user = await this.authService.validateUser(email, password);
if (!user) {
throw new UnauthorizedException('Invalid credentials');
}
return user;
}
}