Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new password reset process for the mobile app #4294

Merged
merged 3 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
163 changes: 163 additions & 0 deletions src/auth-service/controllers/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -1664,6 +1664,169 @@ const createUser = {
return;
}
},
resetPasswordRequest: async (req, res, next) => {
try {
const errors = extractErrorsFromRequest(req);
if (errors) {
next(
new HttpError("bad request errors", httpStatus.BAD_REQUEST, errors)
);
return;
}
const { email } = req.body;
const tenant = req.query.tenant;
const token = userUtil.generateNumericToken(5);
const result = await userUtil.initiatePasswordReset(
{
email,
token,
tenant,
},
next
);

res
.status(httpStatus.OK)
.json({ success: true, message: result.message });
} catch (error) {
logger.error(`🐛🐛 Internal Server Error ${error.message}`);
next(
new HttpError(
"Internal Server Error",
httpStatus.INTERNAL_SERVER_ERROR,
{ message: error.message }
)
);
return;
}
},
Comment on lines +1667 to +1702
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

🛠️ Refactor suggestion

Rate limiting implementation is required for password reset endpoints

The current rate limiting middleware in the auth service is designed for authenticated API clients and isn't suitable for public endpoints like password reset. You'll need to:

  • Implement IP-based rate limiting for the password reset endpoints
  • Use express-rate-limit package which is already installed
  • Consider a stricter limit (e.g., 5 requests per 15 minutes) for these sensitive endpoints

Example implementation:

const rateLimit = require('express-rate-limit');
const passwordResetLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5 // limit each IP to 5 requests per window
});

router.post('/resetPasswordRequest', passwordResetLimiter, ...);
🔗 Analysis chain

Add rate limiting to prevent brute force attacks.

The password reset request endpoint should implement rate limiting to prevent abuse. Also, consider using a consistent response format that doesn't leak information about email existence.

Let's verify if rate limiting is implemented elsewhere in the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for rate limiting implementations
rg -A 5 "rate.?limit|rateLimiter"

Length of output: 9490


Script:

#!/bin/bash
# Check user routes and rate limit implementation
echo "=== User Routes Configuration ==="
rg -A 10 "router.*user" src/auth-service/routes/
echo -e "\n=== Rate Limit Middleware Implementation ==="
cat src/auth-service/middleware/rate-limit.js

Length of output: 5957

resetPassword: async (req, res, next) => {
try {
const errors = extractErrorsFromRequest(req);
if (errors) {
next(
new HttpError("bad request errors", httpStatus.BAD_REQUEST, errors)
);
return;
}
const { token } = req.params;
const { password } = req.body;

const defaultTenant = constants.DEFAULT_TENANT || "airqo";
const tenant = isEmpty(req.query.tenant)
? defaultTenant
: req.query.tenant;

const result = await userUtil.resetPassword(
{
token,
password,
tenant,
},
next
);

res
.status(httpStatus.OK)
.json({ success: true, message: result.message });
} catch (error) {
logObject("error in controller", error);
logger.error(`🐛🐛 Internal Server Error ${error.message}`);
next(
new HttpError(
"Internal Server Error",
httpStatus.INTERNAL_SERVER_ERROR,
{ message: error.message }
)
);
return;
}
},

registerMobileUser: async (req, res, next) => {
try {
const errors = extractErrorsFromRequest(req);
if (errors) {
next(
new HttpError("bad request errors", httpStatus.BAD_REQUEST, errors)
);
return;
}

const request = req;
const defaultTenant = constants.DEFAULT_TENANT || "airqo";
request.query.tenant = isEmpty(req.query.tenant)
? defaultTenant
: req.query.tenant;

request.body.analyticsVersion = 4;

const result = await userUtil.registerMobileUser(request, next);

if (isEmpty(result) || res.headersSent) {
return;
}

if (result.success === true) {
res
.status(httpStatus.CREATED)
.json({ success: true, message: result.message, data: result.user });
} else {
next(new HttpError(result.message, httpStatus.BAD_REQUEST));
}
} catch (error) {
logger.error(`🐛🐛 Internal Server Error ${error.message}`);
next(
new HttpError(
"Internal Server Error",
httpStatus.INTERNAL_SERVER_ERROR,
{ message: error.message }
)
);
return;
}
},

verifyMobileEmail: async (req, res, next) => {
try {
const errors = extractErrorsFromRequest(req);
if (errors) {
next(
new HttpError("bad request errors", httpStatus.BAD_REQUEST, errors)
);
return;
}
const request = req;
const defaultTenant = constants.DEFAULT_TENANT || "airqo";
request.query.tenant = isEmpty(req.query.tenant)
? defaultTenant
: req.query.tenant;

const result = await userUtil.verifyMobileEmail(request, next);

if (isEmpty(result) || res.headersSent) {
return;
}
if (result.success) {
res
.status(httpStatus.OK)
.json({ success: true, message: result.message, data: result.user });
} else {
next(new HttpError(result.message, httpStatus.BAD_REQUEST));
}
} catch (error) {
logger.error(`🐛🐛 Internal Server Error ${error.message}`);
next(
new HttpError(
"Internal Server Error",
httpStatus.INTERNAL_SERVER_ERROR,
{ message: error.message }
)
);
return;
}
},

subscribeToNewsLetter: async (req, res, next) => {
try {
const errors = extractErrorsFromRequest(req);
Expand Down
76 changes: 76 additions & 0 deletions src/auth-service/middleware/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,44 @@ const useEmailWithLocalStrategy = (tenant, req, res, next) =>
)
);
return;
} else if (user.analyticsVersion === 4 && !user.verified) {
await createUserUtil
.mobileVerificationReminder({ tenant, email: user.email }, next)
.then((verificationResponse) => {
if (
!verificationResponse ||
verificationResponse.success === false
) {
logger.error(
`Verification reminder failed: ${
verificationResponse
? verificationResponse.message
: "No response"
}`
);
}
})
.catch((err) => {
logger.error(
`Error sending verification reminder: ${err.message}`
);
});

req.auth.success = false;
req.auth.message =
"account not verified, verification email has been sent to your email";
req.auth.status = httpStatus.FORBIDDEN;
next(
new HttpError(
"account not verified, verification email has been sent to your email",
httpStatus.FORBIDDEN,
{
message:
"account not verified, verification email has been sent to your email",
}
)
);
return;
}
req.auth.success = true;
req.auth.message = "successful login";
Expand Down Expand Up @@ -294,6 +332,44 @@ const useUsernameWithLocalStrategy = (tenant, req, res, next) =>
)
);
return;
} else if (user.analyticsVersion === 4 && !user.verified) {
createUserUtil
.mobileVerificationReminder({ tenant, email: user.email }, next)
.then((verificationResponse) => {
if (
!verificationResponse ||
verificationResponse.success === false
) {
logger.error(
`Verification reminder failed: ${
verificationResponse
? verificationResponse.message
: "No response"
}`
);
}
})
.catch((err) => {
logger.error(
`Error sending verification reminder: ${err.message}`
);
});

req.auth.success = false;
req.auth.message =
"account not verified, verification email has been sent to your email";
req.auth.status = httpStatus.FORBIDDEN;
next(
new HttpError(
"account not verified, verification email has been sent to your email",
httpStatus.FORBIDDEN,
{
message:
"account not verified, verification email has been sent to your email",
}
)
);
return;
}
req.auth.success = true;
req.auth.message = "successful login";
Expand Down
22 changes: 8 additions & 14 deletions src/auth-service/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ const UserSchema = new Schema(
},
userName: {
type: String,
required: [true, "UserName is required!"],
trim: true,
unique: true,
},
Expand Down Expand Up @@ -404,6 +403,14 @@ UserSchema.pre(
return next(new Error("Phone number or email is required!"));
}

if (!this.userName && this.email) {
this.userName = this.email;
}

if (!this.userName) {
return next(new Error("userName is required!"));
}

// Profile picture validation - only for new documents
if (
this.profilePicture &&
Expand Down Expand Up @@ -470,10 +477,6 @@ UserSchema.pre(
];
}

// Ensure default values for new documents
this.verified = this.verified ?? false;
this.analyticsVersion = this.analyticsVersion ?? 2;

// Permissions handling for new documents
if (this.permissions && this.permissions.length > 0) {
this.permissions = [...new Set(this.permissions)];
Expand Down Expand Up @@ -581,15 +584,6 @@ UserSchema.pre(
updates.permissions = uniquePermissions;
}
}

// Conditional default values for updates
if (updates && updates.$set) {
updates.$set.verified = updates.$set.verified ?? false;
updates.$set.analyticsVersion = updates.$set.analyticsVersion ?? 2;
} else {
updates.verified = updates.verified ?? false;
updates.analyticsVersion = updates.analyticsVersion ?? 2;
}
}

// Additional checks for new documents
Expand Down
Loading
Loading