Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions prisma/migrations/20260422170000_add_session_management.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
-- CreateTable for sessions
CREATE TABLE "sessions" (
"id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"access_token_jti" TEXT NOT NULL,
"refresh_token_jti" TEXT,
"ip_address" TEXT,
"user_agent" TEXT,
"is_revoked" BOOLEAN NOT NULL DEFAULT false,
"revoked_at" TIMESTAMP(3),
"expires_at" TIMESTAMP(3) NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"last_activity_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- CreateIndex
CREATE INDEX "sessions_user_id_idx" ON "sessions"("user_id");

-- CreateIndex
CREATE INDEX "sessions_expires_at_idx" ON "sessions"("expires_at");

-- CreateIndex
CREATE INDEX "sessions_is_revoked_idx" ON "sessions"("is_revoked");
24 changes: 24 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ model User {
apiKeys ApiKey[]
passwordHistory PasswordHistory[]
blacklistedTokens BlacklistedToken[]
sessions Session[]

@@index([email])
@@index([role])
Expand Down Expand Up @@ -225,3 +226,26 @@ model Document {
@@index([documentType])
@@map("documents")
}

// Session model for tracking user sessions
model Session {
id String @id @default(uuid())
userId String @map("user_id")
accessTokenJti String @map("access_token_jti")
refreshTokenJti String? @map("refresh_token_jti")
ipAddress String? @map("ip_address")
userAgent String? @map("user_agent")
isRevoked Boolean @default(false) @map("is_revoked")
revokedAt DateTime? @map("revoked_at")
expiresAt DateTime @map("expires_at")
createdAt DateTime @default(now()) @map("created_at")
lastActivityAt DateTime @default(now()) @map("last_activity_at")

// Relations
user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@index([userId])
@@index([expiresAt])
@@index([isRevoked])
@@map("sessions")
}
4 changes: 4 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { PropertiesModule } from './properties/properties.module';
import { PrismaModule } from './database/prisma.module';
import { AppController } from './app.controller';
import { AuthModule } from './auth/auth.module';
import { DashboardModule } from './dashboard/dashboard.module';
import { SessionsModule } from './sessions/sessions.module';

@Module({
imports: [
Expand All @@ -16,6 +18,8 @@ import { AuthModule } from './auth/auth.module';
UsersModule,
PropertiesModule,
AuthModule,
DashboardModule,
SessionsModule,
],
controllers: [AppController],
})
Expand Down
3 changes: 2 additions & 1 deletion src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Module } from '@nestjs/common';
import { PrismaModule } from '../database/prisma.module';
import { UsersModule } from '../users/users.module';
import { SessionsModule } from '../sessions/sessions.module';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { ApiKeyAuthGuard } from './guards/api-key-auth.guard';

@Module({
imports: [PrismaModule, UsersModule],
imports: [PrismaModule, UsersModule, SessionsModule],
controllers: [AuthController],
providers: [AuthService, JwtAuthGuard, ApiKeyAuthGuard],
exports: [AuthService],
Expand Down
170 changes: 169 additions & 1 deletion src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { randomUUID } from 'crypto';
import * as jwt from 'jsonwebtoken';
import { PrismaService } from '../database/prisma.service';
import { UsersService } from '../users/users.service';
import { SessionsService } from '../sessions/sessions.service';
import {
ChangePasswordDto,
CreateApiKeyDto,
Expand Down Expand Up @@ -54,6 +55,7 @@ export class AuthService {
constructor(
private readonly prisma: PrismaService,
private readonly usersService: UsersService,
private readonly sessionsService: SessionsService,
private readonly configService: ConfigService,
) {
this.jwtSecret = this.configService.get<string>('JWT_SECRET') ?? 'propchain-access-secret';
Expand Down Expand Up @@ -224,6 +226,162 @@ export class AuthService {
return sanitizeUser(foundUser);
}

async getDashboard(user: AuthUserPayload) {
const foundUser = await this.prisma.user.findUnique({
where: { id: user.sub },
});

if (!foundUser) {
throw new NotFoundException('User not found');
}

const [properties, buyerTransactions, sellerTransactions, documents, apiKeys] = await Promise.all([
this.prisma.property.findMany({
where: { ownerId: user.sub },
orderBy: { createdAt: 'desc' },
take: 10,
}),
this.prisma.transaction.findMany({
where: { buyerId: user.sub },
orderBy: { createdAt: 'desc' },
take: 5,
include: {
property: {
select: {
id: true,
title: true,
address: true,
city: true,
state: true,
price: true,
},
},
seller: {
select: {
firstName: true,
lastName: true,
},
},
},
}),
this.prisma.transaction.findMany({
where: { sellerId: user.sub },
orderBy: { createdAt: 'desc' },
take: 5,
include: {
property: {
select: {
id: true,
title: true,
address: true,
city: true,
state: true,
price: true,
},
},
buyer: {
select: {
firstName: true,
lastName: true,
},
},
},
}),
this.prisma.document.findMany({
where: { userId: user.sub },
orderBy: { createdAt: 'desc' },
take: 5,
}),
this.prisma.apiKey.findMany({
where: { userId: user.sub },
orderBy: { createdAt: 'desc' },
take: 3,
}),
]);

const [
totalProperties,
activeListings,
pendingSales,
totalPurchases,
totalSales,
completedPurchases,
completedSales,
] = await Promise.all([
this.prisma.property.count({ where: { ownerId: user.sub } }),
this.prisma.property.count({ where: { ownerId: user.sub, status: 'ACTIVE' } }),
this.prisma.transaction.count({ where: { sellerId: user.sub, status: 'PENDING' } }),
this.prisma.transaction.count({ where: { buyerId: user.sub } }),
this.prisma.transaction.count({ where: { sellerId: user.sub } }),
this.prisma.transaction.count({ where: { buyerId: user.sub, status: 'COMPLETED' } }),
this.prisma.transaction.count({ where: { sellerId: user.sub, status: 'COMPLETED' } }),
]);

const recommendationProperties = await this.prisma.property.findMany({
where: {
status: 'ACTIVE',
ownerId: { not: user.sub },
NOT: {
ownerId: user.sub,
},
},
orderBy: { createdAt: 'desc' },
take: 5,
include: {
owner: {
select: {
firstName: true,
lastName: true,
},
},
},
});

const recentActivity = [
...transactionsToActivityItems(buyerTransactions, 'purchase'),
...transactionsToActivityItems(sellerTransactions, 'sale'),
...documents.map((doc) => ({
type: 'document' as const,
id: doc.id,
title: doc.fileName,
description: `Uploaded ${doc.documentType.toLowerCase().replace('_', ' ')}`,
timestamp: doc.createdAt,
})),
]
.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
.slice(0, 10);

return {
profile: sanitizeUser(foundUser),
quickStats: {
totalProperties,
activeListings,
pendingSales,
totalPurchases,
totalSales,
completedPurchases,
completedSales,
apiKeysCount: apiKeys.length,
},
recentActivity,
recommendations: recommendationProperties.map((p) => ({
id: p.id,
title: p.title,
address: p.address,
city: p.city,
state: p.state,
price: p.price.toString(),
propertyType: p.propertyType,
bedrooms: p.bedrooms,
bathrooms: p.bathrooms?.toString(),
squareFeet: p.squareFeet?.toString(),
status: p.status,
agent: `${p.owner.firstName} ${p.owner.lastName}`,
createdAt: p.createdAt,
})),
};
}

async changePassword(user: AuthUserPayload, data: ChangePasswordDto) {
const passwordHistoryLimit = getPasswordHistoryLimit();
const existingUser = await this.prisma.user.findUnique({
Expand Down Expand Up @@ -506,7 +664,7 @@ export class AuthService {
};
}

private async issueTokenPair(user: User) {
private async issueTokenPair(user: User, ipAddress?: string, userAgent?: string) {
const accessJti = randomUUID();
const refreshJti = randomUUID();

Expand All @@ -532,6 +690,16 @@ export class AuthService {
this.refreshTokenTtlSeconds,
);

// Create a session for tracking
await this.sessionsService.createSession(
user.id,
accessJti,
refreshJti,
ipAddress,
userAgent,
this.refreshTokenTtlSeconds,
);

return {
accessToken,
refreshToken,
Expand Down
17 changes: 17 additions & 0 deletions src/dashboard/dashboard.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { DashboardService } from './dashboard.service';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { AuthUserPayload } from '../auth/types/auth-user.type';
import { DashboardDto } from './dto/dashboard.dto';

@Controller('dashboard')
@UseGuards(JwtAuthGuard)
export class DashboardController {
constructor(private readonly dashboardService: DashboardService) {}

@Get()
async getDashboard(@CurrentUser() user: AuthUserPayload): Promise<DashboardDto> {
return this.dashboardService.getDashboard(user.sub);
}
}
11 changes: 11 additions & 0 deletions src/dashboard/dashboard.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { DashboardService } from './dashboard.service';
import { DashboardController } from './dashboard.controller';
import { PrismaModule } from '../database/prisma.module';

@Module({
imports: [PrismaModule],
controllers: [DashboardController],
providers: [DashboardService],
})
export class DashboardModule {}
Loading