43 lines
1.3 KiB
TypeScript
43 lines
1.3 KiB
TypeScript
import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import * as admin from 'firebase-admin';
|
|
|
|
@Injectable()
|
|
export class AuthGuard implements CanActivate {
|
|
constructor(
|
|
@Inject('FIREBASE_ADMIN') private firebaseAdmin: admin.app.App,
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest();
|
|
const authHeader = request.headers.authorization;
|
|
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
throw new UnauthorizedException('Missing or invalid authorization token');
|
|
}
|
|
|
|
const token = authHeader.split('Bearer ')[1];
|
|
|
|
try {
|
|
const decodedToken = await this.firebaseAdmin.auth().verifyIdToken(token);
|
|
|
|
// Check if email is verified (optional but recommended)
|
|
if (!decodedToken.email_verified) {
|
|
throw new UnauthorizedException('Email not verified');
|
|
}
|
|
|
|
// Add the user to the request
|
|
request.user = {
|
|
uid: decodedToken.uid,
|
|
email: decodedToken.email,
|
|
role: decodedToken.role || null,
|
|
// Add other user info as needed
|
|
};
|
|
|
|
return true;
|
|
} catch (error) {
|
|
throw new UnauthorizedException('Invalid token');
|
|
}
|
|
}
|
|
}
|
|
|