Skip to content

Commit ab9fb63

Browse files
committed
WIP:create account and session workflow modification
Signed-off-by: shitrerohit <[email protected]>
1 parent 92238cd commit ab9fb63

File tree

9 files changed

+70
-108
lines changed

9 files changed

+70
-108
lines changed

.env.demo

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,12 @@ OTEL_LOGGER_NAME='credebl-platform-logger'
158158
HOSTNAME='localhost'
159159
SESSIONS_LIMIT=10
160160
# SSO
161+
APP_PROTOCOL=http
162+
#To add more clients, simply copy the variable below and change the word 'CREDEBL' to your client's name.
163+
CREDEBL_CLIENT_ALIAS=CREDEBL
164+
CREDEBL_DOMAIN=http://localhost:3000
165+
CREDEBL_KEYCLOAK_MANAGEMENT_CLIENT_ID= #Provide the value in its encrypted form using CRYPTO_PRIVATE_KEY.
166+
CREDEBL_KEYCLOAK_MANAGEMENT_CLIENT_SECRET= #Provide the value in its encrypted form using CRYPTO_PRIVATE_KEY.
161167
# To add more clients, simply add comma separated values of client names
162168
SUPPORTED_SSO_CLIENTS=CREDEBL
163169

.env.sample

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,9 +178,14 @@ OTEL_LOGGER_NAME='credebl-platform-logger' # Name of the logger used for O
178178
HOSTNAME='localhost' # Hostname or unique identifier for the service instance
179179

180180
# SSO
181+
#To add more clients, simply copy the variable below and change the word 'CREDEBL' to your client's name.
182+
CREDEBL_CLIENT_ALIAS=CREDEBL
183+
CREDEBL_DOMAIN=http://localhost:3000
184+
CREDEBL_KEYCLOAK_MANAGEMENT_CLIENT_ID= #Provide the value in its encrypted form using CRYPTO_PRIVATE_KEY.
185+
CREDEBL_KEYCLOAK_MANAGEMENT_CLIENT_SECRET= #Provide the value in its encrypted form using CRYPTO_PRIVATE_KEY.
181186
# To add more clients, simply add comma separated values of client names
182187
SUPPORTED_SSO_CLIENTS=CREDEBL
183-
NEXTAUTH_PROTOCOL=
188+
APP_PROTOCOL=
184189

185190
# Key for agent base wallet
186191
AGENT_API_KEY='supersecret-that-too-16chars'

apps/api-gateway/src/organization/organization.controller.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,7 @@ export class OrganizationController {
559559
res.cookie('session_id', orgCredentials.sessionId, {
560560
httpOnly: true,
561561
sameSite: 'none',
562-
secure: 'http' !== process.env.NEXTAUTH_PROTOCOL
562+
secure: 'http' !== process.env.APP_PROTOCOL
563563
});
564564

565565
return res.status(HttpStatus.OK).json(finalResponse);

apps/organization/src/organization.service.ts

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -726,24 +726,14 @@ export class OrganizationService {
726726
// Otherwise, create a new account and also create the new session
727727
const fetchAccountDetails = await this.userRepository.checkAccountDetails(orgRoleDetails['user'].id);
728728
if (fetchAccountDetails) {
729-
const accountData = {
730-
sessionToken: authenticationResult?.access_token,
731-
userId: orgRoleDetails['user'].id,
732-
expires: authenticationResult?.expires_in
733-
};
734-
735-
await this.userRepository.updateAccountDetails(accountData).then(async (response) => {
736-
const finalSessionData = { ...sessionData, accountId: response.id };
737-
addSessionDetails = await this.userRepository.createSession(finalSessionData);
738-
});
729+
const finalSessionData = { ...sessionData, accountId: fetchAccountDetails.id };
730+
addSessionDetails = await this.userRepository.createSession(finalSessionData);
739731
} else {
740732
// Note:
741733
// This else block is mostly used for already registered users on the platform to create their account & session in the database.
742734
// Once all users are migrated or created their accounts and sessions in the DB, this code can be removed.
743735
const accountData = {
744-
sessionToken: authenticationResult?.access_token,
745736
userId: orgRoleDetails['user'].id,
746-
expires: authenticationResult?.expires_in,
747737
keycloakUserId: orgRoleDetails['user'].keycloakUserId,
748738
type: TokenType.BEARER_TOKEN
749739
};

apps/user/repositories/user.repository.ts

Lines changed: 17 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1+
/* eslint-disable camelcase */
12
/* eslint-disable prefer-destructuring */
23

34
import {
45
IOrgUsers,
56
ISendVerificationEmail,
67
ISession,
78
IShareUserCertificate,
8-
IUpdateAccountDetails,
99
IUserDeletedActivity,
1010
IUserInformation,
1111
IUsersProfile,
@@ -17,7 +17,6 @@ import {
1717
UserRoleMapping
1818
} from '../interfaces/user.interface';
1919
import { Injectable, InternalServerErrorException, Logger, NotFoundException } from '@nestjs/common';
20-
// eslint-disable-next-line camelcase
2120
import {
2221
Prisma,
2322
RecordType,
@@ -725,67 +724,13 @@ export class UserRepository {
725724
}
726725
}
727726

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-
760-
async updateAccountDetails(accountDetails: ISession): Promise<account> {
761-
try {
762-
const userAccountDetails = await this.prisma.account.update({
763-
where: {
764-
userId: accountDetails.userId
765-
},
766-
data: {
767-
accessToken: accountDetails.sessionToken,
768-
refreshToken: accountDetails.refreshToken,
769-
expiresAt: accountDetails.expires
770-
}
771-
});
772-
return userAccountDetails;
773-
} catch (error) {
774-
this.logger.error(`Error in updateAccountDetails: ${error.message}`);
775-
throw error;
776-
}
777-
}
778-
779727
async addAccountDetails(accountDetails: ISession): Promise<account> {
780728
try {
781729
const userAccountDetails = await this.prisma.account.create({
782730
data: {
783731
userId: accountDetails.userId,
784732
provider: ProviderType.KEYCLOAK,
785733
providerAccountId: accountDetails.keycloakUserId,
786-
accessToken: accountDetails.sessionToken,
787-
refreshToken: accountDetails.refreshToken,
788-
expiresAt: accountDetails.expires,
789734
tokenType: accountDetails.type
790735
}
791736
});
@@ -1014,11 +959,11 @@ export class UserRepository {
1014959
}
1015960
}
1016961

1017-
async deleteSessionRecordByRefreshToken(refreshToken: string): Promise<session> {
962+
async deleteSessionRecordByRefreshToken(sessionId: string): Promise<session> {
1018963
try {
1019964
const userSession = await this.prisma.session.delete({
1020965
where: {
1021-
refreshToken
966+
id: sessionId
1022967
}
1023968
});
1024969
return userSession;
@@ -1027,4 +972,18 @@ export class UserRepository {
1027972
throw error;
1028973
}
1029974
}
975+
976+
async fetchSessionByRefreshToken(refreshToken: string): Promise<session> {
977+
try {
978+
const sessionDetails = await this.prisma.session.findFirst({
979+
where: {
980+
refreshToken
981+
}
982+
});
983+
return sessionDetails;
984+
} catch (error) {
985+
this.logger.error(`Error in fetching session details::${error.message}`);
986+
throw error;
987+
}
988+
}
1030989
}

apps/user/src/user.service.ts

Lines changed: 10 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -489,10 +489,7 @@ export class UserService {
489489
let accountData;
490490
if (null === fetchAccountDetails) {
491491
accountData = {
492-
sessionToken: tokenDetails?.access_token,
493492
userId: userData?.id,
494-
expires: tokenDetails?.expires_in,
495-
refreshToken: tokenDetails?.refresh_token,
496493
keycloakUserId: userData?.keycloakUserId,
497494
type: TokenType.BEARER_TOKEN
498495
};
@@ -502,17 +499,8 @@ export class UserService {
502499
addSessionDetails = await this.userRepository.createSession(finalSessionData);
503500
});
504501
} else {
505-
accountData = {
506-
sessionToken: tokenDetails?.access_token,
507-
userId: userData?.id,
508-
expires: tokenDetails?.expires_in,
509-
refreshToken: tokenDetails?.refresh_token
510-
};
511-
512-
await this.userRepository.updateAccountDetails(accountData).then(async (response) => {
513-
const finalSessionData = { ...sessionData, accountId: response.id };
514-
addSessionDetails = await this.userRepository.createSession(finalSessionData);
515-
});
502+
const finalSessionData = { ...sessionData, accountId: fetchAccountDetails.id };
503+
addSessionDetails = await this.userRepository.createSession(finalSessionData);
516504
}
517505

518506
const finalResponse = {
@@ -554,26 +542,18 @@ export class UserService {
554542
);
555543
this.logger.debug(`tokenResponse::::${JSON.stringify(tokenResponse)}`);
556544
// 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-
);
545+
const userAccountDetails = await this.userRepository.checkAccountDetails(userByKeycloakId?.['id']);
561546
// Update the account details with latest access token, refresh token and exp date
562547
if (!userAccountDetails) {
563548
throw new NotFoundException(ResponseMessages.user.error.userAccountNotFound);
564549
}
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);
550+
// Fetch session details
551+
const sessionDetails = await this.userRepository.fetchSessionByRefreshToken(refreshToken);
552+
if (!sessionDetails) {
553+
throw new NotFoundException(ResponseMessages.user.error.userSeesionNotFound);
575554
}
576-
const deletePreviousSession = await this.userRepository.deleteSessionRecordByRefreshToken(refreshToken);
555+
// Delete previous session
556+
const deletePreviousSession = await this.userRepository.deleteSessionRecordByRefreshToken(sessionDetails.id);
577557
if (!deletePreviousSession) {
578558
throw new InternalServerErrorException(ResponseMessages.user.error.errorInDeleteSession);
579559
}
@@ -583,7 +563,7 @@ export class UserService {
583563
expires: tokenResponse.expires_in,
584564
refreshToken: tokenResponse.refresh_token,
585565
sessionType: SessionType.USER_SESSION,
586-
accountId: updateAccountDetailsResponse.id
566+
accountId: userAccountDetails.id
587567
};
588568
const addSessionDetails = await this.userRepository.createSession(sessionData);
589569
if (!addSessionDetails) {

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,8 @@ export const ResponseMessages = {
7070
errorInUpdateAccountDetails: 'Error in updating the account details',
7171
errorInDeleteSession: 'Error in deleting the session',
7272
errorInSessionCreation: 'Error in create session',
73-
userAccountNotFound: 'User account not found'
73+
userAccountNotFound: 'User account not found',
74+
userSeesionNotFound: 'User session not found'
7475
}
7576
},
7677
organisation: {
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
Warnings:
3+
4+
- You are about to drop the column `accessToken` on the `account` table. All the data in the column will be lost.
5+
- You are about to drop the column `expiresAt` on the `account` table. All the data in the column will be lost.
6+
- You are about to drop the column `refreshToken` on the `account` table. All the data in the column will be lost.
7+
8+
*/
9+
-- DropIndex
10+
DROP INDEX "account_accessToken_key";
11+
12+
-- DropIndex
13+
DROP INDEX "account_refreshToken_key";
14+
15+
-- DropIndex
16+
DROP INDEX "session_refreshToken_key";
17+
18+
-- DropIndex
19+
DROP INDEX "session_sessionToken_key";
20+
21+
-- AlterTable
22+
ALTER TABLE "account" DROP COLUMN "accessToken",
23+
DROP COLUMN "expiresAt",
24+
DROP COLUMN "refreshToken";

libs/prisma-service/prisma/schema.prisma

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,6 @@ model account {
4444
type String?
4545
provider String
4646
providerAccountId String
47-
refreshToken String? @unique
48-
accessToken String? @unique
49-
expiresAt Int?
5047
tokenType String?
5148
scope String?
5249
idToken String?
@@ -59,10 +56,10 @@ model account {
5956

6057
model session {
6158
id String @id @default(uuid()) @db.Uuid
62-
sessionToken String @unique
59+
sessionToken String
6360
userId String @db.Uuid
6461
expires Int
65-
refreshToken String? @unique
62+
refreshToken String?
6663
user user @relation(fields: [userId], references: [id])
6764
createdAt DateTime @default(now())
6865
updatedAt DateTime @updatedAt

0 commit comments

Comments
 (0)