Introduce repository pattern across multiple services, including `favorites`, `tags`, `sessions`, `reports`, `auth`, and more. Decouple crypto functionalities into modular services like `HashingService`, `JwtService`, and `EncryptionService`. Improve testability and maintainability by simplifying dependencies and consolidating utility logic.
45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
import {
|
|
CanActivate,
|
|
ExecutionContext,
|
|
Injectable,
|
|
UnauthorizedException,
|
|
} from "@nestjs/common";
|
|
import { ConfigService } from "@nestjs/config";
|
|
import { getIronSession } from "iron-session";
|
|
import { JwtService } from "../../crypto/services/jwt.service";
|
|
import { getSessionOptions, SessionData } from "../session.config";
|
|
|
|
@Injectable()
|
|
export class AuthGuard implements CanActivate {
|
|
constructor(
|
|
private readonly jwtService: JwtService,
|
|
private readonly configService: ConfigService,
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest();
|
|
const response = context.switchToHttp().getResponse();
|
|
|
|
const session = await getIronSession<SessionData>(
|
|
request,
|
|
response,
|
|
getSessionOptions(this.configService.get("SESSION_PASSWORD") as string),
|
|
);
|
|
|
|
const token = session.accessToken;
|
|
|
|
if (!token) {
|
|
throw new UnauthorizedException();
|
|
}
|
|
|
|
try {
|
|
const payload = await this.jwtService.verifyJwt(token);
|
|
request.user = payload;
|
|
} catch {
|
|
throw new UnauthorizedException();
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|