Files
EMI-Backend/auth/authEmail.js

240 lines
9.6 KiB
JavaScript

const MongoDB = require("../mongoDB.js");
const { client_logger } = require('../utils/analyticsLogger');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const { getSessionId, getUserId, getProfileId } = require('../utils/sessionUtils.js');
const { cookiesOptions } = require('../config/cookiesOptions');
const Notifications = require("../notifications");
// Object Definitions
const Post = require("../def/post.js")
const Profile = require("../def/profile.js");
const DUMMY_BCRYPT_HASH = '$2b$10$2zQfAaxK0cN13N7V2Q5hAOL3wxY5E9OQj1YxDCEV4VpWw2X2gYd6C';
// Function to Singup new users. An user is a combination of a user obj and a profile.
// When new users are subscribed, they have a single profile, which is the personal one.
// Other profiles can be link to that user, like groups or courses.
const signup = async function (req, res) {
// SECURITY FIX (#2): only accept credentials from request body.
const username = (req.body.username || "").trim().toLowerCase();
const password = req.body.password;
const email = (req.body.email || "").trim().toLowerCase();
const profile = req.body.profile;
if (!username || !password || !email) return res.json({ status: "Incomplete information!" });
// Check if the new user has an invitation.
const DB = await MongoDB.getDB;
if (!await DB.getInvitation(email)) {
client_logger.capture({
distinctId: 'app_level',
event: 'server@' + req.method + '@' + req.originalUrl + '@NotInvited',
properties: {
username: username,
email: email,
}
});
return res.json({ status: "Not invitation found!" });
}
let isUserAlreadyRegistered = await DB.getUser(email);
if (isUserAlreadyRegistered && isUserAlreadyRegistered._id) return res.json({ status: "This user is already registered" });
// SECURITY PLAN (point #5):
// bcrypt.hash already includes a per-password salt.
// Future hardening: centralize cost factor policy (and consider rehash-on-login).
const hashedPassword = await bcrypt.hash(password, 10);
const newUserObject = await DB.newUser({
username,
email,
password: hashedPassword
});
// If newUserObject it's an error message, we check by looking toLowerCase function
if (!newUserObject.toLowerCase) {
let user = {
userid: newUserObject.insertedId,
profile: profile,
}
// Filter the provided information by the template, and adding to the DB, and login.
const userObj = new Profile(user);
await DB.newProfile(userObj);
client_logger.capture({
distinctId: newUserObject.insertedId,
event: 'server@' + req.method + '@' + req.originalUrl,
});
// TODO: this might fail, add catch scenarios
return await login(req, res);
}
// Error return
client_logger.capture({
distinctId: 'app_level',
event: 'server@' + req.method + '@' + req.originalUrl + '@error',
properties: {
ustatus: newUserObject,
}
});
return res.json({ status: newUserObject })
}
// Function for user Login, it returns the coockies/json for user_id session_id and profile_id
const login = async function (req, res) {
// Check if user is already logged in and redirect to root if so.
const session_id = getSessionId(req);
const user_sid = getUserId(req);
const DB = await MongoDB.getDB;
if (session_id && user_sid) {
const userInfo = await DB.checkSessionOnDB(session_id, user_sid);
if (userInfo) return res.redirect('/');
}
const invalidCredentials = () => res.status(401).json({ status: "Invalid credentials" });
// SECURITY FIX (#2): only accept credentials from request body.
const username = (req.body.username || req.body.email || "").trim().toLowerCase();
const password = req.body.password || "";
if (!username || !password) return invalidCredentials();
const user = await DB.getUser(username);
if (!user) {
client_logger.capture({
distinctId: 'app_level',
event: 'server@' + req.method + '@' + req.originalUrl + '@invalidCredentials',
properties: { username },
});
}
// SECURITY PLAN (point #5):
// bcrypt.compare validates salted hashes directly; no manual salt parameter is needed.
// SECURITY FIX (#4): compare against dummy hash when user doesn't exist to reduce timing side-channel.
const isSamePassword = await bcrypt.compare(password, user?.password || DUMMY_BCRYPT_HASH);
// SECURITY FIX (#4): same response for non-existing user and wrong password.
if (!user || !isSamePassword) return invalidCredentials();
try {
// Store a new session loging on DB, and use ID as session ID
const sessionObj = await DB.newSession(user._id);
// Create coockies with information for Auth
res.cookie('user_sid', user._id, cookiesOptions);
res.cookie('session_id', sessionObj.insertedId, cookiesOptions);
// Chooses the most recent update profile as current active profile
const latestUpdatedProfile = await DB.latestProfile(user._id);
res.cookie('profile_id', latestUpdatedProfile._id, cookiesOptions);
client_logger.identify({
distinctId: user._id,
properties: {
name: latestUpdatedProfile.profile.firstName,
}
});
client_logger.capture({
distinctId: user._id,
event: 'server@' + req.method + '@' + req.originalUrl,
});
return res.json({
status: "ok",
user_sid: user._id,
session_id: sessionObj.insertedId,
profile_id: latestUpdatedProfile._id
});
} catch (error) {
console.error(error);
client_logger.capture({
distinctId: 'app_level',
event: 'server@' + req.method + '@' + req.originalUrl + '@error',
});
return res.json({ status: "Error on this User Profile, please contact admin." });
}
}
// route for user logout
const logout = async function (req, res) {
const session_id = getSessionId(req);
const user_sid = getUserId(req);
if (session_id && user_sid) {
res.clearCookie('session_id');
res.clearCookie('user_sid');
//remove from DB
const DB = await MongoDB.getDB;
DB.removeSession(session_id);
client_logger.capture({
distinctId: user_sid,
event: 'server@' + req.method + '@' + req.originalUrl,
});
res.redirect('/');
} else {
res.redirect('/login');
}
}
// Util function for generating new random password for users.
function generatePassword(length = 12) {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+";
return Array.from(crypto.randomFillSync(new Uint8Array(length)))
.map((x) => charset[x % charset.length])
.join("");
}
const resetPassword = async function (req, res) {
const session_id = getSessionId(req);
const user_sid = getUserId(req);
const DB = await MongoDB.getDB;
if (session_id && user_sid) {
// Sadly reusing this endpoint to change password to legged in users.
// TODO: Move change password logic to its own endpoint.
const userInfo = await DB.checkSessionOnDB(session_id, user_sid);
if (userInfo) {
const password = req.body.password;
const hashedPassword = await bcrypt.hash(password, 10);
// TODO: Add salt to password here as well.
DB.resetUserPassword(userInfo.username, hashedPassword);
return res.json({
status: "ok",
details: 'password changed!' // This should be an enum that syncs with clients.
});
}
}
// SECURITY PLAN (point #1):
// Replace this entire non-authenticated branch with reset-token flow:
// request-reset(email) -> email link -> confirm-reset(token, newPassword).
// Do not generate/send plaintext passwords by email.
// SECURITY FIX (#4): return generic response regardless of account existence.
const genericResetResponse = {
status: "ok",
details: "If the account exists, check your email for next steps"
};
// Logic for non-logged in users.
const username = (req.body.username || req.body.email || "").trim().toLowerCase();
if (!username) return res.json(genericResetResponse);
const user = await DB.getUser(username);
if (!user) {
client_logger.capture({
distinctId: 'app_level',
event: 'server@' + req.method + '@' + req.originalUrl + '@resetRequestedUnknownUser',
properties: { username }
});
return res.json(genericResetResponse);
}
const password = generatePassword();
const hashedPassword = await bcrypt.hash(password, 10);
// TODO: Add salt to password here as well.
// TODO: We need to limit this to every 2 hours or something like this.
// TODO: Move this template to the Notif file.
DB.resetUserPassword(username, hashedPassword);
Notifications.sendEmail(username, "Your new credentials",
`
<p> Hello,</p>
<p> This is your new password: ${password}</p>
<p><a href="https://social.emmint.com/">Log in</a></p>
<p>Blessings</p>
<p>Emmanuel International Ministries</p>
`)
client_logger.capture({
distinctId: user._id,
event: 'server@' + req.method + '@' + req.originalUrl,
properties: {
username: username,
}
});
return res.json(genericResetResponse);
}
module.exports = {
signup,
login,
logout,
resetPassword,
}