1
0
Fork 0
mirror of https://github.com/seanmorley15/AdventureLog.git synced 2025-07-21 13:59:36 +02:00

Migrate to session based auth

This commit is contained in:
Sean Morley 2024-11-29 18:20:51 -05:00
parent b86c7258e7
commit c65fcc2558
13 changed files with 111 additions and 104 deletions

View file

@ -50,6 +50,7 @@ INSTALLED_APPS = (
"allauth_ui", "allauth_ui",
'allauth', 'allauth',
'allauth.account', 'allauth.account',
'allauth.mfa',
'allauth.headless', 'allauth.headless',
'allauth.socialaccount', 'allauth.socialaccount',
"widget_tweaks", "widget_tweaks",

View file

@ -152,34 +152,9 @@ export const actions: Actions = {
formDataToSend.append('end_date', end_date || ''); formDataToSend.append('end_date', end_date || '');
formDataToSend.append('link', link || ''); formDataToSend.append('link', link || '');
let auth = event.cookies.get('auth'); let sessionId = event.cookies.get('sessionid');
if (!auth) { if (!sessionId) {
const refresh = event.cookies.get('refresh');
if (!refresh) {
return {
status: 401,
body: { message: 'Unauthorized' }
};
}
let res = await tryRefreshToken(refresh);
if (res) {
auth = res;
event.cookies.set('auth', auth, {
httpOnly: true,
sameSite: 'lax',
expires: new Date(Date.now() + 60 * 60 * 1000), // 60 minutes
path: '/'
});
} else {
return {
status: 401,
body: { message: 'Unauthorized' }
};
}
}
if (!auth) {
return { return {
status: 401, status: 401,
body: { message: 'Unauthorized' } body: { message: 'Unauthorized' }
@ -199,9 +174,10 @@ export const actions: Actions = {
method: 'PATCH', method: 'PATCH',
headers: { headers: {
'X-CSRFToken': csrfToken, 'X-CSRFToken': csrfToken,
Cookie: auth Cookie: `sessionid=${sessionId}; csrftoken=${csrfToken}`
}, },
body: formDataToSend body: formDataToSend,
credentials: 'include'
}); });
if (!res.ok) { if (!res.ok) {
@ -218,6 +194,10 @@ export const actions: Actions = {
}, },
get: async (event) => { get: async (event) => {
if (!event.locals.user) { if (!event.locals.user) {
return {
status: 401,
body: { message: 'Unauthorized' }
};
} }
const formData = await event.request.formData(); const formData = await event.request.formData();
@ -240,19 +220,20 @@ export const actions: Actions = {
let previous = null; let previous = null;
let count = 0; let count = 0;
let visitedFetch = await fetch( let collectionsFetch = await fetch(
`${serverEndpoint}/api/collections/?order_by=${order_by}&order_direction=${order_direction}`, `${serverEndpoint}/api/collections/?order_by=${order_by}&order_direction=${order_direction}`,
{ {
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${event.cookies.get('sessionid')}`
} },
credentials: 'include'
} }
); );
if (!visitedFetch.ok) { if (!collectionsFetch.ok) {
console.error('Failed to fetch visited adventures'); console.error('Failed to fetch visited adventures');
return redirect(302, '/login'); return redirect(302, '/login');
} else { } else {
let res = await visitedFetch.json(); let res = await collectionsFetch.json();
let visited = res.results as Adventure[]; let visited = res.results as Adventure[];
next = res.next; next = res.next;
previous = res.previous; previous = res.previous;
@ -309,15 +290,16 @@ export const actions: Actions = {
} }
const fullUrl = `${serverEndpoint}${url}`; const fullUrl = `${serverEndpoint}${url}`;
console.log(fullUrl);
console.log(serverEndpoint); let sessionId = event.cookies.get('sessionid');
try { try {
const response = await fetch(fullUrl, { const response = await fetch(fullUrl, {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} },
credentials: 'include'
}); });
if (!response.ok) { if (!response.ok) {

View file

@ -6,9 +6,10 @@ const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load = (async (event) => { export const load = (async (event) => {
const id = event.params as { id: string }; const id = event.params as { id: string };
let sessionid = event.cookies.get('sessionid');
let request = await fetch(`${endpoint}/api/collections/${id.id}/`, { let request = await fetch(`${endpoint}/api/collections/${id.id}/`, {
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionid}`
} }
}); });
if (!request.ok) { if (!request.ok) {
@ -30,7 +31,7 @@ export const load = (async (event) => {
}) satisfies PageServerLoad; }) satisfies PageServerLoad;
import type { Actions } from '@sveltejs/kit'; import type { Actions } from '@sveltejs/kit';
import { tryRefreshToken } from '$lib/index.server'; import { fetchCSRFToken, tryRefreshToken } from '$lib/index.server';
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000'; const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
@ -39,31 +40,6 @@ export const actions: Actions = {
const id = event.params as { id: string }; const id = event.params as { id: string };
const adventureId = id.id; const adventureId = id.id;
if (!event.locals.user) {
const refresh = event.cookies.get('refresh');
let auth = event.cookies.get('auth');
if (!refresh) {
return {
status: 401,
body: { message: 'Unauthorized' }
};
}
let res = await tryRefreshToken(refresh);
if (res) {
auth = res;
event.cookies.set('auth', auth, {
httpOnly: true,
sameSite: 'lax',
expires: new Date(Date.now() + 60 * 60 * 1000), // 60 minutes
path: '/'
});
} else {
return {
status: 401,
body: { message: 'Unauthorized' }
};
}
}
if (!adventureId) { if (!adventureId) {
return { return {
status: 400, status: 400,
@ -71,15 +47,27 @@ export const actions: Actions = {
}; };
} }
let sessionId = event.cookies.get('sessionid');
if (!sessionId) {
return {
status: 401,
error: new Error('Unauthorized')
};
}
let csrfToken = await fetchCSRFToken();
let res = await fetch(`${serverEndpoint}/api/collections/${event.params.id}`, { let res = await fetch(`${serverEndpoint}/api/collections/${event.params.id}`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
Cookie: `${event.cookies.get('auth')}`, Cookie: `sessionid=${sessionId}; csrftoken=${csrfToken}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json',
} 'X-CSRFToken': csrfToken
},
credentials: 'include'
}); });
console.log(res);
if (!res.ok) { if (!res.ok) {
return { return {
status: res.status, status: res.status,

View file

@ -8,13 +8,11 @@ export const load = (async (event) => {
if (!event.locals.user) { if (!event.locals.user) {
return redirect(302, '/login'); return redirect(302, '/login');
} else { } else {
let next = null; let sessionId = event.cookies.get('sessionid');
let previous = null;
let count = 0;
let adventures: Adventure[] = []; let adventures: Adventure[] = [];
let initialFetch = await fetch(`${serverEndpoint}/api/collections/archived/`, { let initialFetch = await fetch(`${serverEndpoint}/api/collections/archived/`, {
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} }
}); });
if (!initialFetch.ok) { if (!initialFetch.ok) {

View file

@ -8,15 +8,16 @@ export const load = (async (event) => {
if (!event.locals.user) { if (!event.locals.user) {
return redirect(302, '/login'); return redirect(302, '/login');
} else { } else {
let sessionId = event.cookies.get('sessionid');
let visitedFetch = await fetch(`${endpoint}/api/adventures/all/?include_collections=true`, { let visitedFetch = await fetch(`${endpoint}/api/adventures/all/?include_collections=true`, {
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} }
}); });
let visitedRegionsFetch = await fetch(`${endpoint}/api/visitedregion/`, { let visitedRegionsFetch = await fetch(`${endpoint}/api/visitedregion/`, {
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} }
}); });

View file

@ -4,15 +4,16 @@ const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
export const load: PageServerLoad = async (event: RequestEvent) => { export const load: PageServerLoad = async (event: RequestEvent) => {
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000'; const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
if (!event.locals.user || !event.cookies.get('auth')) { if (!event.locals.user || !event.cookies.get('sessionid')) {
return redirect(302, '/login'); return redirect(302, '/login');
} }
let sessionId = event.cookies.get('sessionid');
let stats = null; let stats = null;
let res = await event.fetch(`${endpoint}/api/stats/counts/`, { let res = await event.fetch(`${endpoint}/api/stats/counts/`, {
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} }
}); });
if (!res.ok) { if (!res.ok) {

View file

@ -14,12 +14,14 @@ export const load = (async (event) => {
return { data: [] }; return { data: [] };
} }
let sessionId = event.cookies.get('sessionid');
let res = await fetch( let res = await fetch(
`${serverEndpoint}/api/adventures/search/?query=${query}&property=${property}`, `${serverEndpoint}/api/adventures/search/?query=${query}&property=${property}`,
{ {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} }
} }
); );

View file

@ -2,18 +2,20 @@ import { fail, redirect, type Actions } from '@sveltejs/kit';
import type { PageServerLoad } from '../$types'; import type { PageServerLoad } from '../$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL']; const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { User } from '$lib/types'; import type { User } from '$lib/types';
import { fetchCSRFToken } from '$lib/index.server';
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000'; const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load: PageServerLoad = async (event) => { export const load: PageServerLoad = async (event) => {
if (!event.locals.user) { if (!event.locals.user) {
return redirect(302, '/'); return redirect(302, '/');
} }
if (!event.cookies.get('auth')) { let sessionId = event.cookies.get('sessionid');
if (!sessionId) {
return redirect(302, '/'); return redirect(302, '/');
} }
let res = await fetch(`${endpoint}/auth/user/`, { let res = await fetch(`${endpoint}/auth/user/`, {
headers: { headers: {
Cookie: event.cookies.get('auth') || '' Cookie: `sessionid=${sessionId}`
} }
}); });
let user = (await res.json()) as User; let user = (await res.json()) as User;
@ -34,7 +36,8 @@ export const actions: Actions = {
if (!event.locals.user) { if (!event.locals.user) {
return redirect(302, '/'); return redirect(302, '/');
} }
if (!event.cookies.get('auth')) { let sessionId = event.cookies.get('sessionid');
if (!sessionId) {
return redirect(302, '/'); return redirect(302, '/');
} }
@ -49,7 +52,7 @@ export const actions: Actions = {
const resCurrent = await fetch(`${endpoint}/auth/user/`, { const resCurrent = await fetch(`${endpoint}/auth/user/`, {
headers: { headers: {
Cookie: event.cookies.get('auth') || '' Cookie: `sessionid=${sessionId}`
} }
}); });
@ -94,10 +97,13 @@ export const actions: Actions = {
} }
formDataToSend.append('public_profile', public_profile.toString()); formDataToSend.append('public_profile', public_profile.toString());
let csrfToken = await fetchCSRFToken();
let res = await fetch(`${endpoint}/auth/user/`, { let res = await fetch(`${endpoint}/auth/user/`, {
method: 'PATCH', method: 'PATCH',
headers: { headers: {
Cookie: event.cookies.get('auth') || '' Cookie: `sessionid=${sessionId}; csrftoken=${csrfToken}`,
'X-CSRFToken': csrfToken
}, },
body: formDataToSend body: formDataToSend
}); });
@ -120,7 +126,8 @@ export const actions: Actions = {
if (!event.locals.user) { if (!event.locals.user) {
return redirect(302, '/'); return redirect(302, '/');
} }
if (!event.cookies.get('auth')) { let sessionId = event.cookies.get('sessionid');
if (!sessionId) {
return redirect(302, '/'); return redirect(302, '/');
} }
console.log('changePassword'); console.log('changePassword');
@ -133,10 +140,13 @@ export const actions: Actions = {
return fail(400, { message: 'Passwords do not match' }); return fail(400, { message: 'Passwords do not match' });
} }
let csrfToken = await fetchCSRFToken();
let res = await fetch(`${endpoint}/auth/password/change/`, { let res = await fetch(`${endpoint}/auth/password/change/`, {
method: 'POST', method: 'POST',
headers: { headers: {
Cookie: event.cookies.get('auth') || '', Cookie: `sessionid=${sessionId}; csrftoken=${csrfToken}`,
'X-CSRFToken': csrfToken,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
body: JSON.stringify({ body: JSON.stringify({
@ -153,7 +163,8 @@ export const actions: Actions = {
if (!event.locals.user) { if (!event.locals.user) {
return redirect(302, '/'); return redirect(302, '/');
} }
if (!event.cookies.get('auth')) { let sessionId = event.cookies.get('sessionid');
if (!sessionId) {
return redirect(302, '/'); return redirect(302, '/');
} }
const formData = await event.request.formData(); const formData = await event.request.formData();
@ -161,11 +172,13 @@ export const actions: Actions = {
if (!new_email) { if (!new_email) {
return fail(400, { message: 'Email is required' }); return fail(400, { message: 'Email is required' });
} else { } else {
let csrfToken = await fetchCSRFToken();
let res = await fetch(`${endpoint}/auth/change-email/`, { let res = await fetch(`${endpoint}/auth/change-email/`, {
method: 'POST', method: 'POST',
headers: { headers: {
Cookie: event.cookies.get('auth') || '', Cookie: `sessionid=${sessionId}; csrftoken=${csrfToken}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
}, },
body: JSON.stringify({ body: JSON.stringify({
new_email new_email

View file

@ -8,9 +8,10 @@ export const load = (async (event) => {
if (!event.locals.user) { if (!event.locals.user) {
return redirect(302, '/login'); return redirect(302, '/login');
} else { } else {
let sessionId = event.cookies.get('sessionid');
let res = await fetch(`${serverEndpoint}/api/collections/shared/`, { let res = await fetch(`${serverEndpoint}/api/collections/shared/`, {
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} }
}); });
if (!res.ok) { if (!res.ok) {

View file

@ -4,7 +4,8 @@ const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000'; const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load = (async (event) => { export const load = (async (event) => {
if (!event.cookies.get('auth')) { let sessionId = event.cookies.get('sessionid');
if (!sessionId) {
return redirect(302, '/login'); return redirect(302, '/login');
} }
const uuid = event.params.uuid; const uuid = event.params.uuid;
@ -13,7 +14,7 @@ export const load = (async (event) => {
} }
let res = await fetch(`${serverEndpoint}/auth/user/${uuid}/`, { let res = await fetch(`${serverEndpoint}/auth/user/${uuid}/`, {
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} }
}); });
if (!res.ok) { if (!res.ok) {

View file

@ -4,13 +4,14 @@ const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000'; const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load = (async (event) => { export const load = (async (event) => {
if (!event.cookies.get('auth')) { let sessionId = event.cookies.get('sessionid');
if (!sessionId) {
return redirect(302, '/login'); return redirect(302, '/login');
} }
const res = await fetch(`${serverEndpoint}/auth/users/`, { const res = await fetch(`${serverEndpoint}/auth/users/`, {
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} }
}); });
if (!res.ok) { if (!res.ok) {

View file

@ -2,6 +2,7 @@ const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { Country } from '$lib/types'; import type { Country } from '$lib/types';
import { redirect, type Actions } from '@sveltejs/kit'; import { redirect, type Actions } from '@sveltejs/kit';
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
import { fetchCSRFToken } from '$lib/index.server';
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000'; const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
@ -11,6 +12,9 @@ export const load = (async (event) => {
} else { } else {
const res = await event.fetch(`${endpoint}/api/countries/`, { const res = await event.fetch(`${endpoint}/api/countries/`, {
method: 'GET', method: 'GET',
headers: {
Cookie: `sessionid=${event.cookies.get('sessionid')}`
},
credentials: 'include' credentials: 'include'
}); });
if (!res.ok) { if (!res.ok) {
@ -25,8 +29,6 @@ export const load = (async (event) => {
}; };
} }
} }
return {};
}) satisfies PageServerLoad; }) satisfies PageServerLoad;
export const actions: Actions = { export const actions: Actions = {
@ -39,15 +41,20 @@ export const actions: Actions = {
}; };
} }
if (!event.locals.user || !event.cookies.get('auth')) { let sessionId = event.cookies.get('sessionid');
if (!event.locals.user || !sessionId) {
return redirect(302, '/login'); return redirect(302, '/login');
} }
let csrfToken = await fetchCSRFToken();
const res = await fetch(`${endpoint}/api/visitedregion/`, { const res = await fetch(`${endpoint}/api/visitedregion/`, {
method: 'POST', method: 'POST',
headers: { headers: {
Cookie: `${event.cookies.get('auth')}`, Cookie: `sessionid=${sessionId}; csrftoken=${csrfToken}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
}, },
body: JSON.stringify({ region: body.regionId }) body: JSON.stringify({ region: body.regionId })
}); });
@ -73,15 +80,20 @@ export const actions: Actions = {
const visitId = body.visitId as number; const visitId = body.visitId as number;
if (!event.locals.user || !event.cookies.get('auth')) { let sessionId = event.cookies.get('sessionid');
if (!event.locals.user || !sessionId) {
return redirect(302, '/login'); return redirect(302, '/login');
} }
let csrfToken = await fetchCSRFToken();
const res = await fetch(`${endpoint}/api/visitedregion/${visitId}/`, { const res = await fetch(`${endpoint}/api/visitedregion/${visitId}/`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
Cookie: `${event.cookies.get('auth')}`, Cookie: `sessionid=${sessionId}; csrftoken=${csrfToken}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
} }
}); });

View file

@ -12,10 +12,16 @@ export const load = (async (event) => {
let visitedRegions: VisitedRegion[] = []; let visitedRegions: VisitedRegion[] = [];
let country: Country; let country: Country;
let sessionId = event.cookies.get('sessionid');
if (!sessionId) {
return redirect(302, '/login');
}
let res = await fetch(`${endpoint}/api/${id}/regions/`, { let res = await fetch(`${endpoint}/api/${id}/regions/`, {
method: 'GET', method: 'GET',
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} }
}); });
if (!res.ok) { if (!res.ok) {
@ -28,7 +34,7 @@ export const load = (async (event) => {
res = await fetch(`${endpoint}/api/${id}/visits/`, { res = await fetch(`${endpoint}/api/${id}/visits/`, {
method: 'GET', method: 'GET',
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} }
}); });
if (!res.ok) { if (!res.ok) {
@ -41,7 +47,7 @@ export const load = (async (event) => {
res = await fetch(`${endpoint}/api/countries/${regions[0].country}/`, { res = await fetch(`${endpoint}/api/countries/${regions[0].country}/`, {
method: 'GET', method: 'GET',
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `sessionid=${sessionId}`
} }
}); });
if (!res.ok) { if (!res.ok) {