Skip to content

Commit

Permalink
Merge pull request #441 from seanmorley15/development
Browse files Browse the repository at this point in the history
fix: dynamically set session cookie domain based on request hostname
  • Loading branch information
seanmorley15 authored Jan 13, 2025
2 parents 145a3f0 + 4a36fbb commit 609f68b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
1 change: 0 additions & 1 deletion backend/server/main/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,6 @@
parsed_url = urlparse(frontend_url)
domain_parts = parsed_url.hostname.split('.')
SESSION_COOKIE_DOMAIN = '.' + '.'.join(domain_parts[-2:]) if len(domain_parts) > 1 else parsed_url.hostname
print(SESSION_COOKIE_DOMAIN)

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
Expand Down
24 changes: 22 additions & 2 deletions frontend/src/routes/login/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,19 +103,39 @@ export const actions: Actions = {
}
};

function handleSuccessfulLogin(event: RequestEvent<RouteParams, '/login'>, response: Response) {
function handleSuccessfulLogin(event: RequestEvent, response: Response) {
const setCookieHeader = response.headers.get('Set-Cookie');
if (setCookieHeader) {
const sessionIdRegex = /sessionid=([^;]+).*?expires=([^;]+)/;
const match = setCookieHeader.match(sessionIdRegex);
if (match) {
const [, sessionId, expiryString] = match;

// Get the proper cookie domain
const hostname = event.url.hostname;
const domainParts = hostname.split('.');
let cookieDomain: string | undefined = undefined;

if (domainParts.length > 2) {
// For subdomains like app.mydomain.com -> .mydomain.com
cookieDomain = '.' + domainParts.slice(-2).join('.');
} else if (domainParts.length === 2) {
// For root domains like mydomain.com -> .mydomain.com
cookieDomain = '.' + hostname;
} else {
// For localhost or single-part domains (e.g., "localhost")
cookieDomain = undefined; // Do not set the domain
}

console.log('Setting sessionid cookie with domain:', cookieDomain);

event.cookies.set('sessionid', sessionId, {
path: '/',
httpOnly: true,
sameSite: 'lax',
secure: event.url.protocol === 'https:',
expires: new Date(expiryString)
expires: new Date(expiryString),
domain: cookieDomain // Set the domain dynamically
});
}
}
Expand Down

0 comments on commit 609f68b

Please sign in to comment.