Skip to content

Commit

Permalink
SIKKA-5847[COMPLETED]
Browse files Browse the repository at this point in the history
  • Loading branch information
Mansourkira committed Dec 1, 2023
1 parent e5b6a15 commit 8e6d11e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 13 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@sikka/hajar",
"version": "1.1.24",
"version": "1.1.25",
"description": "Toolkit to create SaaS applications",
"author": "Sikka Software <contact@sikka.io> (http://sikka.io)",
"license": "MIT",
Expand Down
52 changes: 40 additions & 12 deletions src/core/authentication/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,16 +121,17 @@ class HajarAuth {

return newRole;
}
async login(email, password, isGoogle = false) {
async loginAdmin(email, password, isGoogle = false) {
try {
const user = await this.User.findOne({ email: email });
const user = await this.User.findOne({ email: email, ref: "admins" });

if (!user) {
throw new HajarError(
"Invalid email or password",
"invalid-email-password"
);
}

if (!isGoogle) {
const isPasswordCorrect = await this.bcrypt.compare(
password,
Expand All @@ -145,24 +146,51 @@ class HajarAuth {
}
}

if (user.ref === "admins") {
// Password is correct, sign a token for the admin user
const token = this.jwt.sign({ userId: user._id }, this.secret);
// Password is correct, sign a token for the admin user
const token = this.jwt.sign({ userId: user._id }, this.secret);

return { user, token, role: "admin" };
} catch (error) {
console.error(error);
return new HajarError(error.message, "admin-login-error");
}
}

async loginCustomer(email, password, isGoogle = false) {
try {
const user = await this.User.findOne({ email: email, ref: "customers" });

return { user, token, role: "admin" };
} else {
// If the user's "ref" field is not equal to "admins", return an error
if (!user) {
throw new HajarError(
"Access denied. Only admins can log in.",
"access-denied-only-admins-can-log-in"
"Invalid email or password",
"invalid-email-password"
);
}

if (!isGoogle) {
const isPasswordCorrect = await this.bcrypt.compare(
password,
user.password
);

if (!isPasswordCorrect) {
throw new HajarError(
"Invalid email or password",
"invalid-email-password"
);
}
}

// Password is correct, sign a token for the customer user
const token = this.jwt.sign({ userId: user._id }, this.secret);

return { user, token, role: "customer" };
} catch (error) {
// Handle errors and return appropriate responses
console.error(error);
return new HajarError(error.message, "login-error");
return new HajarError(error.message, "customer-login-error");
}
}

logout(res) {
res.clearCookie("@admin-tayar-token");
return true;
Expand Down

0 comments on commit 8e6d11e

Please sign in to comment.