forked from veridatum-labs/earnproof-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.guard.ts
More file actions
63 lines (53 loc) · 1.79 KB
/
Copy pathauth.guard.ts
File metadata and controls
63 lines (53 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from "@nestjs/common";
import { Request } from "express";
import { PrismaService } from "../../database/prisma.service";
import { SessionService } from "../../auth/session.service";
import { AuthenticatedSession } from "../../auth/auth.types";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly sessionService: SessionService,
private readonly prisma: PrismaService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const header = request.headers.authorization;
if (!header?.startsWith("Bearer ")) {
throw new UnauthorizedException("Missing bearer token");
}
const token = header.slice("Bearer ".length);
// Validate the session — throws on malformed / expired / revoked tokens.
const { sessionId, userId } = await this.sessionService.validate(token);
// Fetch the live user record so the guard can enforce account status.
const user = await this.prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
walletAddress: true,
walletHash: true,
role: true,
status: true,
},
});
if (!user) {
throw new UnauthorizedException("User not found");
}
if (user.status === "SUSPENDED" || user.status === "REVOKED" || user.status === "DELETED") {
throw new UnauthorizedException("Account is not active");
}
const authenticatedSession: AuthenticatedSession = {
sessionId,
id: user.id,
walletAddress: user.walletAddress,
walletHash: user.walletHash,
role: user.role,
};
request.user = authenticatedSession;
return true;
}
}