Skip to content

Commit 084a268

Browse files
committed
WIP:refresh token flow modification
Signed-off-by: shitrerohit <[email protected]>
1 parent c6b330b commit 084a268

File tree

4 files changed

+100
-2
lines changed

4 files changed

+100
-2
lines changed

apps/user/interfaces/user.interface.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,13 @@ export interface ISession {
192192
sessionType?: string;
193193
}
194194

195+
export interface IUpdateAccountDetails {
196+
accessToken: string;
197+
refreshToken?: string;
198+
expiresAt: number;
199+
accountId: string;
200+
}
201+
195202
export interface ISessionDetails extends ISession {
196203
id: string;
197204
createdAt: Date;

apps/user/repositories/user.repository.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
ISendVerificationEmail,
66
ISession,
77
IShareUserCertificate,
8+
IUpdateAccountDetails,
89
IUserDeletedActivity,
910
IUserInformation,
1011
IUsersProfile,
@@ -724,6 +725,38 @@ export class UserRepository {
724725
}
725726
}
726727

728+
async fetchAccountByRefreshToken(userId: string, refreshToken: string): Promise<account> {
729+
try {
730+
return await this.prisma.account.findUnique({
731+
where: {
732+
userId,
733+
refreshToken
734+
}
735+
});
736+
} catch (error) {
737+
this.logger.error(`Error in getting account details: ${error.message} `);
738+
throw error;
739+
}
740+
}
741+
742+
async updateAccountDetailsById(accountDetails: IUpdateAccountDetails): Promise<account> {
743+
try {
744+
return await this.prisma.account.update({
745+
where: {
746+
id: accountDetails.accountId
747+
},
748+
data: {
749+
accessToken: accountDetails.accessToken,
750+
refreshToken: accountDetails.refreshToken,
751+
expiresAt: accountDetails.expiresAt
752+
}
753+
});
754+
} catch (error) {
755+
this.logger.error(`Error in getting account details: ${error.message} `);
756+
throw error;
757+
}
758+
}
759+
727760
async updateAccountDetails(accountDetails: ISession): Promise<account> {
728761
try {
729762
const userAccountDetails = await this.prisma.account.update({
@@ -980,4 +1013,18 @@ export class UserRepository {
9801013
throw error;
9811014
}
9821015
}
1016+
1017+
async deleteSessionRecordByRefreshToken(refreshToken: string): Promise<session> {
1018+
try {
1019+
const userSession = await this.prisma.session.delete({
1020+
where: {
1021+
refreshToken
1022+
}
1023+
});
1024+
return userSession;
1025+
} catch (error) {
1026+
this.logger.error(`Error in logging out user: ${error.message}`);
1027+
throw error;
1028+
}
1029+
}
9831030
}

apps/user/src/user.service.ts

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ import {
4141
IEcosystemConfig,
4242
IUserForgotPassword,
4343
ISessionDetails,
44-
ISessions
44+
ISessions,
45+
IUpdateAccountDetails
4546
} from '../interfaces/user.interface';
4647
import { AcceptRejectInvitationDto } from '../dtos/accept-reject-invitation.dto';
4748
import { UserActivityService } from '@credebl/user-activity';
@@ -545,11 +546,50 @@ export class UserService {
545546
try {
546547
const data = jwt.decode(refreshToken) as jwt.JwtPayload;
547548
const userByKeycloakId = await this.userRepository.getUserByKeycloakId(data?.sub);
549+
this.logger.debug(`User details::;${JSON.stringify(userByKeycloakId)}`);
548550
const tokenResponse = await this.clientRegistrationService.getAccessToken(
549551
refreshToken,
550552
userByKeycloakId?.['clientId'],
551553
userByKeycloakId?.['clientSecret']
552554
);
555+
this.logger.debug(`tokenResponse::::${JSON.stringify(tokenResponse)}`);
556+
// Fetch the details from account table based on userid and refresh token
557+
const userAccountDetails = await this.userRepository.fetchAccountByRefreshToken(
558+
userByKeycloakId?.['id'],
559+
refreshToken
560+
);
561+
// Update the account details with latest access token, refresh token and exp date
562+
if (!userAccountDetails) {
563+
throw new NotFoundException(ResponseMessages.user.error.userAccountNotFound);
564+
}
565+
const updateAccountDetails: IUpdateAccountDetails = {
566+
accessToken: tokenResponse.access_token,
567+
// refreshToken: tokenResponse.refresh_token,
568+
expiresAt: tokenResponse.expires_in,
569+
accountId: userAccountDetails.id
570+
};
571+
const updateAccountDetailsResponse = await this.userRepository.updateAccountDetailsById(updateAccountDetails);
572+
// Delete the preveious session record and create new one
573+
if (!updateAccountDetailsResponse) {
574+
throw new InternalServerErrorException(ResponseMessages.user.error.errorInUpdateAccountDetails);
575+
}
576+
const deletePreviousSession = await this.userRepository.deleteSessionRecordByRefreshToken(refreshToken);
577+
if (!deletePreviousSession) {
578+
throw new InternalServerErrorException(ResponseMessages.user.error.errorInDeleteSession);
579+
}
580+
const sessionData = {
581+
sessionToken: tokenResponse.access_token,
582+
userId: userByKeycloakId?.['id'],
583+
expires: tokenResponse.expires_in,
584+
// refreshToken: tokenResponse.refresh_token,
585+
sessionType: SessionType.USER_SESSION,
586+
accountId: updateAccountDetailsResponse.id
587+
};
588+
const addSessionDetails = await this.userRepository.createSession(sessionData);
589+
if (!addSessionDetails) {
590+
throw new InternalServerErrorException(ResponseMessages.user.error.errorInSessionCreation);
591+
}
592+
553593
return tokenResponse;
554594
} catch (error) {
555595
throw new BadRequestException(ResponseMessages.user.error.invalidRefreshToken);

libs/common/src/response-messages/index.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,11 @@ export const ResponseMessages = {
6666
invalidResetLink: 'Invalid or expired reset password link',
6767
invalidAccessToken: 'Authentication failed',
6868
invalidRefreshToken: 'Invalid refreshToken provided',
69-
userOrgsLimit: 'Limit reached: You can be associated with or create maximum 10 organizations.'
69+
userOrgsLimit: 'Limit reached: You can be associated with or create maximum 10 organizations.',
70+
errorInUpdateAccountDetails: 'Error in updating the account details',
71+
errorInDeleteSession: 'Error in deleting the session',
72+
errorInSessionCreation: 'Error in create session',
73+
userAccountNotFound: 'User account not found'
7074
}
7175
},
7276
organisation: {

0 commit comments

Comments
 (0)