Unverified Commit b99f49c8 authored by Abhishek Mishra's avatar Abhishek Mishra Committed by GitHub
Browse files

Merge pull request #42 from choxx/user-change-account-status

User change account status (activate/deactivate)
No related merge requests found
Showing with 708 additions and 172 deletions
+708 -172
import { User } from '@fusionauth/typescript-client';
import { Body, Controller, Get, Param, Patch, Post, Query, Request, UseGuards } from '@nestjs/common';
import {
Body,
Controller,
Get,
Param,
Patch,
Post,
Query,
Request,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/auth-jwt.guard';
import { SignupResponse, UserRegistration, UsersResponse } from './admin.interface';
import {
SignupResponse,
UserRegistration,
UsersResponse,
} from './admin.interface';
import { AdminService } from './admin.service';
import { Roles } from './roles.decorator';
@Controller('admin')
export class AdminController {
constructor(
private readonly adminService: AdminService,
) {}
@Post('/all')
@Roles('Admin', 'school', 'State Admin', 'District Admin', 'Block Admin', 'School Admin')
@UseGuards(JwtAuthGuard)
async fetchUsers(@Request() req, @Body() data: any): Promise<UsersResponse> {
return await this.adminService.fetchUsers(data);
}
@Post('/changePassword')
@Roles('Admin', 'school', 'State Admin', 'District Admin', 'Block Admin', 'School Admin')
@UseGuards(JwtAuthGuard)
async updatePassword(@Body() data: {loginId: string, password: string}): Promise<SignupResponse> {
return this.adminService.updatePassword(data);
}
@Post('/createUser')
@Roles('Admin', 'school', 'State Admin', 'District Admin', 'Block Admin', 'School Admin')
@UseGuards(JwtAuthGuard)
async createUser(@Body() data: UserRegistration): Promise<SignupResponse> {
return await this.adminService.createUser(data);
}
@Patch('/updateUser/:userId')
@Roles('Admin', 'school', 'State Admin', 'District Admin', 'Block Admin', 'School Admin')
@UseGuards(JwtAuthGuard)
async updateUser(@Param('userId') userId: string, @Body() data: User): Promise<SignupResponse> {
return await this.adminService.updateUser(userId, data);
}
@Get('/searchUser')
@Roles('Admin', 'school', 'State Admin', 'District Admin', 'Block Admin', 'School Admin')
@UseGuards(JwtAuthGuard)
async searchUser(@Query() query: {queryString: string, startRow: number, numberOfResults: number}): Promise<UsersResponse> {
console.log(query.numberOfResults)
return await this.adminService.fetchUsersByString(query.queryString, query.startRow, query.numberOfResults);
}
@Get('/user/:userId')
@Roles('Admin', 'school', 'State Admin', 'District Admin', 'Block Admin', 'School Admin')
@UseGuards(JwtAuthGuard)
async searchUserbyId(@Param('userId') userId: string): Promise<UsersResponse> {
return await this.adminService.fetchUsersByString(userId, undefined, undefined);
}
constructor(private readonly adminService: AdminService) {}
@Post('/all')
@Roles(
'Admin',
'school',
'State Admin',
'District Admin',
'Block Admin',
'School Admin',
)
@UseGuards(JwtAuthGuard)
async fetchUsers(@Request() req, @Body() data: any): Promise<UsersResponse> {
return await this.adminService.fetchUsers(data);
}
@Post('/changePassword')
@Roles(
'Admin',
'school',
'State Admin',
'District Admin',
'Block Admin',
'School Admin',
)
@UseGuards(JwtAuthGuard)
async updatePassword(
@Body() data: { loginId: string; password: string },
): Promise<SignupResponse> {
return this.adminService.updatePassword(data);
}
@Post('/createUser')
@Roles(
'Admin',
'school',
'State Admin',
'District Admin',
'Block Admin',
'School Admin',
)
@UseGuards(JwtAuthGuard)
async createUser(@Body() data: UserRegistration): Promise<SignupResponse> {
return await this.adminService.createUser(data);
}
@Patch('/updateUser/:userId')
@Roles(
'Admin',
'school',
'State Admin',
'District Admin',
'Block Admin',
'School Admin',
)
@UseGuards(JwtAuthGuard)
async updateUser(
@Param('userId') userId: string,
@Body() data: User,
): Promise<SignupResponse> {
return await this.adminService.updateUser(userId, data);
}
@Get('/searchUser')
@Roles(
'Admin',
'school',
'State Admin',
'District Admin',
'Block Admin',
'School Admin',
)
@UseGuards(JwtAuthGuard)
async searchUser(
@Query()
query: {
queryString: string;
startRow: number;
numberOfResults: number;
},
): Promise<UsersResponse> {
console.log(query.numberOfResults);
return await this.adminService.fetchUsersByString(
query.queryString,
query.startRow,
query.numberOfResults,
);
}
@Get('/user/:userId')
@Roles(
'Admin',
'school',
'State Admin',
'District Admin',
'Block Admin',
'School Admin',
)
@UseGuards(JwtAuthGuard)
async searchUserbyId(
@Param('userId') userId: string,
): Promise<UsersResponse> {
return await this.adminService.fetchUsersByString(
userId,
undefined,
undefined,
);
}
@Patch('/user/:userId/deactivate')
@Roles(
'Admin',
'school',
'State Admin',
'District Admin',
'Block Admin',
'School Admin',
)
@UseGuards(JwtAuthGuard)
async deactivateUserById(
@Param('userId') userId: string,
@Query('hardDelete') hardDelete = false,
): Promise<UsersResponse> {
return await this.adminService.deactivateUserById(userId, hardDelete);
}
@Patch('/user/:userId/activate')
@Roles(
'Admin',
'school',
'State Admin',
'District Admin',
'Block Admin',
'School Admin',
)
@UseGuards(JwtAuthGuard)
async activateUserById(
@Param('userId') userId: string,
): Promise<UsersResponse> {
return await this.adminService.activateUserById(userId);
}
}
......@@ -161,4 +161,32 @@ export class AdminService {
}
return registration;
}
async deactivateUserById(userId: string, hardDelete: boolean): Promise<any> {
const activationResponse: { userId: UUID; err: Error } =
await this.fusionAuthService.deactivateUserById(userId, hardDelete);
if (activationResponse.userId == null) {
throw new HttpException(activationResponse.err, HttpStatus.BAD_REQUEST);
}
// fetch the latest user info now & respond
const userResponse = await this.fusionAuthService.getUserById(userId);
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.result = userResponse.user;
return response;
}
async activateUserById(userId: string): Promise<any> {
const activationResponse: { userId: UUID; err: Error } =
await this.fusionAuthService.activateUserById(userId);
if (activationResponse.userId == null) {
throw new HttpException(activationResponse.err, HttpStatus.BAD_REQUEST);
}
// fetch the latest user info now & respond
const userResponse = await this.fusionAuthService.getUserById(userId);
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.result = userResponse.user;
return response;
}
}
......@@ -33,7 +33,10 @@ export class FusionauthService {
protected readonly logger = new Logger(FusionauthService.name); // logger instance
constructor(private readonly httpService: HttpService, private readonly queryGenService: QueryGeneratorService) {
constructor(
private readonly httpService: HttpService,
private readonly queryGenService: QueryGeneratorService,
) {
this.fusionauthClient = new FusionAuthClient(
process.env.FUSIONAUTH_API_KEY,
process.env.FUSIONAUTH_BASE_URL,
......@@ -210,7 +213,7 @@ export class FusionauthService {
persist(authObj: any): Promise<{ statusFA: FAStatus; userId: UUID }> {
this.logger.log(JSON.stringify(authObj));
var resp;
let resp;
const registrations: Array<UserRegistration> = [];
const currentRegistration: UserRegistration = {
username: authObj.username,
......@@ -260,7 +263,10 @@ export class FusionauthService {
this.logger.log(JSON.stringify({ res }));
})
.catch((e): Promise<{ statusFA: FAStatus; userId: UUID }> => {
this.logger.error('Could not create a user in', JSON.stringify(e));
this.logger.error(
'Could not create a user in',
JSON.stringify(e),
);
this.logger.error('Trying to fetch an existing user in');
return this.fusionauthClient
.retrieveUserByUsername(authObj.username)
......@@ -448,13 +454,15 @@ export class FusionauthService {
}
}
async createAndRegisterUser(user: RegistrationRequest): Promise<{userId: UUID, user: User, err: Error}> {
async createAndRegisterUser(
user: RegistrationRequest,
): Promise<{ userId: UUID; user: User; err: Error }> {
return this.fusionauthClient
.register(null, user)
.then(
(
response: ClientResponse<RegistrationResponse>,
): { userId: UUID; user: User, err: Error } => {
): { userId: UUID; user: User; err: Error } => {
this.logger.log('Found user');
return {
userId: response.response.user.id,
......@@ -463,17 +471,20 @@ export class FusionauthService {
};
},
)
.catch((e): { userId: UUID; user: User, err: Error } => {
.catch((e): { userId: UUID; user: User; err: Error } => {
this.logger.error(`Could not create user ${user}`, JSON.stringify(e));
return {
userId: null,
user: null,
err: e
err: e,
};
});
}
async updateUser(userId: string, user: UserRequest): Promise<{_userId: UUID, user: User, err: Error}> {
async updateUser(
userId: string,
user: UserRequest,
): Promise<{ _userId: UUID; user: User; err: Error }> {
return this.fusionauthClient
.patchUser(userId, user)
.then(
......@@ -484,21 +495,27 @@ export class FusionauthService {
return {
_userId: response.response.user.id,
user: response.response.user,
err: null
err: null,
};
},
)
.catch((e): { _userId: UUID; user: User; err: Error } => {
this.logger.error(`Could not update user ${user.user.id}`, JSON.stringify(e));
this.logger.error(
`Could not update user ${user.user.id}`,
JSON.stringify(e),
);
return {
_userId: null,
user: null,
err: e
err: e,
};
});
}
async upddatePasswordWithLoginId(data: {loginId: string, password: string}): Promise<any> {
async upddatePasswordWithLoginId(data: {
loginId: string;
password: string;
}): Promise<any> {
return this.httpService
.post(
process.env.FUSIONAUTH_BASE_URL + '/api/user/change-password',
......@@ -528,30 +545,52 @@ export class FusionauthService {
);
}
async updateUserRegistration(userId: UUID, registration: FusionAuthUserRegistration): Promise<{_userId: UUID, registration: FusionAuthUserRegistration, err: Error}> {
async updateUserRegistration(
userId: UUID,
registration: FusionAuthUserRegistration,
): Promise<{
_userId: UUID;
registration: FusionAuthUserRegistration;
err: Error;
}> {
return this.fusionauthClient
.patchRegistration(userId, { registration: registration })
.then(
(
response: ClientResponse<RegistrationResponse>,
): { _userId: UUID; registration: FusionAuthUserRegistration; err: Error } => {
): {
_userId: UUID;
registration: FusionAuthUserRegistration;
err: Error;
} => {
this.logger.log('Found user');
this.logger.log(JSON.stringify(response));
return {
_userId: userId,
registration: response.response.registration,
err: null
err: null,
};
},
)
.catch((e): { _userId: UUID; registration: FusionAuthUserRegistration; err: Error } => {
this.logger.error(`Could not update user ${userId}`, JSON.stringify(e));
return {
_userId: null,
registration: null,
err: e
};
});
.catch(
(
e,
): {
_userId: UUID;
registration: FusionAuthUserRegistration;
err: Error;
} => {
this.logger.error(
`Could not update user ${userId}`,
JSON.stringify(e),
);
return {
_userId: null,
registration: null,
err: e,
};
},
);
}
async getUserById(
......@@ -583,4 +622,65 @@ export class FusionauthService {
};
});
}
async deactivateUserById(
userId: string,
hardDelete: boolean,
): Promise<{ userId: UUID; err: Error }> {
if (hardDelete) {
return this.fusionauthClient
.deleteUser(userId)
.then(
(response: ClientResponse<void>): { userId: UUID; err: Error } => {
this.logger.log(response);
return { userId: userId, err: null };
},
)
.catch((e): { userId: UUID; err: Error } => {
this.logger.error(
`Could not update user ${userId}`,
JSON.stringify(e),
);
return {
userId: null,
err: e,
};
});
}
return this.fusionauthClient
.deactivateUser(userId)
.then((response: ClientResponse<void>): { userId: UUID; err: Error } => {
this.logger.log(response);
return { userId: userId, err: null };
})
.catch((e): { userId: UUID; err: Error } => {
this.logger.error(`Could not update user ${userId}`, JSON.stringify(e));
return {
userId: null,
err: e,
};
});
}
async activateUserById(
userId: string,
): Promise<{ userId: UUID; err: Error }> {
return this.fusionauthClient
.reactivateUser(userId)
.then(
(
response: ClientResponse<UserResponse>,
): { userId: UUID; err: Error } => {
this.logger.log(response);
return { userId: userId, err: null };
},
)
.catch((e): { userId: UUID; err: Error } => {
this.logger.error(`Could not update user ${userId}`, JSON.stringify(e));
return {
userId: null,
err: e,
};
});
}
}
......@@ -2,16 +2,14 @@ import { User } from '@fusionauth/typescript-client';
import {
Body,
Controller,
Request,
Get,
Headers,
Param,
Patch,
Post,
Query,
Headers,
} from '@nestjs/common';
import {
ApiConfig,
SignupResponse,
UserRegistration,
UsersResponse,
......@@ -22,8 +20,8 @@ import { FusionauthService } from './fusionauth/fusionauth.service';
import { OtpService } from './otp/otp.service';
import { SMSResponse } from './sms/sms.interface';
import { RefreshRequest } from '@fusionauth/typescript-client/build/src/FusionAuthClient';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const CryptoJS = require('crypto-js');
const AES = require('crypto-js/aes');
CryptoJS.lib.WordArray.words;
......@@ -38,15 +36,10 @@ export class ApiController {
@Get()
getHello(): any {
let respVar: {respCode: string, respMessage: string}= {respCode: "200", respMessage: "Hello!"};
const config: ApiConfig = this.configResolverService.getConfigByApplicationId("port");
const host = this.configResolverService.getHost("port");
const apiKey = this.configResolverService.getApiKey("port");
const encStatus = this.configResolverService.getEncryptionStatus("port");
const encKey = this.configResolverService.getEncryptionKey("port");
respVar['authHeader']="Dummy"
respVar['authHeader1'] = "authHeader1"
return {host: host, key: apiKey, encStatus: encStatus, encKey: encKey, respVar: respVar['authHeader']};
return {
respCode: '200',
respMessage: 'Hello!',
};
}
@Get('sendOTP')
......@@ -62,77 +55,124 @@ export class ApiController {
}
@Post('login')
async login(@Body() user: any, @Headers('authorization') authHeader): Promise<any> {
const encStatus = this.configResolverService.getEncryptionStatus(user.applicationId);
if(encStatus){
const encodedBase64Key = this.configResolverService.getEncryptionKey(user.applicationId);
const parsedBase64Key = encodedBase64Key === undefined? CryptoJS.enc.Base64.parse('bla'): CryptoJS.enc.Base64.parse(encodedBase64Key);
user.loginId = this.apiService.decrypt(user.loginId, parsedBase64Key);
user.password = this.apiService.decrypt(user.password, parsedBase64Key);
}
const status: SignupResponse = await this.apiService.login(user, authHeader);
return status;
async login(
@Body() user: any,
@Headers('authorization') authHeader,
): Promise<any> {
const encStatus = this.configResolverService.getEncryptionStatus(
user.applicationId,
);
if (encStatus) {
const encodedBase64Key = this.configResolverService.getEncryptionKey(
user.applicationId,
);
const parsedBase64Key =
encodedBase64Key === undefined
? CryptoJS.enc.Base64.parse('bla')
: CryptoJS.enc.Base64.parse(encodedBase64Key);
user.loginId = this.apiService.decrypt(user.loginId, parsedBase64Key);
user.password = this.apiService.decrypt(user.password, parsedBase64Key);
}
return await this.apiService.login(user, authHeader);
}
@Post('login/pin')
async loginByPin(@Body() user: any, @Headers('authorization') authHeader): Promise<any> {
const encStatus = this.configResolverService.getEncryptionStatus(user.applicationId);
const encodedBase64Key = this.configResolverService.getEncryptionKey(user.applicationId);
const parsedBase64Key = encodedBase64Key === undefined? CryptoJS.enc.Base64.parse('bla'): CryptoJS.enc.Base64.parse(encodedBase64Key);
if(encStatus){
user.loginId = this.apiService.decrypt(user.loginId, parsedBase64Key);
// user.password = this.apiService.decrypt(user.password, parsedBase64Key);
}else{
user.password = this.apiService.encrypt(user.password, parsedBase64Key);
}
async loginByPin(
@Body() user: any,
@Headers('authorization') authHeader,
): Promise<any> {
const encStatus = this.configResolverService.getEncryptionStatus(
user.applicationId,
);
const encodedBase64Key = this.configResolverService.getEncryptionKey(
user.applicationId,
);
const parsedBase64Key =
encodedBase64Key === undefined
? CryptoJS.enc.Base64.parse('bla')
: CryptoJS.enc.Base64.parse(encodedBase64Key);
if (encStatus) {
user.loginId = this.apiService.decrypt(user.loginId, parsedBase64Key);
// user.password = this.apiService.decrypt(user.password, parsedBase64Key);
} else {
user.password = this.apiService.encrypt(user.password, parsedBase64Key);
}
const status: SignupResponse = await this.apiService.login(user, authHeader);
return status;
return await this.apiService.login(user, authHeader);
}
//
@Get('all')
async fetchUsers(@Query() data: {
startRow: number;
numberOfResults: number;
}, @Headers('authorization') authHeader, @Headers('x-application-id') applicationId): Promise<UsersResponse> {
const users: UsersResponse = await this.apiService.fetchUsers(applicationId, data.startRow, data.numberOfResults, authHeader);
return users;
async fetchUsers(
@Query()
data: {
startRow: number;
numberOfResults: number;
},
@Headers('authorization') authHeader,
@Headers('x-application-id') applicationId,
): Promise<UsersResponse> {
return await this.apiService.fetchUsers(
applicationId,
data.startRow,
data.numberOfResults,
authHeader,
);
}
@Post('changePassword')
async updatePassword(
@Body() data: { loginId: string, password: string },
@Body() data: { loginId: string; password: string },
@Headers('authorization') authHeader,
@Headers('x-application-id') applicationId
@Headers('x-application-id') applicationId,
): Promise<SignupResponse> {
const status: SignupResponse = await this.apiService.updatePassword(data, applicationId, authHeader);
return status;
return await this.apiService.updatePassword(
data,
applicationId,
authHeader,
);
}
@Post('changePin')
async updatePin(
@Body() data: { loginId: string, password: string },
@Body() data: { loginId: string; password: string },
@Headers('authorization') authHeader,
@Headers('x-application-id') applicationId
@Headers('x-application-id') applicationId,
): Promise<SignupResponse> {
const encodedBase64Key = this.configResolverService.getEncryptionKey(applicationId);
const parsedBase64Key = encodedBase64Key === undefined? CryptoJS.enc.Base64.parse('bla'): CryptoJS.enc.Base64.parse(encodedBase64Key);
const encodedBase64Key =
this.configResolverService.getEncryptionKey(applicationId);
const parsedBase64Key =
encodedBase64Key === undefined
? CryptoJS.enc.Base64.parse('bla')
: CryptoJS.enc.Base64.parse(encodedBase64Key);
data.password = this.apiService.encrypt(data.password, parsedBase64Key);
const status: SignupResponse = await this.apiService.updatePassword(data, applicationId, authHeader);
return status;
return await this.apiService.updatePassword(
data,
applicationId,
authHeader,
);
}
@Post('signup')
async createUser(@Body() data: UserRegistration, @Headers('authorization') authHeader, @Headers('x-application-id') applicationId): Promise<SignupResponse> {
const users: SignupResponse = await this.apiService.createUser(data, applicationId, authHeader);
return users;
async createUser(
@Body() data: UserRegistration,
@Headers('authorization') authHeader,
@Headers('x-application-id') applicationId,
): Promise<SignupResponse> {
return await this.apiService.createUser(data, applicationId, authHeader);
}
@Post('signupByPin')
async createUserByPin(@Body() data: UserRegistration, @Headers('authorization') authHeader, @Headers('x-application-id') applicationId): Promise<SignupResponse> {
const users: SignupResponse = await this.apiService.createUserByPin(data, applicationId, authHeader);
return users;
async createUserByPin(
@Body() data: UserRegistration,
@Headers('authorization') authHeader,
@Headers('x-application-id') applicationId,
): Promise<SignupResponse> {
return await this.apiService.createUserByPin(
data,
applicationId,
authHeader,
);
}
@Patch('updateUser/:userId')
......@@ -140,10 +180,14 @@ export class ApiController {
@Param('userId') userId: string,
@Body() data: User,
@Headers('authorization') authHeader,
@Headers('x-application-id') applicationId
@Headers('x-application-id') applicationId,
): Promise<SignupResponse> {
const user: SignupResponse = await this.apiService.updateUser(userId, data, applicationId, authHeader);
return user;
return await this.apiService.updateUser(
userId,
data,
applicationId,
authHeader,
);
}
@Get('searchUserByQuery')
......@@ -155,33 +199,31 @@ export class ApiController {
numberOfResults: number;
},
@Headers('authorization') authHeader,
@Headers('x-application-id') applicationId
@Headers('x-application-id') applicationId,
): Promise<UsersResponse> {
console.log(query.numberOfResults);
const users: UsersResponse = await this.apiService.fetchUsersByString(
return await this.apiService.fetchUsersByString(
query.queryString,
query.startRow,
query.numberOfResults,
applicationId,
authHeader
authHeader,
);
return users;
}
@Get('user/:userId')
async searchUserbyId(
@Param('userId') userId: string,
@Headers('authorization') authHeader,
@Headers('x-application-id') applicationId
@Headers('x-application-id') applicationId,
): Promise<UsersResponse> {
const users: UsersResponse = await this.apiService.fetchUsersByString(
return await this.apiService.fetchUsersByString(
userId,
undefined,
undefined,
applicationId,
authHeader
authHeader,
);
return users;
}
@Post('refresh-token')
......@@ -196,4 +238,32 @@ export class ApiController {
authHeader,
);
}
@Patch('/user/:userId/deactivate')
async deactivateUserById(
@Param('userId') userId: string,
@Query('hardDelete') hardDelete = false,
@Headers('authorization') authHeader,
@Headers('x-application-id') applicationId,
): Promise<UsersResponse> {
return await this.apiService.deactivateUserById(
userId,
hardDelete,
applicationId,
authHeader,
);
}
@Patch('/user/:userId/activate')
async activateUserById(
@Param('userId') userId: string,
@Headers('authorization') authHeader,
@Headers('x-application-id') applicationId,
): Promise<UsersResponse> {
return await this.apiService.activateUserById(
userId,
applicationId,
authHeader,
);
}
}
import { LoginResponse, User, UUID, Error } from '@fusionauth/typescript-client';
import {
Error,
LoginResponse,
User,
UUID,
} from '@fusionauth/typescript-client';
import ClientResponse from '@fusionauth/typescript-client/build/src/ClientResponse';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
RefreshTokenResult,
ResponseCode,
ResponseStatus,
SignupResponse,
UsersResponse,
UserRegistration,
RefreshTokenResult,
UsersResponse,
} from './api.interface';
import { FusionauthService } from './fusionauth/fusionauth.service';
import { OtpService } from './otp/otp.service';
import { v4 as uuidv4 } from 'uuid';
import { ConfigResolverService } from './config.resolver.service';
import { RefreshRequest } from '@fusionauth/typescript-client/build/src/FusionAuthClient';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const CryptoJS = require('crypto-js');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const AES = require('crypto-js/aes');
CryptoJS.lib.WordArray.words;
......@@ -23,7 +30,7 @@ CryptoJS.lib.WordArray.words;
@Injectable()
export class ApiService {
encodedBase64Key;
parsedBase64Key
parsedBase64Key;
constructor(
private configService: ConfigService,
private readonly fusionAuthService: FusionauthService,
......@@ -32,10 +39,17 @@ export class ApiService {
) {}
login(user: any, authHeader: string): Promise<SignupResponse> {
const encStatus = this.configResolverService.getEncryptionStatus(user.applicationId);
if(encStatus){
this.encodedBase64Key = this.configResolverService.getEncryptionKey(user.applicationId);
this.parsedBase64Key = this.encodedBase64Key === undefined? CryptoJS.enc.Base64.parse('bla'): CryptoJS.enc.Base64.parse(this.encodedBase64Key);
const encStatus = this.configResolverService.getEncryptionStatus(
user.applicationId,
);
if (encStatus) {
this.encodedBase64Key = this.configResolverService.getEncryptionKey(
user.applicationId,
);
this.parsedBase64Key =
this.encodedBase64Key === undefined
? CryptoJS.enc.Base64.parse('bla')
: CryptoJS.enc.Base64.parse(this.encodedBase64Key);
user.loginId = this.encrypt(user.loginId, this.parsedBase64Key);
user.password = this.encrypt(user.password, this.parsedBase64Key);
}
......@@ -57,7 +71,7 @@ export class ApiService {
// }else {
// fusionAuthUser['user']['data']['accountName'] = user.loginId;
// }
// } else {
// fusionAuthUser['user']['data']['accountName'] =
// fusionAuthUser.user.firstName;
......@@ -97,8 +111,13 @@ export class ApiService {
}
loginByPin(user: any, authHeader: string): Promise<SignupResponse> {
this.encodedBase64Key = this.configResolverService.getEncryptionKey(user.applicationId);
this.parsedBase64Key = this.encodedBase64Key === undefined? CryptoJS.enc.Base64.parse('bla'): CryptoJS.enc.Base64.parse(this.encodedBase64Key);
this.encodedBase64Key = this.configResolverService.getEncryptionKey(
user.applicationId,
);
this.parsedBase64Key =
this.encodedBase64Key === undefined
? CryptoJS.enc.Base64.parse('bla')
: CryptoJS.enc.Base64.parse(this.encodedBase64Key);
return this.fusionAuthService
.login(user, authHeader)
.then(async (resp: ClientResponse<LoginResponse>) => {
......@@ -150,7 +169,12 @@ export class ApiService {
});
}
async fetchUsers(applicationId: string, startRow?: number, numberOfResults?: number, authHeader?: string): Promise<UsersResponse> {
async fetchUsers(
applicationId: string,
startRow?: number,
numberOfResults?: number,
authHeader?: string,
): Promise<UsersResponse> {
const { total, users }: { total: number; users: Array<User> } =
await this.fusionAuthService.getUsers(
applicationId,
......@@ -172,13 +196,29 @@ export class ApiService {
return response;
}
async updatePassword(data: {loginId: string, password: string}, applicationId: string, authHeader?: string): Promise<any> {
return this.fusionAuthService.upddatePasswordWithLoginId(data, applicationId, authHeader);
}
async updatePassword(
data: { loginId: string; password: string },
applicationId: string,
authHeader?: string,
): Promise<any> {
return this.fusionAuthService.upddatePasswordWithLoginId(
data,
applicationId,
authHeader,
);
}
async createUser(data: UserRegistration, applicationId: string, authHeader?: string): Promise<SignupResponse> {
async createUser(
data: UserRegistration,
applicationId: string,
authHeader?: string,
): Promise<SignupResponse> {
const { userId, user, err }: { userId: UUID; user: User; err: Error } =
await this.fusionAuthService.createAndRegisterUser(data, applicationId , authHeader);
await this.fusionAuthService.createAndRegisterUser(
data,
applicationId,
authHeader,
);
if (userId == null || user == null) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
......@@ -187,12 +227,24 @@ async createUser(data: UserRegistration, applicationId: string, authHeader?: str
return response;
}
async createUserByPin(data: UserRegistration, applicationId: string, authHeader?: string): Promise<SignupResponse> {
const encodedBase64Key = this.configResolverService.getEncryptionKey(applicationId);
const parsedBase64Key = encodedBase64Key === undefined? CryptoJS.enc.Base64.parse('bla'): CryptoJS.enc.Base64.parse(encodedBase64Key);
data.user.password = this.encrypt(data.user.password, parsedBase64Key)
async createUserByPin(
data: UserRegistration,
applicationId: string,
authHeader?: string,
): Promise<SignupResponse> {
const encodedBase64Key =
this.configResolverService.getEncryptionKey(applicationId);
const parsedBase64Key =
encodedBase64Key === undefined
? CryptoJS.enc.Base64.parse('bla')
: CryptoJS.enc.Base64.parse(encodedBase64Key);
data.user.password = this.encrypt(data.user.password, parsedBase64Key);
const { userId, user, err }: { userId: UUID; user: User; err: Error } =
await this.fusionAuthService.createAndRegisterUser(data, applicationId , authHeader);
await this.fusionAuthService.createAndRegisterUser(
data,
applicationId,
authHeader,
);
if (userId == null || user == null) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
......@@ -201,9 +253,19 @@ async createUser(data: UserRegistration, applicationId: string, authHeader?: str
return response;
}
async updateUser(userId: string, data: User, applicationId: string, authHeader?: string): Promise<any> {
async updateUser(
userId: string,
data: User,
applicationId: string,
authHeader?: string,
): Promise<any> {
const { _userId, user, err }: { _userId: UUID; user: User; err: Error } =
await this.fusionAuthService.updateUser(userId, {user: data}, applicationId, authHeader);
await this.fusionAuthService.updateUser(
userId,
{ user: data },
applicationId,
authHeader,
);
if (_userId == null || user == null) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
......@@ -217,7 +279,7 @@ async createUser(data: UserRegistration, applicationId: string, authHeader?: str
startRow: number,
numberOfResults: number,
applicationId: string,
authHeader?: string
authHeader?: string,
): Promise<UsersResponse> {
const { total, users }: { total: number; users: Array<User> } =
await this.fusionAuthService.getUsersByString(
......@@ -225,7 +287,7 @@ async createUser(data: UserRegistration, applicationId: string, authHeader?: str
startRow,
numberOfResults,
applicationId,
authHeader
authHeader,
);
const response: UsersResponse = new UsersResponse().init(uuidv4());
if (users != null) {
......@@ -242,17 +304,15 @@ async createUser(data: UserRegistration, applicationId: string, authHeader?: str
}
encrypt(plainString: any, key: string): any {
const encryptedString = AES.encrypt(plainString, key, {
return AES.encrypt(plainString, key, {
mode: CryptoJS.mode.ECB,
}).toString();
return encryptedString;
}
decrypt(encryptedString: any, key: string): any {
const plainString = AES.decrypt(encryptedString, key, {
return AES.decrypt(encryptedString, key, {
mode: CryptoJS.mode.ECB,
}).toString(CryptoJS.enc.Utf8);
return plainString;
}
async refreshToken(
......@@ -281,4 +341,58 @@ async createUser(data: UserRegistration, applicationId: string, authHeader?: str
return response;
}
async deactivateUserById(
userId: string,
hardDelete: boolean,
applicationId: string,
authHeader?: string,
): Promise<any> {
const activationResponse: { userId: UUID; err: Error } =
await this.fusionAuthService.deactivateUserById(
userId,
hardDelete,
applicationId,
authHeader,
);
if (activationResponse.userId == null) {
throw new HttpException(activationResponse.err, HttpStatus.BAD_REQUEST);
}
// fetch the latest user info now & respond
const userResponse = await this.fusionAuthService.getUserById(
userId,
applicationId,
authHeader,
);
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.result = userResponse.user;
return response;
}
async activateUserById(
userId: string,
applicationId: string,
authHeader?: string,
): Promise<any> {
const activationResponse: { userId: UUID; err: Error } =
await this.fusionAuthService.activateUserById(
userId,
applicationId,
authHeader,
);
if (activationResponse.userId == null) {
throw new HttpException(activationResponse.err, HttpStatus.BAD_REQUEST);
}
// fetch the latest user info now & respond
const userResponse = await this.fusionAuthService.getUserById(
userId,
applicationId,
authHeader,
);
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.result = userResponse.user;
return response;
}
}
......@@ -16,7 +16,7 @@ import FusionAuthClient, {
} from '@fusionauth/typescript-client';
import ClientResponse from '@fusionauth/typescript-client/build/src/ClientResponse';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { catchError, map } from 'rxjs';
import { QueryGeneratorService } from './query-generator/query-generator.service';
......@@ -33,6 +33,7 @@ export enum FAStatus {
@Injectable()
export class FusionauthService {
fusionauthClient: FusionAuthClient;
protected readonly logger = new Logger(FusionauthService.name); // logger instance
constructor(
private readonly httpService: HttpService,
......@@ -221,8 +222,6 @@ export class FusionauthService {
persist(authObj: any): Promise<{ statusFA: FAStatus; userId: UUID }> {
console.log(authObj);
let resp;
let resp1;
const responses: Array<{ statusFA: FAStatus; userId: UUID }> = [];
const registrations: Array<UserRegistration> = [];
const currentRegistration: UserRegistration = {
username: authObj.username,
......@@ -260,6 +259,7 @@ export class FusionauthService {
const userRequest_samarth_hp: RegistrationRequest = {
registration: currentRegistration_samarth_hp,
};
// eslint-disable-next-line prefer-const
resp = this.fusionauthClient
.register(undefined, userRequest)
.then(
......@@ -620,4 +620,119 @@ export class FusionauthService {
};
});
}
async getUserById(
userId: UUID,
applicationId,
authHeader?: string,
): Promise<{ statusFA: FAStatus; userId: UUID; user: User }> {
let apiKey = this.configResolverService.getApiKey(applicationId);
if (authHeader != null) {
apiKey = authHeader;
}
const host = this.configResolverService.getHost(applicationId);
const fusionauthClient = this.getClient(apiKey, host);
return fusionauthClient
.retrieveUser(userId)
.then(
(
response: ClientResponse<UserResponse>,
): { statusFA: FAStatus; userId: UUID; user: User } => {
this.logger.log('Found user');
return {
statusFA: FAStatus.USER_EXISTS,
userId: response.response.user.id,
user: response.response.user,
};
},
)
.catch((e): { statusFA: FAStatus; userId: UUID; user: User } => {
this.logger.error(
`Could not fetch user with user id ${userId}`,
JSON.stringify(e),
);
return {
statusFA: FAStatus.ERROR,
userId: null,
user: null,
};
});
}
async deactivateUserById(
userId: string,
hardDelete: boolean,
applicationId,
authHeader?: string,
): Promise<{ userId: UUID; err: Error }> {
let apiKey = this.configResolverService.getApiKey(applicationId);
if (authHeader != null) {
apiKey = authHeader;
}
const host = this.configResolverService.getHost(applicationId);
const fusionauthClient = this.getClient(apiKey, host);
if (hardDelete) {
return fusionauthClient
.deleteUser(userId)
.then(
(response: ClientResponse<void>): { userId: UUID; err: Error } => {
this.logger.log(response);
return { userId: userId, err: null };
},
)
.catch((e): { userId: UUID; err: Error } => {
this.logger.error(
`Could not update user ${userId}`,
JSON.stringify(e),
);
return {
userId: null,
err: e,
};
});
}
return fusionauthClient
.deactivateUser(userId)
.then((response: ClientResponse<void>): { userId: UUID; err: Error } => {
this.logger.log(response);
return { userId: userId, err: null };
})
.catch((e): { userId: UUID; err: Error } => {
this.logger.error(`Could not update user ${userId}`, JSON.stringify(e));
return {
userId: null,
err: e,
};
});
}
async activateUserById(
userId: string,
applicationId,
authHeader?: string,
): Promise<{ userId: UUID; err: Error }> {
let apiKey = this.configResolverService.getApiKey(applicationId);
if (authHeader != null) {
apiKey = authHeader;
}
const host = this.configResolverService.getHost(applicationId);
const fusionauthClient = this.getClient(apiKey, host);
return fusionauthClient
.reactivateUser(userId)
.then(
(
response: ClientResponse<UserResponse>,
): { userId: UUID; err: Error } => {
this.logger.log(response);
return { userId: userId, err: null };
},
)
.catch((e): { userId: UUID; err: Error } => {
this.logger.error(`Could not update user ${userId}`, JSON.stringify(e));
return {
userId: null,
err: e,
};
});
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment