Skip to content

Commit

Permalink
add
Browse files Browse the repository at this point in the history
  • Loading branch information
Sourav-Tekdi committed Jan 16, 2025
1 parent ea303be commit 3177f36
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 51 deletions.
55 changes: 30 additions & 25 deletions src/adapters/postgres/user-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,6 @@ export class PostgresUserService implements IServicelocator {
private tenantsRepository: Repository<Tenants>,
@InjectRepository(UserRoleMapping)
private userRoleMappingRepository: Repository<UserRoleMapping>,
@InjectRepository(Cohort)
private cohortRepository: Repository<Cohort>,
@InjectRepository(Role)
private roleRepository: Repository<Role>,
private fieldsService: PostgresFieldsService,
Expand Down Expand Up @@ -906,26 +904,26 @@ export class PostgresUserService implements IServicelocator {
try {
// Fetch the user by ID
const user = await this.usersRepository.findOne({ where: { userId } });

if (!user) {
// If the user is not found, return null
return null;
}

// Update the user's details
await this.usersRepository.update(userId, userData);

// Fetch and return the updated user
const updatedUser = await this.usersRepository.findOne({ where: { userId } });

return updatedUser;
} catch (error) {
} catch (error) {
// Re-throw or handle the error as needed
throw new Error('An error occurred while updating user details');
}
}



async createUser(
request: any,
Expand Down Expand Up @@ -986,7 +984,7 @@ export class PostgresUserService implements IServicelocator {
const userSchema = new UserCreateDto(userCreateDto);

let errKeycloak = "";
let resKeycloak = "";
let resKeycloak;

const keycloakResponse = await getKeycloakAdminToken();
const token = keycloakResponse.data.access_token;
Expand All @@ -1003,30 +1001,37 @@ export class PostgresUserService implements IServicelocator {
HttpStatus.BAD_REQUEST
);
}

resKeycloak = await createUserInKeyCloak(userSchema, token).catch(
(error) => {
LoggerUtil.error(
`${API_RESPONSES.SERVER_ERROR}: ${request.url}`,
`KeyCloak Error: ${error.message}`,
apiId
);

errKeycloak = error.response?.data.errorMessage;
resKeycloak = await createUserInKeyCloak(userSchema, token)


if(resKeycloak.statusCode !== 201 ){
if (resKeycloak.statusCode === 409) {
LoggerUtil.log(API_RESPONSES.EMAIL_EXIST, apiId);

return APIResponse.error(
response,
apiId,
API_RESPONSES.EMAIL_EXIST,
`${resKeycloak.message} ${resKeycloak.email}`,
HttpStatus.CONFLICT
);
}else{
LoggerUtil.log(API_RESPONSES.SERVER_ERROR, apiId);
return APIResponse.error(
response,
apiId,
API_RESPONSES.SERVER_ERROR,
`${errKeycloak}`,
`${resKeycloak.message}`,
HttpStatus.INTERNAL_SERVER_ERROR
);
}
);
}

LoggerUtil.log(API_RESPONSES.USER_CREATE_KEYCLOAK, apiId);


userCreateDto.userId = resKeycloak;

userCreateDto.userId = resKeycloak.userId;

// if cohort given then check for academic year

Expand Down Expand Up @@ -1100,7 +1105,7 @@ export class PostgresUserService implements IServicelocator {
HttpStatus.CREATED,
API_RESPONSES.USER_CREATE_SUCCESSFULLY
);
} catch (e) {
} catch (e) {
LoggerUtil.error(
`${API_RESPONSES.SERVER_ERROR}: ${request.url}`,
`Error: ${e.message}`,
Expand Down Expand Up @@ -1311,7 +1316,7 @@ export class PostgresUserService implements IServicelocator {
response: Response
) {
const user = new User();
user.userId = userCreateDto?.userId,
user.userId = userCreateDto?.userId,
user.username = userCreateDto?.username,
user.firstName = userCreateDto?.firstName,
user.middleName = userCreateDto?.middleName,
Expand Down
71 changes: 47 additions & 24 deletions src/common/utils/keycloak.adapter.util.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { API_RESPONSES } from "./response.messages";
import { LoggerUtil } from "src/common/logger/LoggerUtil";
const axios = require("axios");

function getUserRole(userRoles: string[]) {
if (userRoles.includes("systemAdmin")) {
return "systemAdmin";
Expand Down Expand Up @@ -53,58 +55,79 @@ async function getKeycloakAdminToken() {
return res;
}

async function createUserInKeyCloak(query, token) {
const axios = require("axios");

async function createUserInKeyCloak(query, token) {
if (!query.password) {
return "User cannot be created, Password missing";
}

const data = JSON.stringify({
firstName: query.firstName,
lastName: query.lastName,
email: query.email ? query.email : null,
enabled: "true",
email: query.email || null, // Use `||` for simpler null/undefined handling
username: query.username,
// groups: [getUserGroup(query.role)],
enabled: true, // Changed "true" (string) to true (boolean)
credentials: [
{
temporary: "false",
temporary: false, // Changed "false" (string) to false (boolean)
type: "password",
value: query.password,
},
],
});

console.log("Payload for Keycloak:", data);

const config = {
method: "post",
url: process.env.KEYCLOAK + process.env.KEYCLOAK_ADMIN,
url: `${process.env.KEYCLOAK}${process.env.KEYCLOAK_ADMIN}`,
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
Authorization: `Bearer ${token}`,
},
data: data,
};
let userResponse;
// try {
// userResponse = await axios(config);
// } catch (e) {
// return e;
// }

// const userString = userResponse.headers.location;
// const index = userString.lastIndexOf("/");
// const userId = userString.substring(index + 1);
data,
};

// return userId;
try {
const userResponse = await axios(config);
return userResponse.headers.location.split("/").pop();
// Make the request and wait for the response
const response = await axios(config);

// Log and return the created user's ID
console.log("User created successfully:", response.data);
const userId = response.headers.location.split("/").pop(); // Extract user ID from the location header
console.log("Created User ID:", userId);
return { statusCode: response.status, message: "User created successfully", userId : userId };
} catch (error) {
return "Error creating user: " + error.response.data.error;
// Handle errors and log relevant details
if (error.response) {
console.error("Error Response Status:", error.response.status);
console.error("Error Response Data:", error.response.data);
console.error("Error Response Headers:", error.response.headers);

return {
statusCode: error.response.status,
message: error.response.data.errorMessage || "Error occurred during user creation",
email: query.email || "No email provided",
};
} else if (error.request) {
console.error("No response received:", error.request);
return {
statusCode: 500,
message: "No response received from Keycloak",
email: query.email || "No email provided",
};
} else {
console.error("Error setting up request:", error.message);
return {
statusCode: 500,
message: `Error setting up request: ${error.message}`,
email: query.email || "No email provided",
};
}
}
}


async function checkIfEmailExistsInKeycloak(email, token) {
const axios = require("axios");
const config = {
Expand Down
1 change: 1 addition & 0 deletions src/common/utils/response.messages.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export const API_RESPONSES = {
USERNAME_NOT_FOUND: "Username does not exist",
EMAIL_EXIST: "Email already exists",
USER_NOT_FOUND: "User does not exist",
FORGOT_PASSWORD_SUCCESS: "Forgot password Reset successfully",
EMAIL_NOT_FOUND_FOR_RESET:
Expand Down
3 changes: 1 addition & 2 deletions src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,15 +155,14 @@ export class UserController {
public async updateUser(
@Headers() headers,
@Param("userid") userId: string,
@Req() request: Request,
@Body() userUpdateDto: UserUpdateDTO,
@Res() response: Response
) {
// userDto.tenantId = headers["tenantid"];
userUpdateDto.userId = userId;
return await this.userAdapter
.buildUserAdapter()
.updateUser(userUpdateDto, response);
.updateUser( userUpdateDto, response);
}

@UseFilters(new AllExceptionsFilter(APIID.USER_LIST))
Expand Down

0 comments on commit 3177f36

Please sign in to comment.