Compare commits
7 Commits
0b36db9b33
...
codex/pass
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3a782a360 | ||
|
|
19d805d322 | ||
|
|
469962d03c | ||
|
|
c6d9dfd3c1 | ||
|
|
0baf237548 | ||
|
|
ea864b27d4 | ||
|
|
c136d25974 |
@@ -9,15 +9,48 @@ 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';
|
||||
const PASSWORD_TOKEN_TTL_MINUTES = parseInt(process.env.PASSWORD_TOKEN_TTL_MINUTES || '20', 10);
|
||||
const PASSWORD_TOKEN_PATH = process.env.PASSWORD_TOKEN_PATH || '/token-login';
|
||||
const FRONTEND_URL = (process.env.FRONTEND_URL || 'https://social.emmint.com').replace(/\/+$/, '');
|
||||
|
||||
const createPasswordTokenHash = (rawToken) =>
|
||||
crypto.createHash('sha256').update(rawToken).digest('hex');
|
||||
|
||||
const createSessionFromUser = async ({ DB, user, req, res }) => {
|
||||
const sessionObj = await DB.newSession(user._id);
|
||||
res.cookie('user_sid', user._id, cookiesOptions);
|
||||
res.cookie('session_id', sessionObj.insertedId, cookiesOptions);
|
||||
const latestUpdatedProfile = await DB.latestProfile(user._id);
|
||||
if (latestUpdatedProfile && latestUpdatedProfile._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 {
|
||||
status: "ok",
|
||||
user_sid: user._id,
|
||||
session_id: sessionObj.insertedId,
|
||||
profile_id: latestUpdatedProfile?._id
|
||||
};
|
||||
};
|
||||
|
||||
// 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) {
|
||||
const username = req.query.username || req.body.username;
|
||||
const password = req.query.password || req.body.password;
|
||||
const email = req.query.email || req.body.email;
|
||||
const profile = req.query.profile || req.body.profile;
|
||||
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;
|
||||
@@ -34,12 +67,10 @@ const signup = async function (req, res) {
|
||||
}
|
||||
let isUserAlreadyRegistered = await DB.getUser(email);
|
||||
if (isUserAlreadyRegistered && isUserAlreadyRegistered._id) return res.json({ status: "This user is already registered" });
|
||||
// Hash password to be stored on the DB.
|
||||
// TODO: I think this is missing a Salt factor to improve security
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
const newUserObject = await DB.newUser({
|
||||
username: username.toLowerCase(),
|
||||
email: email.toLowerCase(),
|
||||
username,
|
||||
email,
|
||||
password: hashedPassword
|
||||
});
|
||||
// If newUserObject it's an error message, we check by looking toLowerCase function
|
||||
@@ -79,47 +110,23 @@ const login = async function (req, res) {
|
||||
const userInfo = await DB.checkSessionOnDB(session_id, user_sid);
|
||||
if (userInfo) return res.redirect('/');
|
||||
}
|
||||
const username = req.body.username || req.query.username;
|
||||
const password = req.body.password || req.query.password || "";
|
||||
const invalidCredentials = () => res.status(401).json({ status: "Invalid credentials" });
|
||||
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 + '@userNotFound',
|
||||
properties: {
|
||||
username: username,
|
||||
}
|
||||
event: 'server@' + req.method + '@' + req.originalUrl + '@invalidCredentials',
|
||||
properties: { username },
|
||||
});
|
||||
return res.json({ status: "user not founded" });
|
||||
}
|
||||
// TODO: Also add salt parameter here.
|
||||
const isSamePassword = await bcrypt.compare(password, user.password);
|
||||
if (!isSamePassword) return res.json({ status: "incorrect password" });
|
||||
const isSamePassword = await bcrypt.compare(password, user?.password || DUMMY_BCRYPT_HASH);
|
||||
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
|
||||
});
|
||||
return res.json(await createSessionFromUser({ DB, user, req, res }));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
client_logger.capture({
|
||||
@@ -151,51 +158,43 @@ const logout = async function (req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
const username = (req.body.username || req.body.email || "").trim().toLowerCase();
|
||||
if (!username) return res.json(genericResetResponse);
|
||||
const user = await DB.getUser(username);
|
||||
if (!user) return res.json({ status: "user not founded" });
|
||||
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",
|
||||
if (!user) {
|
||||
client_logger.capture({
|
||||
distinctId: 'app_level',
|
||||
event: 'server@' + req.method + '@' + req.originalUrl + '@resetRequestedUnknownUser',
|
||||
properties: { username }
|
||||
});
|
||||
return res.json(genericResetResponse);
|
||||
}
|
||||
const rawToken = crypto.randomBytes(32).toString('hex');
|
||||
const tokenHash = createPasswordTokenHash(rawToken);
|
||||
const expiresAt = new Date(Date.now() + PASSWORD_TOKEN_TTL_MINUTES * 60 * 1000);
|
||||
const tokenStored = await DB.createPasswordLoginToken(user._id, tokenHash, expiresAt);
|
||||
if (!tokenStored) {
|
||||
return res.json(genericResetResponse);
|
||||
}
|
||||
const loginUrl = `${FRONTEND_URL}${PASSWORD_TOKEN_PATH}?token=${rawToken}`;
|
||||
Notifications.sendEmail(username, "Your secure sign-in link",
|
||||
`
|
||||
<p> Hello,</p>
|
||||
<p> This is your new password: ${password}</p>
|
||||
<p><a href="https://social.emmint.com/">Log in</a></p>
|
||||
<p>Hello,</p>
|
||||
<p>Use this one-time sign-in link to access your account:</p>
|
||||
<p><a href="${loginUrl}">${loginUrl}</a></p>
|
||||
<p>This link expires in ${PASSWORD_TOKEN_TTL_MINUTES} minutes and can only be used once.</p>
|
||||
<p>If you did not request this, you can ignore this email.</p>
|
||||
<p>Blessings</p>
|
||||
<p>Emmanuel International Ministries</p>
|
||||
`)
|
||||
`);
|
||||
client_logger.capture({
|
||||
distinctId: user._id,
|
||||
event: 'server@' + req.method + '@' + req.originalUrl,
|
||||
@@ -203,10 +202,30 @@ const resetPassword = async function (req, res) {
|
||||
username: username,
|
||||
}
|
||||
});
|
||||
return res.json({
|
||||
status: "ok",
|
||||
details: 'Check your email for new password' // Enum of details?
|
||||
});
|
||||
return res.json(genericResetResponse);
|
||||
}
|
||||
|
||||
const loginWithPasswordToken = async function (req, res) {
|
||||
const DB = await MongoDB.getDB;
|
||||
const token = (req.body.token || "").trim();
|
||||
if (!token || token.length < 32) {
|
||||
return res.status(401).json({ status: "Invalid or expired token" });
|
||||
}
|
||||
const tokenHash = createPasswordTokenHash(token);
|
||||
const tokenDoc = await DB.consumePasswordLoginToken(tokenHash);
|
||||
if (!tokenDoc || !tokenDoc.userId) {
|
||||
return res.status(401).json({ status: "Invalid or expired token" });
|
||||
}
|
||||
const user = await DB.getUserById(tokenDoc.userId);
|
||||
if (!user || !user._id) {
|
||||
return res.status(401).json({ status: "Invalid or expired token" });
|
||||
}
|
||||
try {
|
||||
return res.json(await createSessionFromUser({ DB, user, req, res }));
|
||||
} catch (error) {
|
||||
console.error("Token login error", error);
|
||||
return res.status(500).json({ status: "Internal server error" });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -215,4 +234,5 @@ module.exports = {
|
||||
login,
|
||||
logout,
|
||||
resetPassword,
|
||||
}
|
||||
loginWithPasswordToken,
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
const isProduction = process.env.NODE_ENV === "production";
|
||||
const forceSecureCookie = process.env.COOKIE_SECURE === "true";
|
||||
const secure = forceSecureCookie || isProduction;
|
||||
|
||||
const cookiesOptions = {
|
||||
maxAge: 1000 * 60 * 60 * 24 * 90, // would expire after 30 days
|
||||
maxAge: 1000 * 60 * 60 * 24 * 90, // would expire after 90 days
|
||||
httpOnly: true, // The cookie only accessible by the web server
|
||||
sameSite: 'none', // This and secure are required for properly
|
||||
secure: true, // manage cockies in cros-domain
|
||||
sameSite: secure ? 'none' : 'lax',
|
||||
secure,
|
||||
};
|
||||
|
||||
module.exports = { cookiesOptions };
|
||||
module.exports = { cookiesOptions };
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
var corsOptions = {
|
||||
origin: [
|
||||
'http://localhost:8080',
|
||||
'http://localhost:8081',
|
||||
'http://127.0.0.1:3000',
|
||||
'http://127.0.0.1:8080',
|
||||
'http://127.0.0.1:8081',
|
||||
'http://localhost:3000',
|
||||
"https://social.emmint.com",
|
||||
"https://fellowship.emmint.com",
|
||||
@@ -9,4 +13,4 @@ var corsOptions = {
|
||||
credentials: true
|
||||
};
|
||||
|
||||
module.exports = { corsOptions };
|
||||
module.exports = { corsOptions };
|
||||
|
||||
@@ -96,16 +96,18 @@ userDB = (DB) => {
|
||||
DB.getFriendsFriends = async (profileId, limit = 10) => {
|
||||
const profile = await DB.getProfile(profileId);
|
||||
if (!profile) return [];
|
||||
let ids = profile.following.map((id) => DB.ObjectID(id));
|
||||
const following = Array.isArray(profile.following) ? profile.following : [];
|
||||
let ids = following.filter((id) => DB.ObjectID.isValid(id)).map((id) => DB.ObjectID(id));
|
||||
let alreadyFollowingMap = {};
|
||||
alreadyFollowingMap[profileId] = 1; //skip that profile
|
||||
profile.following.forEach(id => {
|
||||
following.forEach(id => {
|
||||
if (!alreadyFollowingMap[id]) alreadyFollowingMap[id] = 1;
|
||||
})
|
||||
return DB.profileCols.find({ _id: { $in: ids } }).project({ following: 1 }).limit(limit).toArray().then(profiles => {
|
||||
let friendsOfFriendsMap = {};
|
||||
profiles.forEach(p => {
|
||||
p.following.forEach(followingId => {
|
||||
const related = Array.isArray(p.following) ? p.following : [];
|
||||
related.forEach(followingId => {
|
||||
if (alreadyFollowingMap[followingId]) return 0;
|
||||
if (!friendsOfFriendsMap[followingId]) friendsOfFriendsMap[followingId] = 0;
|
||||
friendsOfFriendsMap[followingId] = friendsOfFriendsMap[followingId] + 1;
|
||||
@@ -312,9 +314,10 @@ userDB = (DB) => {
|
||||
DB.getFollowingGroups = async (profileid) => {
|
||||
const profile = await DB.getProfile(profileid);
|
||||
let ids = [];
|
||||
for (id in profile.following) {
|
||||
const following = Array.isArray(profile?.following) ? profile.following : [];
|
||||
for (id in following) {
|
||||
try {
|
||||
let oId = DB.ObjectID(profile.following[id]);
|
||||
let oId = DB.ObjectID(following[id]);
|
||||
let checkProfile = await DB.getProfileCache(oId)
|
||||
if (checkProfile && checkProfile.isGroup && !checkProfile.isChat) {
|
||||
ids.push(oId)
|
||||
@@ -482,4 +485,4 @@ userDB = (DB) => {
|
||||
|
||||
}
|
||||
|
||||
module.exports = userDB;
|
||||
module.exports = userDB;
|
||||
|
||||
37
index.js
37
index.js
@@ -9,6 +9,7 @@ require('dotenv').config();
|
||||
const express = require('express');
|
||||
const app = express();
|
||||
const port = process.env.PORT || 3000;
|
||||
app.set('trust proxy', true);
|
||||
// -- Accept request from other origins
|
||||
const cors = require('cors');
|
||||
const { corsOptions } = require('./config/corsOptions');
|
||||
@@ -34,11 +35,11 @@ const limiter = rateLimit({
|
||||
return ip.includes(":") ? ip.split(":")[0] : ip; // Remove port if present
|
||||
}
|
||||
});
|
||||
app.set('trust proxy', true);
|
||||
app.use(limiter);
|
||||
|
||||
// Authentication
|
||||
const { signup, login, logout, resetPassword } = require('./auth/authEmail.js');
|
||||
const { signup, login, logout, resetPassword, loginWithPasswordToken } = require('./auth/authEmail.js');
|
||||
const { authRateLimiter } = require('./middleware/authRateLimiter');
|
||||
/**
|
||||
* @swagger
|
||||
* /signup:
|
||||
@@ -71,7 +72,7 @@ const { signup, login, logout, resetPassword } = require('./auth/authEmail.js');
|
||||
* 400:
|
||||
* description: Bad request.
|
||||
*/
|
||||
app.route('/signup').get(signup).post(signup);
|
||||
app.post('/signup', signup);
|
||||
/**
|
||||
* @swagger
|
||||
* /login:
|
||||
@@ -104,7 +105,7 @@ app.route('/signup').get(signup).post(signup);
|
||||
* 401:
|
||||
* description: Invalid credentials.
|
||||
*/
|
||||
app.route('/login').get(login).post(login);
|
||||
app.post('/login', authRateLimiter('login'), login);
|
||||
/**
|
||||
* @swagger
|
||||
* /logout:
|
||||
@@ -127,7 +128,7 @@ app.get('/logout', logout);
|
||||
* @swagger
|
||||
* /resetPassword:
|
||||
* post:
|
||||
* summary: Resets a user's password
|
||||
* summary: Sends a one-time sign-in link if the account exists
|
||||
* tags: [Auth]
|
||||
* requestBody:
|
||||
* required: true
|
||||
@@ -152,7 +153,29 @@ app.get('/logout', logout);
|
||||
* 400:
|
||||
* description: Bad request.
|
||||
*/
|
||||
app.route('/resetPassword').post(resetPassword);
|
||||
app.route('/resetPassword').post(authRateLimiter('reset'), resetPassword);
|
||||
/**
|
||||
* @swagger
|
||||
* /password/token-login:
|
||||
* post:
|
||||
* summary: Consumes a one-time password token and starts a session
|
||||
* tags: [Auth]
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* token:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Logged in with one-time token
|
||||
* 401:
|
||||
* description: Invalid or expired token
|
||||
*/
|
||||
app.post('/password/token-login', authRateLimiter('token'), loginWithPasswordToken);
|
||||
|
||||
// Routes
|
||||
const profileRoute = require('./routes/profile.js');
|
||||
@@ -486,4 +509,4 @@ DB.getDB.then((DB) => {
|
||||
});
|
||||
|
||||
// Export the app for testing purposes
|
||||
module.exports = { app, mongoDB: DB };
|
||||
module.exports = { app, mongoDB: DB };
|
||||
|
||||
116
middleware/authRateLimiter.js
Normal file
116
middleware/authRateLimiter.js
Normal file
@@ -0,0 +1,116 @@
|
||||
const crypto = require('crypto');
|
||||
const { client_logger } = require('../utils/analyticsLogger');
|
||||
|
||||
const AUTH_ATTEMPT_WINDOW_MS = Math.max(60 * 1000, parseInt(process.env.AUTH_ATTEMPT_WINDOW_MS || `${15 * 60 * 1000}`, 10));
|
||||
const AUTH_ATTEMPT_MAX = Math.max(1, parseInt(process.env.AUTH_ATTEMPT_MAX || '5', 10));
|
||||
const AUTH_BLOCK_BASE_MS = Math.max(30 * 1000, parseInt(process.env.AUTH_BLOCK_BASE_MS || `${5 * 60 * 1000}`, 10));
|
||||
const AUTH_BLOCK_MAX_MS = Math.max(AUTH_BLOCK_BASE_MS, parseInt(process.env.AUTH_BLOCK_MAX_MS || `${60 * 60 * 1000}`, 10));
|
||||
|
||||
const limiterStore = new Map();
|
||||
let lastPruneAt = 0;
|
||||
|
||||
const getClientIp = (req) => {
|
||||
const forwarded = req.headers['x-forwarded-for']?.split(',')[0]?.trim();
|
||||
const rawIp = forwarded || req.ip || req.connection?.remoteAddress || 'unknown';
|
||||
return rawIp.replace('::ffff:', '');
|
||||
};
|
||||
|
||||
const hashValue = (value) =>
|
||||
crypto.createHash('sha256').update(String(value)).digest('hex').slice(0, 16);
|
||||
|
||||
const getIdentity = (req, mode) => {
|
||||
if (mode === 'token') {
|
||||
const token = (req.body?.token || '').trim();
|
||||
return token ? `token:${hashValue(token)}` : 'token:anonymous';
|
||||
}
|
||||
const username = (req.body?.username || req.body?.email || '').trim().toLowerCase();
|
||||
return username ? `acct:${hashValue(username)}` : 'acct:anonymous';
|
||||
};
|
||||
|
||||
const getLimiterKey = (req, mode) => `${mode}:${getIdentity(req, mode)}:ip:${getClientIp(req)}`;
|
||||
|
||||
const getOrInitRecord = (key, now) => {
|
||||
const existing = limiterStore.get(key);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const record = {
|
||||
count: 0,
|
||||
windowStartedAt: now,
|
||||
blockedUntil: 0,
|
||||
blockLevel: 0,
|
||||
};
|
||||
limiterStore.set(key, record);
|
||||
return record;
|
||||
};
|
||||
|
||||
const computeBlockMs = (blockLevel) =>
|
||||
Math.min(AUTH_BLOCK_BASE_MS * (2 ** Math.max(0, blockLevel - 1)), AUTH_BLOCK_MAX_MS);
|
||||
|
||||
const authRateLimiter = (mode) => (req, res, next) => {
|
||||
const now = Date.now();
|
||||
if (now - lastPruneAt > 5 * 60 * 1000) {
|
||||
for (const [storeKey, storeValue] of limiterStore.entries()) {
|
||||
const isWindowExpired = now - storeValue.windowStartedAt > AUTH_ATTEMPT_WINDOW_MS;
|
||||
const isNotBlocked = storeValue.blockedUntil <= now;
|
||||
if (isWindowExpired && isNotBlocked) {
|
||||
limiterStore.delete(storeKey);
|
||||
}
|
||||
}
|
||||
lastPruneAt = now;
|
||||
}
|
||||
const key = getLimiterKey(req, mode);
|
||||
const record = getOrInitRecord(key, now);
|
||||
|
||||
if (now - record.windowStartedAt > AUTH_ATTEMPT_WINDOW_MS) {
|
||||
record.count = 0;
|
||||
record.windowStartedAt = now;
|
||||
}
|
||||
|
||||
if (record.blockedUntil > now) {
|
||||
const retryAfterSec = Math.ceil((record.blockedUntil - now) / 1000);
|
||||
res.set('Retry-After', retryAfterSec.toString());
|
||||
client_logger.capture({
|
||||
distinctId: 'app_level',
|
||||
event: 'security@auth@rate_limited',
|
||||
properties: {
|
||||
route: req.originalUrl,
|
||||
method: req.method,
|
||||
mode,
|
||||
keyHash: hashValue(key),
|
||||
retryAfterSec,
|
||||
blockLevel: record.blockLevel,
|
||||
}
|
||||
});
|
||||
return res.status(429).json({ status: 'Too many attempts. Please try again later.' });
|
||||
}
|
||||
|
||||
record.count += 1;
|
||||
if (record.count > AUTH_ATTEMPT_MAX) {
|
||||
record.blockLevel += 1;
|
||||
const blockMs = computeBlockMs(record.blockLevel);
|
||||
record.blockedUntil = now + blockMs;
|
||||
record.count = 0;
|
||||
record.windowStartedAt = now;
|
||||
res.set('Retry-After', Math.ceil(blockMs / 1000).toString());
|
||||
client_logger.capture({
|
||||
distinctId: 'app_level',
|
||||
event: 'security@auth@rate_limited',
|
||||
properties: {
|
||||
route: req.originalUrl,
|
||||
method: req.method,
|
||||
mode,
|
||||
keyHash: hashValue(key),
|
||||
retryAfterSec: Math.ceil(blockMs / 1000),
|
||||
blockLevel: record.blockLevel,
|
||||
}
|
||||
});
|
||||
return res.status(429).json({ status: 'Too many attempts. Please try again later.' });
|
||||
}
|
||||
|
||||
return next();
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
authRateLimiter,
|
||||
};
|
||||
@@ -2,19 +2,30 @@ const { getSessionId, getUserId, getProfileId } = require('../utils/sessionUtils
|
||||
const { client_logger } = require('../utils/analyticsLogger');
|
||||
const { cookiesOptions } = require('../config/cookiesOptions');
|
||||
const MongoDB = require("../mongoDB.js");
|
||||
const { ObjectId } = require("mongodb");
|
||||
|
||||
const sessionChecker = async (req, res, next) => {
|
||||
const session_id = getSessionId(req);
|
||||
const user_sid = getUserId(req);
|
||||
let profile_id = getProfileId(req);
|
||||
try {
|
||||
const session_id = getSessionId(req);
|
||||
const user_sid = getUserId(req);
|
||||
let profile_id = getProfileId(req);
|
||||
|
||||
if (session_id && user_sid) {
|
||||
DB = await MongoDB.getDB;
|
||||
if (!session_id || !user_sid) {
|
||||
return res.redirect('/login');
|
||||
}
|
||||
if (!ObjectId.isValid(session_id) || !ObjectId.isValid(user_sid)) {
|
||||
return res.redirect('/login');
|
||||
}
|
||||
|
||||
const DB = await MongoDB.getDB;
|
||||
const userInfo = await DB.checkSessionOnDB(session_id, user_sid);
|
||||
req.userInfo = userInfo;
|
||||
|
||||
if (!await DB.getProfileCache(profile_id)) {
|
||||
const latestProfile = await DB.latestProfile(user_sid);
|
||||
if (!latestProfile || !latestProfile._id) {
|
||||
return res.redirect('/login');
|
||||
}
|
||||
res.cookie('profile_id', latestProfile._id, cookiesOptions);
|
||||
profile_id = latestProfile._id;
|
||||
}
|
||||
@@ -23,16 +34,16 @@ const sessionChecker = async (req, res, next) => {
|
||||
|
||||
if (!userInfo) return res.redirect('/login');
|
||||
|
||||
// Log Request
|
||||
client_logger.capture({
|
||||
distinctId: user_sid,
|
||||
event: 'server@' + req.method + '@' + req.originalUrl,
|
||||
});
|
||||
|
||||
next();
|
||||
} else {
|
||||
} catch (error) {
|
||||
console.error("Session checker error", error);
|
||||
return res.redirect('/login');
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = sessionChecker;
|
||||
module.exports = sessionChecker;
|
||||
|
||||
62
mongoDB.js
62
mongoDB.js
@@ -11,19 +11,39 @@ const paymentDB = require("./dbTools/payments.js");
|
||||
const songsDB = require("./dbTools/songs.js");
|
||||
|
||||
console.log("Connecting to MongoDB...");
|
||||
const nodeMajorVersion = parseInt((process.versions.node || "0").split(".")[0], 10);
|
||||
if (nodeMajorVersion >= 22) {
|
||||
console.warn("Warning: mongodb@3.x is not fully tested on Node.js 22+. Prefer Node.js 20 LTS for local stability.");
|
||||
}
|
||||
|
||||
const mongoConnectOptions = {
|
||||
useNewUrlParser: true,
|
||||
useUnifiedTopology: true,
|
||||
serverSelectionTimeoutMS: 10000,
|
||||
connectTimeoutMS: 10000,
|
||||
socketTimeoutMS: 45000,
|
||||
keepAlive: true,
|
||||
};
|
||||
|
||||
const getDB = new Promise((resolve, reject) => {
|
||||
const DB = {ObjectID: mongo.ObjectID};
|
||||
MongoClient.connect(mongoUrl, function(err, db) {
|
||||
MongoClient.connect(mongoUrl, mongoConnectOptions, function(err, db) {
|
||||
if (err) return reject(err);
|
||||
|
||||
console.log("Connected to DB!");
|
||||
DB.db = db;
|
||||
DB.ObjectID = ObjectID;
|
||||
|
||||
DB.db.on("close", () => console.error("MongoDB connection closed"));
|
||||
DB.db.on("reconnect", () => console.log("MongoDB reconnected"));
|
||||
DB.db.on("error", (error) => console.error("MongoDB connection error", error));
|
||||
|
||||
DB.usersCol = db.db(DBName).collection("users");
|
||||
DB.tokensCol = db.db(DBName).collection("tokens");
|
||||
DB.invitationCol = db.db(DBName).collection("invitation");
|
||||
DB.passwordLoginTokensCol = db.db(DBName).collection("password_login_tokens");
|
||||
DB.passwordLoginTokensCol.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 }).catch(console.error);
|
||||
DB.passwordLoginTokensCol.createIndex({ tokenHash: 1 }, { unique: true }).catch(console.error);
|
||||
|
||||
DB.checkSessionOnDB = async (session_id, user_sid)=>{
|
||||
const temp_id = new mongo.ObjectID(session_id);
|
||||
@@ -31,7 +51,7 @@ const getDB = new Promise((resolve, reject) => {
|
||||
const doc = await DB.tokensCol.findOne({"_id":temp_id});
|
||||
if(doc && doc.uid == user_sid){
|
||||
const userMongoId = new mongo.ObjectID(user_sid);
|
||||
const userInfo = await DB.usersCol.findOne({"_id": userMongoId}, {fields: {password: 0}});
|
||||
const userInfo = await DB.usersCol.findOne({"_id": userMongoId}, {projection: {password: 0}});
|
||||
return userInfo;
|
||||
}
|
||||
return false;
|
||||
@@ -61,6 +81,42 @@ const getDB = new Promise((resolve, reject) => {
|
||||
return DB.usersCol.findOne({ _id });
|
||||
}
|
||||
|
||||
DB.createPasswordLoginToken = async (userId, tokenHash, expiresAt) => {
|
||||
const userObjectId = mongo.ObjectID.isValid(userId) ? new mongo.ObjectID(userId) : userId;
|
||||
const tokenDoc = {
|
||||
userId: userObjectId,
|
||||
tokenHash,
|
||||
createdAt: new Date(),
|
||||
expiresAt,
|
||||
usedAt: null,
|
||||
};
|
||||
return DB.passwordLoginTokensCol.insertOne(tokenDoc).catch((err) => {
|
||||
console.log(err);
|
||||
return false;
|
||||
});
|
||||
};
|
||||
|
||||
DB.consumePasswordLoginToken = async (tokenHash) => {
|
||||
const now = new Date();
|
||||
const result = await DB.passwordLoginTokensCol.findOneAndUpdate(
|
||||
{
|
||||
tokenHash,
|
||||
usedAt: null,
|
||||
expiresAt: { $gt: now }
|
||||
},
|
||||
{
|
||||
$set: { usedAt: now }
|
||||
},
|
||||
{
|
||||
returnOriginal: false
|
||||
}
|
||||
).catch((err) => {
|
||||
console.log(err);
|
||||
return false;
|
||||
});
|
||||
return result?.value || null;
|
||||
};
|
||||
|
||||
let usernamesCache = {}
|
||||
DB.getUsernameByIdCache = async (userid)=>{
|
||||
if(!userid) return {};
|
||||
@@ -126,4 +182,4 @@ const getDB = new Promise((resolve, reject) => {
|
||||
});
|
||||
});
|
||||
|
||||
exports.getDB = getDB;
|
||||
exports.getDB = getDB;
|
||||
|
||||
@@ -8,7 +8,10 @@ const Notifications = require("./../notifications.js");
|
||||
DB.getDB.then((DB) => {
|
||||
|
||||
const getProfileId = (req) => {
|
||||
return DB.ObjectID(req.cookies.profile_id || req.query.profile_id || req.body.profile_id);
|
||||
const rawProfileId = req.cookies.profile_id || req.query.profile_id || req.body.profile_id || req.profileInfo?._id;
|
||||
if (!rawProfileId) return null;
|
||||
if (!DB.ObjectID.isValid(rawProfileId)) return null;
|
||||
return DB.ObjectID(rawProfileId);
|
||||
};
|
||||
|
||||
const postBelongToProfile = (post, profileid) => {
|
||||
@@ -155,12 +158,17 @@ DB.getDB.then((DB) => {
|
||||
* $ref: '#/components/schemas/Post'
|
||||
*/
|
||||
router.get("/organic", async (req, res) => {
|
||||
const profileid = getProfileId(req);
|
||||
let organicPosts = await DB.getFeed(profileid);
|
||||
//Add non-organic posts
|
||||
const nonOrganicPosts = await generateNonOrganicPosts(req, profileid);
|
||||
const posts = mergePosts(organicPosts, nonOrganicPosts);
|
||||
return res.json(posts);
|
||||
try {
|
||||
const profileid = getProfileId(req);
|
||||
if (!profileid) return res.status(400).json([]);
|
||||
let organicPosts = await DB.getFeed(profileid);
|
||||
const nonOrganicPosts = await generateNonOrganicPosts(req, profileid);
|
||||
const posts = mergePosts(organicPosts || [], nonOrganicPosts || []);
|
||||
return res.json(posts);
|
||||
} catch (error) {
|
||||
console.error("Error loading organic feed", error);
|
||||
return res.status(500).json([]);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -182,12 +190,17 @@ DB.getDB.then((DB) => {
|
||||
* $ref: '#/components/schemas/Post'
|
||||
*/
|
||||
router.get("/", async (req, res) => {
|
||||
const profileid = getProfileId(req);
|
||||
//Add non-organic posts
|
||||
const nonOrganicPosts = await generateNonOrganicPosts(req, profileid);
|
||||
let promotionalPosts = await DB.getPromotionalPosts(profileid);
|
||||
const posts = mergePosts(promotionalPosts, nonOrganicPosts);
|
||||
return res.json(posts);
|
||||
try {
|
||||
const profileid = getProfileId(req);
|
||||
if (!profileid) return res.status(400).json([]);
|
||||
const nonOrganicPosts = await generateNonOrganicPosts(req, profileid);
|
||||
let promotionalPosts = await DB.getPromotionalPosts(profileid);
|
||||
const posts = mergePosts(promotionalPosts || [], nonOrganicPosts || []);
|
||||
return res.json(posts);
|
||||
} catch (error) {
|
||||
console.error("Error loading feed", error);
|
||||
return res.status(500).json([]);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -980,4 +993,4 @@ DB.getDB.then((DB) => {
|
||||
|
||||
});
|
||||
|
||||
module.exports = router
|
||||
module.exports = router
|
||||
|
||||
@@ -795,12 +795,24 @@ DB.getDB.then((DB) => {
|
||||
* $ref: '#/components/schemas/Profile'
|
||||
*/
|
||||
router.get("/:id", async (req, res) => {
|
||||
let profileId = req.params.id;
|
||||
let profile = await DB.getProfile(profileId);
|
||||
return res.json({
|
||||
status: "ok",
|
||||
...profile
|
||||
});
|
||||
try {
|
||||
let profileId = req.params.id;
|
||||
let profile = await DB.getProfile(profileId);
|
||||
if (!profile || !profile._id) {
|
||||
return res.status(404).json({
|
||||
status: "Profile not found",
|
||||
});
|
||||
}
|
||||
return res.json({
|
||||
status: "ok",
|
||||
...profile
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error loading profile", error);
|
||||
return res.status(500).json({
|
||||
status: "Internal server error"
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -913,4 +925,4 @@ DB.getDB.then((DB) => {
|
||||
|
||||
});
|
||||
|
||||
module.exports = router
|
||||
module.exports = router
|
||||
|
||||
Reference in New Issue
Block a user