Skip to content

Commit

Permalink
Merge pull request #229 from BetterLectio/auth-serverside-dev
Browse files Browse the repository at this point in the history
Auth serverside dev
  • Loading branch information
victorDigital committed Nov 17, 2023
2 parents 2cf493b + ac09209 commit a3cad0b
Show file tree
Hide file tree
Showing 21 changed files with 304 additions and 296 deletions.
2 changes: 2 additions & 0 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ rules:
complexity: 0
max-len: 0
linebreak-style: 0
space-before-function-paren: 0
newline-per-chained-call: 0
id-length: [warn, { exceptions: [i, j, k, x, y] }]
multiline-comment-style: [error, separate-lines]
svelte/indent: [error, { indent: tab, switchCase: 0 }]
Expand Down
5 changes: 4 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@
"editor.defaultFormatter": "svelte.svelte-vscode"
},
"svelte.plugin.svelte.format.enable": false,
"files.eol": "\n"
"files.eol": "\n",
"cSpell.words": [
"lectio"
]
}
68 changes: 65 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@
"eslint-plugin-svelte": "^2.26.0",
"html5-qrcode": "^2.3.8",
"postcss": "^8.4.23",
"simple-svelte-autocomplete": "^2.5.2",
"svelte": "^3.54.0",
"svelte-eslint-parser": "^0.32.2",
"sveltekit-superforms": "^1.10.2",
"tailwindcss": "^3.3.2",
"vite": "^4.3.9"
"vite": "^4.3.9",
"zod": "^3.22.4"
},
"type": "module",
"dependencies": {
Expand All @@ -43,4 +46,4 @@
"swiper": "^11.0.4",
"theme-change": "^2.5.0"
}
}
}
2 changes: 1 addition & 1 deletion src/app.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
%sveltekit.head%
</head>

<body data-sveltekit-preload-data="hover" class="antialiased selection:bg-base-content selection:text-base-100">
<body data-sveltekit-preload-data="tap" class="antialiased selection:bg-base-content selection:text-base-100">
<div>%sveltekit.body%</div>
</body>

Expand Down
2 changes: 1 addition & 1 deletion src/hooks.client.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Replay, handleErrorWithSentry } from '@sentry/sveltekit';
import * as Sentry from '@sentry/sveltekit';
import { Replay, handleErrorWithSentry } from '@sentry/sveltekit';

Sentry.init({
environment: import.meta.env.MODE,
Expand Down
2 changes: 1 addition & 1 deletion src/lib/components/SideBar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@
<a href="/studieplan" class="btn btn-sm mb-1 flex flex-col content-center w-full tooltip tooltip-right" data-tip="Studieplan" tabindex="0">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-mortarboard-fill" viewBox="0 0 16 16"
><path d="M14.5 3a.5.5 0 0 1 .5.5v9a.5.5 0 0 1-.5.5h-13a.5.5 0 0 1-.5-.5v-9a.5.5 0 0 1 .5-.5h13zm-13-1A1.5 1.5 0 0 0 0 3.5v9A1.5 1.5 0 0 0 1.5 14h13a1.5 1.5 0 0 0 1.5-1.5v-9A1.5 1.5 0 0 0 14.5 2h-13z"/>
<path d="M3 8.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0 2a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5zm0-5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-9a.5.5 0 0 1-.5-.5v-1z"/></svg
<path d="M3 8.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0 2a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5zm0-5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-9a.5.5 0 0 1-.5-.5v-1z"/></svg
>
</a>
<a href="/værktøjer" class="btn btn-sm mb-1 flex flex-col content-center w-full tooltip tooltip-right" data-tip="Værktøjer" tabindex="0">
Expand Down
4 changes: 3 additions & 1 deletion src/lib/js/HoldOversætter.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ export function holdOversætter(holdForkortet = '', holdArray = []) {

export async function holdOversætterNy(holdId, fallback = 'Andet') {
try {
const { fag } = await get(`/hold_til_fag?id=${ holdId}`);
throw 'rate limiter fucker meget (fucker med check cookie (ikke en god ting))';
// eslint-disable-next-line no-unreachable
const { fag } = await get(`/hold_til_fag?id=${holdId}`);
return fag;
} catch {
return fallback;
Expand Down
8 changes: 3 additions & 5 deletions src/lib/js/LectioCookieHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@ export function cookieInfo() {
return new Promise(resolve => {
if (
!localStorage.getItem('lectio-cookie')
&& window.location.href.split('?')[0].split('/').at(-1) !== 'auth'
&& window.location.href.split('?')[0].split('/').at(-1) !== ''
&& window.location.href.split('?')[0].split('/').at(-1) !== 'auth'
&& window.location.href.split('?')[0].split('/').at(-1) !== ''
) {
console.log('Redirect to auth page');
const transformedLink = encodeURIComponent(window.location.href);
window.location.href = `/auth?redirect=${ transformedLink}`;
// error handling based on page
} else {
try {
const cookie = localStorage.getItem('lectio-cookie');
Expand Down
59 changes: 25 additions & 34 deletions src/lib/js/http.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { addNotification } from '$lib/js/notifyStore.js';

// async function sha256(str) {
// const buf = await crypto.subtle.digest("SHA-256", new TextEncoder("utf-8").encode(str));
// return Array.prototype.map.call(new Uint8Array(buf), (x) => ("00" + x.toString(16)).slice(-2)).join("");
Expand All @@ -17,15 +15,17 @@ export function reloadData(reload = true) {
if (reload) window.location.reload();
}

async function checkCookieValidity() {
const cookieValidationCheck = await fetch(`${api}/check-cookie`, { headers: { 'lectio-cookie': localStorage.getItem('lectio-cookie') } });
const { valid: isCookieValid } = await cookieValidationCheck.json();
// the following function is know to cu

return {
isCookieValid,
lectioCookie: cookieValidationCheck.headers.get('set-lectio-cookie')
};
}
// async function checkCookieValidity() {
// const cookieValidationCheck = await fetch(`${api}/check-cookie`, { headers: { 'lectio-cookie': localStorage.getItem('lectio-cookie') } });
// const { valid: isCookieValid } = await cookieValidationCheck.json();
//
// return {
// isCookieValid,
// lectioCookie: cookieValidationCheck.headers.get('set-lectio-cookie')
// };
// }

export async function get(endpoint, body = null) {
// FIXME: code does not work
Expand All @@ -39,13 +39,6 @@ export async function get(endpoint, body = null) {
// await new Promise(resolve => setTimeout(resolve, 10));
// }

// If the user is not authenticated, redirect to the auth page
if (localStorage.getItem('lectio-cookie') === null) {
console.log('No cookie, redirecting to auth page');
const transformedLink = encodeURIComponent(window.location.href);
window.location.href = `/auth?redirect=${transformedLink}`;
}

let nonce = localStorage.getItem('nonce');
if (nonce === null) {
reloadData(false);
Expand Down Expand Up @@ -76,25 +69,23 @@ export async function get(endpoint, body = null) {
return JSON.parse(textResponse.replaceAll('\n', ' '));
}

// check cookie er en del af load funktionen og er derfor ikke nødvendig her

// Responsen er ikke OK, derfor validerer vi om det var en fejl med requesten,
// eller om vores cookie er udløbet/ikke valid
const { isCookieValid, lectioCookie } = await checkCookieValidity();

if (isCookieValid) {
if (lectioCookie !== null) localStorage.setItem('lectio-cookie', lectioCookie);

console.error(`Error fetching data from ${api}${endpoint}`,
'\n\nrequest response:',
response,
'\n\nrequest response body:',
textResponse);
} else {
console.log('Cookie not valid, redirecting to auth page.');
addNotification('Din session er ugyldig, omdirigerer til login-side', 'alert-error');

const transformedLink = encodeURIComponent(window.location.href);
window.location.href = `/auth?redirect=${transformedLink}`;
}
// const { isCookieValid, lectioCookie } = await checkCookieValidity();

// if (isCookieValid) {
// if (lectioCookie !== null) localStorage.setItem('lectio-cookie', lectioCookie);

// console.error(`Error fetching data from ${api}${endpoint}`,
// '\n\nrequest response:',
// response,
// '\n\nrequest response body:',
// textResponse);
// } else {
// // error handle based on page
// }

return null;
}
Expand Down
7 changes: 7 additions & 0 deletions src/lib/js/serverCookies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export async function validCookie(base64Cookie) {
const cookies = await JSON.parse(await Buffer.from(base64Cookie, 'base64'));
const skoleId = cookies[await (await cookies.map(cookie => cookie.name)).indexOf('LastLoginExamno')].value;
const response = await fetch(`https://www.lectio.dk/lectio/${skoleId}/help/mainhelp.aspx`, { headers: { cookie: await (await cookies.map(cookie => `${cookie.name}=${cookie.value}`)).join('; ') } });

return (await response.text()).includes('Log ud');
}
1 change: 0 additions & 1 deletion src/routes/+layout.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export const load = ({ url: { pathname } }) => ({ pathname });
export const ssr = false;

import { PUBLIC_MIXPANEL_TOKEN } from '$env/static/public';
Expand Down
32 changes: 26 additions & 6 deletions src/routes/+layout.server.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,29 @@
import { Redirect } from '@sveltejs/kit';
import { redirect } from '@sveltejs/kit';
import { validCookie } from '../lib/js/serverCookies.js';

/** @type {import('./$types').LayoutServerLoad} */
export async function load({ cookies, url }) {
// check cookies to check if user is logged in
// if not, redirect to /login

return {};
// make the redirect in case redirect its needed
const redirectFromAuth = encodeURIComponent(url.href);
try {
const lectioCookie = cookies.get('lectio-cookie');
if (url.pathname !== '/auth') {
if (!lectioCookie) {
throw redirect(302, `/auth${redirectFromAuth ? `?redirect=${redirectFromAuth}` : ''}`);
}
// Check if the cookie is valid
const cookieIsValid = await validCookie(lectioCookie);
if (!cookieIsValid) {
// delete the cookie if it exists
if (cookies.get('lectio-cookie')) cookies.delete('lectio-cookie');
// redirect to auth page
throw redirect(302, `/auth${redirectFromAuth ? `?redirect=${redirectFromAuth}` : ''}`);
}
}
return { lectioCookie, pathname: url.pathname };
} catch (error) {
// redirect to auth page and pass the redirect url and delete the cookie
console.error('Cookie-check error: ',error);
if (cookies.get('lectio-cookie')) cookies.delete('lectio-cookie');
throw redirect(302, `/auth${redirectFromAuth ? `?redirect=${redirectFromAuth}` : ''}`);
}
}
7 changes: 5 additions & 2 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@
import { cookieInfo } from '$lib/js/LectioCookieHandler.js';
import { onMount } from 'svelte';
import { onNavigate } from '$app/navigation';
import { page } from '$app/stores';
import { themeChange } from 'theme-change';
import { version } from '$app/environment';
import { page } from '$app/stores';
export let data = null;
console.log(data);
if (data.lectioCookie) localStorage.setItem('lectio-cookie', data.lectioCookie);
else localStorage.removeItem('lectio-cookie');
const app = $page.url.searchParams.get('app');
if (app === 'iOS') $mobile = 'iOS';
Expand Down Expand Up @@ -133,7 +136,7 @@
localStorage.setItem('schoolId', schoolId);
localStorage.setItem('theme', theme);
window.location.href = '/auth';
window.location.href = '/logout';
}}
class="btn-error btn">Log mig ud!</button
>
Expand Down
9 changes: 9 additions & 0 deletions src/routes/+page.server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { redirect } from '@sveltejs/kit';


export function load({ cookies, url }) {
// if the path is "/" and the user has a cookie, redirect to "/forside"
const lectioCookie = cookies.get('lectio-cookie');
if (url.pathname === '/' && lectioCookie) throw redirect(302, '/forside');
return {};
}
Loading

0 comments on commit a3cad0b

Please sign in to comment.