Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implemented MFA #28

Merged
merged 5 commits into from
Jul 29, 2024
Merged
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
2 changes: 2 additions & 0 deletions .deploy/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ spec:
value: __TENANT_SUBDOMAIN_PREFIX__
- name: SSI_API_DOMAIN
value: __SSI_API_DOMAIN__
- name: MFA_ISSUER
value: __MFA_ISSUER__
- name: CAVACH_API_DOMAIN
value: __CAVACH_API_DOMAIN__
- name: VAULT_PREFIX
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/pipeline.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ jobs:
run: find .deploy/deployment.yaml -type f -exec sed -i "s#__TENANT_SUBDOMAIN_PREFIX__#${{ secrets.TENANT_SUBDOMAIN_PREFIX }}#" {} \;
- name: "Replace Secrets"
run: find .deploy/deployment.yaml -type f -exec sed -i "s#__SSI_API_DOMAIN__#${{ secrets.SSI_API_DOMAIN }}#" {} \;
- name: "Replace Secrets"
run: find .deploy/deployment.yaml -type f -exec sed -i "s#__MFA_ISSUER__#${{ secrets.MFA_ISSUER }}#" {} \;
- name: "Replace Secrets"
run: find .deploy/deployment.yaml -type f -exec sed -i "s#__CAVACH_API_DOMAIN__#${{ secrets.CAVACH_API_DOMAIN }}#" {} \;
- name: "Replace Secrets"
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,12 @@
"hypersign-edv-client": "github:hypersign-protocol/hypersign-edv-client#develop",
"idb-keyval": "^6.2.1",
"mongoose": "^6.8.3",
"otplib": "^12.0.1",
"passport": "^0.6.0",
"passport-google-oauth20": "^2.0.0",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"qrcode": "^1.5.3",
"readline-sync": "^1.4.10",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.2.0",
Expand Down
5 changes: 5 additions & 0 deletions src/app-auth/app-auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { SupportedServiceService } from 'src/supported-service/services/supporte
import { SupportedServiceList } from 'src/supported-service/services/service-list';
import { JWTAuthorizeMiddleware } from 'src/utils/middleware/jwt-authorization.middleware';
import { UserModule } from 'src/user/user.module';
import { TwoFAAuthorizationMiddleware } from 'src/utils/middleware/2FA-jwt-authorization.middleware';

@Module({
imports: [
Expand Down Expand Up @@ -60,5 +61,9 @@ export class AppAuthModule implements NestModule {
.apply(JWTAuthorizeMiddleware)
.exclude({ path: '/api/v1/app/marketplace', method: RequestMethod.GET })
.forRoutes(AppAuthController);
consumer
.apply(TwoFAAuthorizationMiddleware)
.exclude({ path: '/api/v1/app/marketplace', method: RequestMethod.GET })
.forRoutes(AppAuthController);
}
}
3 changes: 2 additions & 1 deletion src/app-oauth/app-oauth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import {
import { AppOauthController } from './app-oauth.controller';
import { AppAuthModule } from 'src/app-auth/app-auth.module';
import { JWTAuthorizeMiddleware } from 'src/utils/middleware/jwt-authorization.middleware';
import { UserModule } from 'src/user/user.module';
@Module({
imports: [AppAuthModule],
imports: [AppAuthModule, UserModule],
controllers: [AppOauthController],
providers: [],
})
Expand Down
63 changes: 63 additions & 0 deletions src/social-login/controller/social-login.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@ import {
Post,
Res,
Query,
Body,
Delete,
} from '@nestjs/common';
import { SocialLoginService } from '../services/social-login.service';
import { AuthGuard } from '@nestjs/passport';
import {
ApiBadRequestResponse,
ApiBearerAuth,
ApiExcludeEndpoint,
ApiOkResponse,
ApiQuery,
Expand All @@ -23,9 +27,18 @@ import { AllExceptionsFilter } from 'src/utils/utils';
import { ConfigService } from '@nestjs/config';
import {
AuthResponse,
DeleteMFARespDto,
Generate2FARespDto,
LoginResponse,
UnauthorizedError,
Verify2FARespDto,
} from '../dto/response.dto';
import {
DeleteMFADto,
Generate2FA,
MFACodeVerificationDto,
} from '../dto/request.dto';
import { AppError } from 'src/app-auth/dtos/fetch-app.dto';
@UseFilters(AllExceptionsFilter)
@ApiTags('Authentication')
@Controller()
Expand Down Expand Up @@ -66,6 +79,7 @@ export class SocialLoginController {
const token = await this.socialLoginService.socialLogin(req);
res.redirect(`${this.config.get('REDIRECT_URL')}?token=${token}`);
}
@ApiBearerAuth('Authorization')
@ApiOkResponse({
description: 'User Info',
type: AuthResponse,
Expand All @@ -83,4 +97,53 @@ export class SocialLoginController {
error: null,
};
}

@ApiOkResponse({
description: 'Generated QR successfully',
type: Generate2FARespDto,
})
@ApiUnauthorizedResponse({
status: 401,
type: UnauthorizedError,
})
@ApiBearerAuth('Authorization')
@Post('/api/v1/auth/mfa/generate')
async generateMfa(@Req() req, @Body() body: Generate2FA) {
const result = await this.socialLoginService.generate2FA(body, req.user);
return { twoFADataUrl: result };
}

@ApiOkResponse({
description: 'Verified MFA code and generated new token',
type: Verify2FARespDto,
})
@ApiUnauthorizedResponse({
status: 401,
type: UnauthorizedError,
})
@ApiBearerAuth('Authorization')
@Post('/api/v1/auth/mfa/verify')
async verifyMFA(
@Req() req,
@Body() mfaVerificationDto: MFACodeVerificationDto,
) {
return this.socialLoginService.verifyMFACode(req.user, mfaVerificationDto);
}
@ApiOkResponse({
description: 'Removed MFA successfully',
type: DeleteMFARespDto,
})
@ApiBadRequestResponse({
status: 400,
type: AppError,
})
@ApiUnauthorizedResponse({
status: 401,
type: UnauthorizedError,
})
@ApiBearerAuth('Authorization')
@Delete('/api/v1/auth/mfa')
async removeMFA(@Req() req, @Body() mfaremoveDto: DeleteMFADto) {
return this.socialLoginService.removeMFA(req.user, mfaremoveDto);
}
}
61 changes: 61 additions & 0 deletions src/social-login/dto/request.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { IsEnum, IsNotEmpty, IsString } from 'class-validator';
import { AuthneticatorType } from './response.dto';
import { ApiProperty } from '@nestjs/swagger';

export class MFACodeVerificationDto {
@ApiProperty({
name: 'authenticatorType',
description: 'Type of authenticator used for 2FA',
example: AuthneticatorType.google,
enum: AuthneticatorType,
})
@IsEnum(AuthneticatorType)
authenticatorType: string;
@ApiProperty({
name: 'twoFactorAuthenticationCode',
description: 'Code generated in authenticator app',
example: '678324',
})
@IsString()
@IsNotEmpty()
twoFactorAuthenticationCode: string;
}

export class Generate2FA {
@ApiProperty({
name: 'authenticatorType',
description: 'Type of authenticator used for 2FA',
example: AuthneticatorType.google,
enum: AuthneticatorType,
})
@IsEnum(AuthneticatorType)
authenticatorType: string;
}

export class DeleteMFADto {
@ApiProperty({
name: 'authenticatorType',
description: 'Type of authenticator used for 2FA',
example: AuthneticatorType.google,
enum: AuthneticatorType,
})
@IsEnum(AuthneticatorType)
authenticatorType: string;
@ApiProperty({
name: 'twoFactorAuthenticationCode',
description:
'Code generated in authenticator app of selected authenticatorType',
example: '678324',
})
@IsString()
@IsNotEmpty()
twoFactorAuthenticationCode: string;
@ApiProperty({
name: 'authenticatorToDelete',
description: 'Type of authenticator that user want to remove',
example: AuthneticatorType.okta,
enum: AuthneticatorType,
})
@IsEnum(AuthneticatorType)
authenticatorToDelete: string;
}
40 changes: 39 additions & 1 deletion src/social-login/dto/response.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNumber, IsString } from 'class-validator';
import { IsBoolean, IsNumber, IsString } from 'class-validator';

export class UnauthorizedError {
@ApiProperty({
Expand Down Expand Up @@ -66,3 +66,41 @@ export class AuthResponse {
})
error: string;
}
export class Generate2FARespDto {
@ApiProperty({
name: 'twoFADataUrl',
description: 'QR Data',
example: 'data:image/png;base64,iV......',
})
@IsString()
twoFADataUrl: string;
}
export class Verify2FARespDto {
@ApiProperty({
name: 'isVerified',
description: 'COde verification result',
example: true,
})
@IsBoolean()
isVerified: boolean;
@ApiProperty({
name: 'accessToken',
description: '2FA based accessToken',
example: 'eyJh.....',
})
@IsString()
accessToken: string;
}
export class DeleteMFARespDto {
@ApiProperty({
name: 'message',
description: 'A success message',
example: 'Removed authenticator successfully',
})
@IsString()
message: string;
}
export enum AuthneticatorType {
google = 'google',
okta = 'okta',
}
110 changes: 109 additions & 1 deletion src/social-login/services/social-login.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import {
BadRequestException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { UserRepository } from 'src/user/repository/user.repository';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
Expand All @@ -7,6 +12,14 @@ import { Providers } from '../strategy/social.strategy';
import { sanitizeUrl } from 'src/utils/utils';
import { SupportedServiceList } from 'src/supported-service/services/service-list';
import { SERVICE_TYPES } from 'src/supported-service/services/iServiceList';
import { AuthneticatorType } from '../dto/response.dto';
import { authenticator } from 'otplib';
import { toDataURL } from 'qrcode';
import {
DeleteMFADto,
Generate2FA,
MFACodeVerificationDto,
} from '../dto/request.dto';

@Injectable()
export class SocialLoginService {
Expand Down Expand Up @@ -75,4 +88,99 @@ export class SocialLoginService {
});
return token;
}

async generate2FA(genrate2FADto: Generate2FA, user) {
Logger.log(
'Inside generate2FA() method to generate 2FA QRCode',
'SocialLoginService',
);
const { authenticatorType } = genrate2FADto;
let secret: string;
const existingAuthenticator = user.authenticators?.find(
(auth) => auth.type === authenticatorType,
);
if (existingAuthenticator) {
secret = existingAuthenticator.secret;
} else {
secret = authenticator.generateSecret(20);
}
if (!user.authenticators) {
user.authenticators = [];
}
user.authenticators.push({
type: authenticatorType,
secret,
});
this.userRepository.findOneUpdate(
{ userId: user.userId },
{ authenticators: user.authenticators },
);
const issuer = this.config.get('MFA_ISSUER');
const otpAuthUrl = authenticator.keyuri(user.email, issuer, secret);
return toDataURL(otpAuthUrl);
}
async verifyMFACode(user, mfaVerificationDto: MFACodeVerificationDto) {
Logger.log(
'Inside verifyMFACode() method to verify MFA code',
'SocialLoginService',
);
const { authenticatorType, twoFactorAuthenticationCode } =
mfaVerificationDto;
const authenticatorDetail = user.authenticators.find(
(auth) => auth.type === authenticatorType,
);
const isVerified = authenticator.verify({
token: twoFactorAuthenticationCode,
secret: authenticatorDetail.secret,
});
const payload = {
email: user.email,
appUserID: user.userId,
userAccessList: user.accessList,
isTwoFactorEnabled: user.authenticators && user.authenticators.length > 0,
isTwoFactorAuthenticated: isVerified,
};
const accessToken = await this.jwt.signAsync(payload, {
expiresIn: '24h',
secret: this.config.get('JWT_SECRET'),
});
return {
isVerified,
authToken: accessToken,
};
}

async removeMFA(user, deleteMfaDto: DeleteMFADto) {
const {
twoFactorAuthenticationCode,
authenticatorToDelete,
authenticatorType,
} = deleteMfaDto;
const authDetail = user.authenticators.find(
(auth) => auth.type === authenticatorType,
);
const isVerified = authenticator.verify({
token: twoFactorAuthenticationCode,
secret: authDetail.secret,
});
if (!isVerified) {
throw new BadRequestException([
"Your passcode doesn't match. Please try again",
]);
}
const authenticatorIndex = user.authenticators.findIndex(
(auth) => auth.type === authenticatorToDelete,
);
if (authenticatorIndex === -1) {
throw new NotFoundException(
`${authenticatorToDelete} Authenticator not found`,
);
}
user.authenticators.splice(authenticatorIndex, 1);
this.userRepository.findOneUpdate(
{ userId: user.userId },
{ authenticators: user.authenticators },
);
return { message: 'Removed authenticator successfully' };
}
}
Loading
Loading