Skip to content

Commit

Permalink
csrf token finally fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
singharaj-usai committed Oct 11, 2024
1 parent 38d0b88 commit df27dbc
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
20 changes: 16 additions & 4 deletions client/js/auth/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,8 @@ const App = {
username: $("#username").val(),
email: $("#email").val(),
password: $("#password").val(),
confirmPassword: $("#confirm-password").val()
confirmPassword: $("#confirm-password").val(),
_csrf: csrfToken
};

this.showLoadingIndicator();
Expand All @@ -421,6 +422,7 @@ const App = {
type: "POST",
data: JSON.stringify(formData),
contentType: "application/json",
headers: csrfToken ? { 'X-CSRF-Token': csrfToken } : {},
success: (response) => {
this.hideLoadingIndicator();
this.showAlert("success", response.message);
Expand All @@ -431,7 +433,6 @@ const App = {
error: (xhr, status, error) => {
this.hideLoadingIndicator();
if (status === "timeout") {
// Assume the account was created successfully
this.showAlert("success", "Your account has been created successfully. You can now log in.");
setTimeout(() => {
window.location.href = "/login";
Expand All @@ -453,6 +454,9 @@ const App = {
const username = $("#username").val();
const password = $("#password").val();

const data = { username, password };
const headers = {};

// cloudflare captcha
/* const turnstileResponse = turnstile.getResponse();
console.log("Turnstile response:", turnstileResponse);
Expand All @@ -461,12 +465,20 @@ const App = {
return;
} */

// Add CSRF token if available
if (csrfToken) {
data._csrf = csrfToken;
headers['X-CSRF-Token'] = csrfToken;
}

$.ajax({
url: "/api/login",
method: "POST",
data: { username, password }, //captchaResponse: turnstileResponse },
headers: { 'CSRF-Token': csrfToken }, // CSRF token
data: data, //captchaResponse: turnstileResponse },
headers: headers,
xhrFields: {
withCredentials: true // cookies are sent with the request
},
success: (response) => {
localStorage.setItem("token", response.token);
localStorage.setItem("username", response.username);
Expand Down
22 changes: 16 additions & 6 deletions server/functions/api/routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ const authLimiter = rateLimit({
message: "Too many requests from this IP, please try again in 10 minute",
});

// for accounts signed up without csrf protection
const flexibleCsrfProtection = (req, res, next) => {
const csrfToken = req.headers['x-csrf-token'] || req.body._csrf;
if (csrfToken) {
csrfProtection(req, res, next);
} else {
console.warn('Request without CSRF token received');
next();
}
};

// Validation middleware
const validateUser = [
Expand Down Expand Up @@ -143,7 +153,7 @@ const validateUser = [


// REgister account
router.post("/register-create", csrfProtection, authLimiter, validateUser, async (req, res) => {
router.post("/register-create", flexibleCsrfProtection, authLimiter, validateUser, async (req, res) => {
try {
const { username, email, password } = req.body;
console.log("Registration attempt for:", email);
Expand Down Expand Up @@ -244,7 +254,7 @@ router.get("/validate-session", async (req, res) => {


// Check if user is banned
router.get("/check-ban", csrfProtection, authenticateToken, async (req, res) => {
router.get("/check-ban", flexibleCsrfProtection, authenticateToken, async (req, res) => {
try {
const user = await User.findById(req.user.userId);
if (!user) {
Expand All @@ -261,7 +271,7 @@ const MAX_LOGIN_ATTEMPTS = 5;
const LOCK_TIME = 2 * 60 * 1000; // 2 minutes

// Login endpoint
router.post("/login", csrfProtection, authLimiter, async (req, res) => {
router.post("/login", flexibleCsrfProtection, authLimiter, async (req, res) => {
try {
const { username, password } = req.body;
// console.log("Login attempt for:", username);
Expand Down Expand Up @@ -342,14 +352,14 @@ router.post("/login", csrfProtection, authLimiter, async (req, res) => {
res.cookie('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'Strict',
sameSite: 'Lax',
maxAge: 24 * 60 * 60 * 1000, // 1 day
});

res.json({

token,
username: user.username,
userId: user.userId,
userId: user._id,
signupDate: user.signupDate,
lastLoggedIn: user.lastLoggedIn,
isBanned: user.isBanned,
Expand Down

0 comments on commit df27dbc

Please sign in to comment.