-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
hooks.server.ts
49 lines (38 loc) · 1.33 KB
/
hooks.server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import type { Handle } from '@sveltejs/kit';
import { USERS } from '$env/static/private';
import type { AuthUser } from '$lib/types';
/**
* ? The types you will need to copy are in $lib/types and src/app.d.ts
*/
const users: AuthUser[] = JSON.parse(USERS);
export const basicAuth: Handle = ({ event, resolve }) => {
const authorization = event.request.headers.get('Authorization');
if (!authorization || !authorization.startsWith('Basic '))
return new Response('Unauthorized', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Protected"',
},
});
const token = authorization.replace('Basic ', '');
const [username, password] = Buffer.from(token, 'base64')
.toString()
.split(':');
const user: AuthUser | undefined = users.find(
(u) => u.username === username && u.password === password,
);
if (!user)
return new Response('Unauthorized', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Protected"',
},
});
event.locals.user = {
username: user.username,
};
return resolve(event);
};
// Use sequence if you have multiple hooks
// https://kit.svelte.dev/docs/modules#sveltejs-kit-hooks-sequence
export const handle = basicAuth;