Skip to content

Commit

Permalink
Merge pull request #71 from YoginiTayade/username-update-1
Browse files Browse the repository at this point in the history
Task #229369 username and password updation
  • Loading branch information
suraj-tekdi authored Oct 30, 2024
2 parents f0db64f + 4b52371 commit f726f4b
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 9 deletions.
5 changes: 3 additions & 2 deletions src/adapters/hasura/altBulkUploadStudent.adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ import { ALTStudentService } from "./altStudent.adapter";
import { getPassword, getToken } from "./adapter.utils";
import { ErrorResponse } from "src/error-response";
import { SuccessResponse } from "src/success-response";
import { ALTHasuraUserService } from "./altUser.adapter";
@Injectable()
export class ALTBulkUploadStudentService {
constructor(
private httpService: HttpService,
private studentService: ALTStudentService,
private groupMembershipService: GroupMembershipService,
private groupService: HasuraGroupService
private groupService: HasuraGroupService,
private altUserService: ALTHasuraUserService
) {}

public async createStudents(
Expand Down Expand Up @@ -48,7 +50,6 @@ export class ALTBulkUploadStudentService {
try {
for (const student of bulkStudentDto.students) {
student.groups = [];
student.password = getPassword(8);
student.status = true;
const studentRes: any = await this.studentService.createAndAddToGroup(
request,
Expand Down
6 changes: 3 additions & 3 deletions src/adapters/hasura/altStudent.adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,15 +280,15 @@ export class ALTStudentService {
message: "Ok.",
data: createdUser,
});
} else if (
} else if (
newCreatedStudent?.data.schoolUdise !== studentDto.schoolUdise
) {
return new ErrorResponse({
errorCode: "400",
errorMessage: `Create and add to group failed Old and new school does not match,`,
});
} else {
// console.log(newCreatedStudent, "new Created user");
//console.log(newCreatedStudent, "new Created user");
return new ErrorResponse({
errorCode: "400",
errorMessage: `Create and add to group failed , ${newCreatedStudent?.errorMessage}`,
Expand Down Expand Up @@ -336,7 +336,7 @@ export class ALTStudentService {
bulkToken
);
// entry in student

try {
userId = createdUser?.user.data.userId;
} catch (e) {
Expand Down
75 changes: 71 additions & 4 deletions src/adapters/hasura/altUser.adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,27 +107,31 @@ export class ALTHasuraUserService {
}

if (!userDto.username) {
userDto.username = getUsername(userDto);
userDto.username = await this.getUsername(userDto, request, altUserRoles);
}

if (!userDto.email) {
userDto.email = userDto.username + "@yopmail.com";
}
if (!userDto.password) {
userDto.password = getPassword(8);
userDto.password = userDto.username;
}

const userSchema = new UserDto(userDto, true);

const usernameExistsInKeycloak = await checkIfUsernameExistsInKeycloak(
userDto.username,
bulkToken
);

if (usernameExistsInKeycloak?.data[0]?.username) {
// console.log("check in db", usernameExistsInKeycloak?.data[0]?.id);
const usernameExistsInDB: any = await this.getUserByUsername(
usernameExistsInKeycloak?.data[0]?.username,
request,
altUserRoles
);

if (usernameExistsInDB?.statusCode === 200) {
if (usernameExistsInDB?.data) {
// console.log(usernameExistsInDB, "usernameExistsInDB");
Expand All @@ -145,6 +149,7 @@ export class ALTHasuraUserService {
null,
usernameExistsInKeycloak?.data[0]?.id
);

// console.log(resetPasswordRes ,"pres");
if (resetPasswordRes.statusCode !== 204) {
return new ErrorResponse({
Expand Down Expand Up @@ -176,6 +181,7 @@ export class ALTHasuraUserService {
userSchema,
altUserRoles
);

return {
user: newlyCreatedUser,
isNewlyCreated: true,
Expand Down Expand Up @@ -229,7 +235,7 @@ export class ALTHasuraUserService {
});
}
// db??
const databaseResponse = this.createUserInDatabase(
const databaseResponse = await this.createUserInDatabase(
request,
userDto,
userSchema,
Expand All @@ -256,7 +262,7 @@ export class ALTHasuraUserService {
keycloakUserId,
altUserRoles
) {
const encryptedPassword = await encryptPassword(userDto["password"]);
const encryptedPassword = userDto["password"];
const encPass = encryptedPassword.toString();

let query = "";
Expand Down Expand Up @@ -878,4 +884,65 @@ export class ALTHasuraUserService {
});
}
}
public async getUsername(obj, request, altUserRoles) {
const [firstName, lastName] = obj.name.split(" ");

// Step 1: Extract initials
const initials = `${firstName[0].toLowerCase()}${
lastName ? lastName[0].toLowerCase() : ""
}`;
const dob = obj.dateOfBirth.replace(/^(\d{4})-(\d{2})-(\d{2})$/, "$3$2$1"); // Convert to ddmmyyyy

// Step 3: Create the base username
let initialUsername = `${initials}${dob}`;

const uniqueUsername = await this.ensureUniqueUsername(
initialUsername,
request,
altUserRoles
);
return uniqueUsername;
}
async ensureUniqueUsername(baseUsername, request, altUserRoles) {
let username = baseUsername;
let count = 0; // Start count from 0, to get "01" suffix for the first increment

// Check if the exact base username is taken
while (await this.isUsernameTaken(username, request, altUserRoles)) {
// Increment count and format it as "01", "02", etc.
count++;
const suffix = String(count).padStart(2, "0"); // Formats as "01", "02", etc.
username = `${baseUsername}${suffix}`;
}

return username;
}

// Function to check if a username is taken in the database
async isUsernameTaken(username, request, altUserRoles) {
const data = {
query: `query GetUserByUsername($username:String) {
Users(where: {username: {_eq: $username}}) {
userId
}
}`,
variables: { username: username },
};

const headers = {
Authorization: request.headers.authorization,
"x-hasura-role": getUserRole(altUserRoles),
"Content-Type": "application/json",
};

const config = {
method: "post",
url: process.env.REGISTRYHASURA,
headers: headers,
data: data,
};

const response = await this.axios(config);
return response.data.data.Users.length > 0; // Returns true if username is taken
}
}

0 comments on commit f726f4b

Please sign in to comment.