Skip to content

Commit

Permalink
generating access token based on access
Browse files Browse the repository at this point in the history
  • Loading branch information
Vishwas1 committed Mar 25, 2024
1 parent cc88625 commit 82de1a3
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 8 deletions.
5 changes: 4 additions & 1 deletion src/app-auth/app-auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
Module,
NestModule,
RequestMethod,
forwardRef,
} from '@nestjs/common';

import { AppAuthService } from './services/app-auth.service';
Expand All @@ -21,12 +22,14 @@ import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
import { SupportedServiceService } from 'src/supported-service/services/supported-service.service';
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';

@Module({
imports: [
MongooseModule.forFeature([{ name: App.name, schema: AppSchema }]),
HidWalletModule,
EdvModule,

UserModule,
JwtModule.register({}),
],
providers: [
Expand Down
99 changes: 96 additions & 3 deletions src/app-auth/services/app-auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { VaultWalletManager } from '../../edv/services/vaultWalletManager';
import * as url from 'url';
import { SupportedServiceService } from 'src/supported-service/services/supported-service.service';
import { SERVICE_TYPES } from 'src/supported-service/services/iServiceList';
import { UserRepository } from 'src/user/repository/user.repository';

enum GRANT_TYPES {
access_service_kyc = 'access_service_kyc',
Expand All @@ -37,6 +38,7 @@ export class AppAuthService {
private readonly jwt: JwtService,
private readonly appAuthApiKeyService: AppAuthApiKeyService,
private readonly supportedServices: SupportedServiceService,
private readonly userRepository: UserRepository,
) {}

async createAnApp(
Expand Down Expand Up @@ -266,6 +268,21 @@ export class AppAuthService {
return appDetail;
}

private checkIfDateExpired(expiryDate: Date | null) {
if (!expiryDate) {
// if expiryDate null, then its never expired
return false;
}
const now = Date.now();
const expiryDateTime = new Date(expiryDate);
const expiryEpoch = expiryDateTime.getTime();
if (now > expiryEpoch) {
return true;
} else {
return false;
}
}

async generateAccessToken(
appSecreatKey: string,
expiresin = 4,
Expand All @@ -285,6 +302,14 @@ export class AppAuthService {

throw new UnauthorizedException(['access_denied']);
}
const userDetails = await this.userRepository.findOne({
userId: appDetail.userId,
});
if (!userDetails) {
throw new UnauthorizedException([
'Admin user not found. He/She might have delete the account or never created one',
]);
}

const compareHash = await this.appAuthSecretService.comapareSecret(
appSecreatKey,
Expand All @@ -302,24 +327,55 @@ export class AppAuthService {

const serviceType = appDetail.services[0]?.id; // TODO: remove this later
let grant_type = '';
let accessList = [];
switch (serviceType) {
case SERVICE_TYPES.SSI_API: {
grant_type = GRANT_TYPES.access_service_ssi;
accessList = userDetails.accessList
.map((x) => {
if (x.serviceType === SERVICE_TYPES.SSI_API) {
if (!this.checkIfDateExpired(x.expiryDate)) {
return x.access;
}
}
})
.filter((x) => x != undefined);
break;
}
case SERVICE_TYPES.CAVACH_API: {
grant_type = GRANT_TYPES.access_service_kyc;
accessList = userDetails.accessList
.map((x) => {
if (x.serviceType === SERVICE_TYPES.CAVACH_API) {
if (!this.checkIfDateExpired(x.expiryDate)) {
return x.access;
}
}
})
.filter((x) => x != undefined);
break;
}
default: {
throw new BadRequestException('Invalid service ' + appDetail.appId);
}
}

return this.getAccessToken(grant_type, appDetail, expiresin);
if (accessList.length <= 0) {
throw new UnauthorizedException(
'You are not authorized to access service of type ',
serviceType,
);
}

return this.getAccessToken(grant_type, appDetail, expiresin, accessList);
}

private async getAccessToken(grantType, appDetail, expiresin = 4) {
private async getAccessToken(
grantType,
appDetail,
expiresin = 4,
accessList = [],
) {
const payload = {
appId: appDetail.appId,
userId: appDetail.userId,
Expand All @@ -328,6 +384,7 @@ export class AppAuthService {
whitelistedCors: appDetail.whitelistedCors,
subdomain: appDetail.subdomain,
edvId: appDetail.edvId,
accessList,
};

const secret = this.config.get('JWT_SECRET');
Expand Down Expand Up @@ -366,14 +423,33 @@ export class AppAuthService {
);
}

const userDetails = await this.userRepository.findOne({
userId: app.userId,
});
if (!userDetails) {
throw new UnauthorizedException([
'You do not have access to this service',
]);
}

const serviceType = app.services[0]?.id; // TODO: remove this later
let accessList = [];
switch (serviceType) {
case SERVICE_TYPES.SSI_API: {
if (grantType != 'access_service_ssi') {
throw new BadRequestException(
'Invalid grant type for this service ' + appId,
);
}
accessList = userDetails.accessList
.map((x) => {
if (x.serviceType === SERVICE_TYPES.SSI_API) {
if (!this.checkIfDateExpired(x.expiryDate)) {
return x.access;
}
}
})
.filter((x) => x != undefined);
break;
}
case SERVICE_TYPES.CAVACH_API: {
Expand All @@ -382,12 +458,29 @@ export class AppAuthService {
'Invalid grant type for this service ' + appId,
);
}
accessList = userDetails.accessList
.map((x) => {
if (x.serviceType === SERVICE_TYPES.CAVACH_API) {
if (!this.checkIfDateExpired(x.expiryDate)) {
return x.access;
}
}
})
.filter((x) => x != undefined);
break;
}
default: {
throw new BadRequestException('Invalid service ' + appId);
}
}
return this.getAccessToken(grantType, app);

if (accessList.length <= 0) {
throw new UnauthorizedException(
'You are not authorized to access service of type ',
serviceType,
);
}

return this.getAccessToken(grantType, app, 12, accessList);
}
}
1 change: 1 addition & 0 deletions src/social-login/services/social-login.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export class SocialLoginService {
name,
email,
appUserID: userInfo.userId,
userAccessList: userInfo.accessList,
};
const secret = this.config.get('JWT_SECRET');
const token = await this.jwt.signAsync(payload, {
Expand Down
2 changes: 0 additions & 2 deletions src/supported-service/services/service-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,6 @@ export class SupportedServiceList {
Object.keys(SERVICES[serviceType].ACCESS_TYPES).forEach((access) => {
if (access == SERVICES[serviceType].ACCESS_TYPES.READ_SESSION) {
return;
} else if (access == SERVICES[serviceType].ACCESS_TYPES.WRITE_SESSION) {
return;
} else if (access == SERVICES[serviceType].ACCESS_TYPES.ALL) {
return;
} else {
Expand Down
2 changes: 0 additions & 2 deletions src/user/user.module.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { Module } from '@nestjs/common';
import { UserController } from './controllers/user.controller';
import { UserService } from './services/user.service';
import { AppAuthModule } from 'src/app-auth/app-auth.module';
import { UserRepository } from './repository/user.repository';
import { MongooseModule } from '@nestjs/mongoose';
import { UserSchema, User } from './schema/user.schema';
import { SupportedServiceModule } from 'src/supported-service/supported-service.module';
@Module({
imports: [
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
AppAuthModule,
SupportedServiceModule,
],
controllers: [UserController],
Expand Down
1 change: 1 addition & 0 deletions src/utils/middleware/jwt-authorization.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export class JWTAuthorizeMiddleware implements NestMiddleware {
userId: decoded.appUserID,
email: decoded.email,
name: decoded.name,
userAccessList: decoded.userAccessList,
id: decoded['id'],
};

Expand Down

0 comments on commit 82de1a3

Please sign in to comment.