chnages
chnages
This commit is contained in:
1 parent
3e22355510
commit
e22a8dc248
71 files changed
+24775
-1
No files matched your search
@@ -0,0 +1,29 @@
|
||||
// ============================================================
|
||||
// deviceParser.js — Parse User-Agent into readable device info
|
||||
// ============================================================
|
||||
|
||||
function parseDevice(userAgent) {
|
||||
if (!userAgent) return 'Unknown Device';
|
||||
|
||||
// Detect OS
|
||||
let os = 'Unknown OS';
|
||||
if (/windows nt 10/i.test(userAgent)) os = 'Windows 10/11';
|
||||
else if (/windows nt/i.test(userAgent)) os = 'Windows';
|
||||
else if (/android/i.test(userAgent)) os = 'Android';
|
||||
else if (/iphone/i.test(userAgent)) os = 'iPhone';
|
||||
else if (/ipad/i.test(userAgent)) os = 'iPad';
|
||||
else if (/mac os/i.test(userAgent)) os = 'macOS';
|
||||
else if (/linux/i.test(userAgent)) os = 'Linux';
|
||||
|
||||
// Detect browser
|
||||
let browser = 'Unknown Browser';
|
||||
if (/edg\//i.test(userAgent)) browser = 'Edge';
|
||||
else if (/opr\//i.test(userAgent)) browser = 'Opera';
|
||||
else if (/chrome/i.test(userAgent)) browser = 'Chrome';
|
||||
else if (/firefox/i.test(userAgent)) browser = 'Firefox';
|
||||
else if (/safari/i.test(userAgent)) browser = 'Safari';
|
||||
|
||||
return `${browser} on ${os}`;
|
||||
}
|
||||
|
||||
module.exports = { parseDevice };
|
||||
@@ -0,0 +1,114 @@
|
||||
// ============================================================
|
||||
// email.js — Send emails via Gmail using Nodemailer
|
||||
// ============================================================
|
||||
|
||||
const nodemailer = require('nodemailer');
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
service: 'gmail',
|
||||
auth: {
|
||||
user: process.env.EMAIL_USER,
|
||||
pass: process.env.EMAIL_PASS,
|
||||
},
|
||||
});
|
||||
|
||||
// Send the OTP email to the user
|
||||
async function sendOTPEmail(toEmail, username, otp) {
|
||||
const mailOptions = {
|
||||
from: `"Auth System" <${process.env.EMAIL_USER}>`,
|
||||
to: toEmail,
|
||||
subject: 'Your OTP Code',
|
||||
html: `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 400px; margin: auto;
|
||||
border: 1px solid #e5e7eb; border-radius: 8px; padding: 24px;">
|
||||
<h2 style="color: #16a34a; margin-top: 0;">One-Time Password</h2>
|
||||
<p>Hello <strong>${username}</strong>,</p>
|
||||
<p>Your login OTP code is:</p>
|
||||
<div style="font-size: 2rem; font-weight: bold; letter-spacing: 8px;
|
||||
color: #16a34a; text-align: center; padding: 16px 0;">
|
||||
${otp}
|
||||
</div>
|
||||
<p style="color: #6b7280; font-size: 0.9rem;">
|
||||
This code expires in <strong>5 minutes</strong>.<br/>
|
||||
If you did not request this, please ignore this email.
|
||||
</p>
|
||||
</div>
|
||||
`,
|
||||
};
|
||||
|
||||
await transporter.sendMail(mailOptions);
|
||||
}
|
||||
|
||||
// Send the Change Password Link email
|
||||
async function sendChangePasswordLink(toEmail, username, link) {
|
||||
const mailOptions = {
|
||||
from: `"Auth System" <${process.env.EMAIL_USER}>`,
|
||||
to: toEmail,
|
||||
subject: 'Password Change Request',
|
||||
html: `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 400px; margin: auto;
|
||||
border: 1px solid #e5e7eb; border-radius: 8px; padding: 24px;">
|
||||
<h2 style="color: #1d4ed8; margin-top: 0;">Change Your Password</h2>
|
||||
<p>Hello <strong>${username}</strong>,</p>
|
||||
<p>You requested to change your password. Click the secure link below to set a new password:</p>
|
||||
<div style="text-align: center; margin: 24px 0;">
|
||||
<a href="${link}" style="background-color: #1d4ed8; color: white; padding: 12px 24px;
|
||||
text-decoration: none; border-radius: 6px; font-weight: bold;">
|
||||
Set New Password
|
||||
</a>
|
||||
</div>
|
||||
<p style="color: #6b7280; font-size: 0.9rem;">
|
||||
This link expires in <strong>15 minutes</strong>.<br/>
|
||||
If you did not request this, please ignore this email and your password will remain unchanged.
|
||||
</p>
|
||||
</div>
|
||||
`,
|
||||
};
|
||||
|
||||
await transporter.sendMail(mailOptions);
|
||||
}
|
||||
|
||||
// Send a new device login alert email
|
||||
async function sendNewDeviceAlert(toEmail, username, deviceInfo, ipAddress, loginTime) {
|
||||
const timeStr = new Date(loginTime).toLocaleString('en-US', {
|
||||
weekday: 'short', year: 'numeric', month: 'short', day: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit', timeZoneName: 'short',
|
||||
});
|
||||
|
||||
const mailOptions = {
|
||||
from: `"Auth System" <${process.env.EMAIL_USER}>`,
|
||||
to: toEmail,
|
||||
subject: 'New Device Login Detected',
|
||||
html: `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 440px; margin: auto;
|
||||
border: 1px solid #e5e7eb; border-radius: 8px; padding: 24px;">
|
||||
<h2 style="color: #ea580c; margin-top: 0;">New Device Login</h2>
|
||||
<p>Hello <strong>${username}</strong>,</p>
|
||||
<p>We detected a new login to your account from a device we haven't seen before:</p>
|
||||
<table style="width: 100%; border-collapse: collapse; margin: 16px 0; font-size: 0.9rem;">
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; background: #f9fafb; border: 1px solid #e5e7eb; font-weight: 600; width: 100px;">Device</td>
|
||||
<td style="padding: 8px 12px; border: 1px solid #e5e7eb;">${deviceInfo}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; background: #f9fafb; border: 1px solid #e5e7eb; font-weight: 600;">IP Address</td>
|
||||
<td style="padding: 8px 12px; border: 1px solid #e5e7eb; font-family: monospace;">${ipAddress}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; background: #f9fafb; border: 1px solid #e5e7eb; font-weight: 600;">Time</td>
|
||||
<td style="padding: 8px 12px; border: 1px solid #e5e7eb;">${timeStr}</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p style="color: #6b7280; font-size: 0.9rem;">
|
||||
If this was you, no action is needed.<br/>
|
||||
If you don't recognize this login, please <strong>change your password immediately</strong>
|
||||
and log out of all devices from your dashboard.
|
||||
</p>
|
||||
</div>
|
||||
`,
|
||||
};
|
||||
|
||||
await transporter.sendMail(mailOptions);
|
||||
}
|
||||
|
||||
module.exports = { sendOTPEmail, sendChangePasswordLink, sendNewDeviceAlert };
|
||||
@@ -0,0 +1,19 @@
|
||||
// ============================================================
|
||||
// hash.js — Password hashing using bcrypt
|
||||
// ============================================================
|
||||
|
||||
const bcrypt = require('bcryptjs');
|
||||
|
||||
function generateSalt() {
|
||||
return bcrypt.genSaltSync(10);
|
||||
}
|
||||
|
||||
function hashPassword(password, salt) {
|
||||
return bcrypt.hashSync(password, salt);
|
||||
}
|
||||
|
||||
function verifyPassword(inputPassword, storedHash) {
|
||||
return bcrypt.compareSync(inputPassword, storedHash);
|
||||
}
|
||||
|
||||
module.exports = { generateSalt, hashPassword, verifyPassword };
|
||||
@@ -0,0 +1,66 @@
|
||||
// ============================================================
|
||||
// logger.js — Save activity logs to the database
|
||||
// ============================================================
|
||||
// Every important action (login, register, OTP, etc.) calls
|
||||
// this function to leave a record in the logs table.
|
||||
// ============================================================
|
||||
|
||||
const pool = require('../db');
|
||||
|
||||
// Actions — use these constants everywhere so spelling is consistent
|
||||
const ACTIONS = {
|
||||
REGISTER_SUCCESS: 'REGISTER_SUCCESS',
|
||||
REGISTER_FAILED: 'REGISTER_FAILED',
|
||||
LOGIN_SUCCESS: 'LOGIN_SUCCESS',
|
||||
LOGIN_FAILED: 'LOGIN_FAILED',
|
||||
ACCOUNT_LOCKED: 'ACCOUNT_LOCKED',
|
||||
OTP_SENT: 'OTP_SENT',
|
||||
OTP_RESENT: 'OTP_RESENT',
|
||||
OTP_VERIFIED: 'OTP_VERIFIED',
|
||||
OTP_FAILED: 'OTP_FAILED',
|
||||
OTP_EXPIRED: 'OTP_EXPIRED',
|
||||
LOGOUT: 'LOGOUT',
|
||||
CHANGE_PASSWORD: 'CHANGE_PASSWORD',
|
||||
CHANGE_PASSWORD_FAILED:'CHANGE_PASSWORD_FAILED',
|
||||
ADMIN_UNLOCK_USER: 'ADMIN_UNLOCK_USER',
|
||||
ADMIN_DELETE_USER: 'ADMIN_DELETE_USER',
|
||||
ADMIN_CHANGE_ROLE: 'ADMIN_CHANGE_ROLE',
|
||||
CAPTCHA_FAILED: 'CAPTCHA_FAILED',
|
||||
LOGOUT_ALL: 'LOGOUT_ALL',
|
||||
FORGOT_PASSWORD: 'FORGOT_PASSWORD',
|
||||
FORGOT_PASSWORD_FAILED:'FORGOT_PASSWORD_FAILED',
|
||||
RESET_PASSWORD: 'RESET_PASSWORD',
|
||||
RESET_PASSWORD_FAILED: 'RESET_PASSWORD_FAILED',
|
||||
PASSWORD_EXPIRED: 'PASSWORD_EXPIRED',
|
||||
NEW_DEVICE_LOGIN: 'NEW_DEVICE_LOGIN',
|
||||
};
|
||||
|
||||
// Get IP address from the request object
|
||||
function getIP(req) {
|
||||
return (
|
||||
req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
|
||||
req.socket?.remoteAddress ||
|
||||
'unknown'
|
||||
);
|
||||
}
|
||||
|
||||
// Write a log entry to the database
|
||||
// userId — can be null (e.g. failed login where user doesn't exist)
|
||||
// action — use ACTIONS constants above
|
||||
// status — 'success' | 'failed' | 'warning'
|
||||
// details — any extra human-readable info
|
||||
async function log(userId, action, status, details, req) {
|
||||
try {
|
||||
const ip = req ? getIP(req) : 'system';
|
||||
await pool.query(
|
||||
`INSERT INTO logs (user_id, action, status, details, ip_address)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
[userId || null, action, status, details || null, ip]
|
||||
);
|
||||
} catch (err) {
|
||||
// Never crash the app because logging failed
|
||||
console.error('[Logger] Failed to write log:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { log, ACTIONS };
|
||||
@@ -0,0 +1,30 @@
|
||||
// ============================================================
|
||||
// otp.js — One-Time Password (OTP) generator
|
||||
// ============================================================
|
||||
|
||||
const crypto = require('crypto');
|
||||
const bcrypt = require('bcryptjs');
|
||||
|
||||
// Generate a random 6-digit OTP using crypto.randomInt()
|
||||
function generateOTP() {
|
||||
return crypto.randomInt(100000, 1000000).toString();
|
||||
}
|
||||
|
||||
// Get the expiry time: 5 minutes from now
|
||||
function getOTPExpiry() {
|
||||
const expiry = new Date();
|
||||
expiry.setMinutes(expiry.getMinutes() + 5);
|
||||
return expiry;
|
||||
}
|
||||
|
||||
// Hash an OTP with bcrypt before storing in DB
|
||||
function hashOTP(otp) {
|
||||
return bcrypt.hashSync(String(otp), 10);
|
||||
}
|
||||
|
||||
// Verify an OTP against a stored bcrypt hash
|
||||
function verifyOTPHash(inputOTP, storedHash) {
|
||||
return bcrypt.compareSync(String(inputOTP), storedHash);
|
||||
}
|
||||
|
||||
module.exports = { generateOTP, getOTPExpiry, hashOTP, verifyOTPHash };
|
||||
@@ -0,0 +1,30 @@
|
||||
// ============================================================
|
||||
// turnstile.js — Cloudflare Turnstile CAPTCHA verification
|
||||
// ============================================================
|
||||
// Shared helper so both the auth flow and the public Contact Us
|
||||
// form can validate Turnstile tokens server-side against the
|
||||
// existing TURNSTILE_SECRET_KEY. The browser never bypasses this.
|
||||
// ============================================================
|
||||
|
||||
const axios = require('axios');
|
||||
|
||||
async function verifyTurnstile(token) {
|
||||
// If no token supplied, fail closed.
|
||||
if (!token) return false;
|
||||
try {
|
||||
const response = await axios.post(
|
||||
'https://challenges.cloudflare.com/turnstile/v0/siteverify',
|
||||
new URLSearchParams({
|
||||
secret: process.env.TURNSTILE_SECRET_KEY,
|
||||
response: token,
|
||||
}),
|
||||
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
|
||||
);
|
||||
return response.data.success === true;
|
||||
} catch (err) {
|
||||
console.error('Turnstile verification error:', err.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { verifyTurnstile };
|
||||
@@ -0,0 +1,102 @@
|
||||
// ============================================================
|
||||
// validator.js — Input validation and sanitization
|
||||
// ============================================================
|
||||
// Always validate user input before storing it in the database.
|
||||
// This protects against bad data and injection attacks.
|
||||
// ============================================================
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// Load simple leaked passwords dictionary into memory
|
||||
let leakedPasswords = new Set();
|
||||
try {
|
||||
const filePath = path.join(__dirname, '..', 'leaked_passwords.txt');
|
||||
const data = fs.readFileSync(filePath, 'utf8');
|
||||
data.split(/\r?\n/).forEach(line => {
|
||||
const pwd = line.trim();
|
||||
if (pwd) leakedPasswords.add(pwd);
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('Could not load leaked_passwords.txt. Leaked password checking is disabled.');
|
||||
}
|
||||
|
||||
// Check if email format is valid (e.g. user@example.com)
|
||||
function validateEmail(email) {
|
||||
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return regex.test(email);
|
||||
}
|
||||
|
||||
// Username: only letters, numbers, underscores. Length 3-30.
|
||||
function validateUsername(username) {
|
||||
const regex = /^[a-zA-Z0-9_]{3,30}$/;
|
||||
return regex.test(username);
|
||||
}
|
||||
|
||||
// Check if password exists in our leaked passwords file
|
||||
function isLeakedPassword(password) {
|
||||
return leakedPasswords.has(password);
|
||||
}
|
||||
|
||||
// Password must be at least 8 characters and contain:
|
||||
// - at least 1 uppercase letter
|
||||
// - at least 1 lowercase letter
|
||||
// - at least 1 number
|
||||
// - at least 1 special character
|
||||
function validatePassword(password) {
|
||||
if (typeof password !== 'string' || password.length < 8) return false;
|
||||
if (!/[A-Z]/.test(password)) return false; // uppercase
|
||||
if (!/[a-z]/.test(password)) return false; // lowercase
|
||||
if (!/[0-9]/.test(password)) return false; // digit
|
||||
if (!/[^a-zA-Z0-9]/.test(password)) return false; // special char
|
||||
return true;
|
||||
}
|
||||
|
||||
// Returns a user-friendly message about what's missing from the password
|
||||
function getPasswordErrors(password) {
|
||||
const errors = [];
|
||||
if (typeof password !== 'string') return ['Password is required.'];
|
||||
if (password.length < 8) errors.push('at least 8 characters');
|
||||
if (!/[A-Z]/.test(password)) errors.push('an uppercase letter');
|
||||
if (!/[a-z]/.test(password)) errors.push('a lowercase letter');
|
||||
if (!/[0-9]/.test(password)) errors.push('a number');
|
||||
if (!/[^a-zA-Z0-9]/.test(password)) errors.push('a special character');
|
||||
return errors;
|
||||
}
|
||||
|
||||
// Sanitize input to prevent XSS (cross-site scripting)
|
||||
// This escapes HTML special characters like < > & " '
|
||||
function sanitize(input) {
|
||||
if (typeof input !== 'string') return input;
|
||||
return input
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
// Password strength checker — returns 'weak', 'medium', or 'strong'
|
||||
// Used on the frontend to show a live strength indicator
|
||||
function checkPasswordStrength(password) {
|
||||
let score = 0;
|
||||
if (password.length >= 8) score++; // basic length
|
||||
if (password.length >= 12) score++; // longer = better
|
||||
if (/[A-Z]/.test(password)) score++; // has uppercase
|
||||
if (/[0-9]/.test(password)) score++; // has number
|
||||
if (/[^a-zA-Z0-9]/.test(password)) score++; // has special char
|
||||
|
||||
if (score <= 2) return 'weak';
|
||||
if (score <= 3) return 'medium';
|
||||
return 'strong';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
validateEmail,
|
||||
validateUsername,
|
||||
validatePassword,
|
||||
getPasswordErrors,
|
||||
isLeakedPassword,
|
||||
sanitize,
|
||||
checkPasswordStrength,
|
||||
};
|
||||
Reference in new issue
Block a user