forked from juliendorra/esquisse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.ts
49 lines (38 loc) · 1.48 KB
/
auth.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 "https://deno.land/x/dotenv/load.ts";
import { compare } from "./bcrypt.ts";
const PREFIX = "USER_";
const env = Deno.env.toObject();
const userEntries = Object.entries(env)
.filter(([key]) => key.startsWith(PREFIX))
.map(([key, value]) => [key.replace(PREFIX, ''), value]);
console.log('Loaded user data from environment variables ', userEntries);
// A helper function to perform Basic Auth check
export async function basicAuth(request: Request): Promise<boolean> {
const authorization = request.headers.get("Authorization");
if (!authorization) {
console.log('Authorization header missing');
return false;
}
const encodedCreds = authorization.split(" ")[1];
if (!encodedCreds) {
console.log('Credentials not provided in Authorization header');
return false;
}
const decodedCreds = atob(encodedCreds);
const [username, password] = decodedCreds.split(":");
console.log(`Received authorization request for user: ${username}`);
// Check credentials
for (const [envUser, envHash] of userEntries) {
if (envUser === username) {
if (await compare(password, envHash)) {
console.log(`Authentication successful for user: ${username}`);
return true;
} else {
console.log(`Invalid password for user: ${username}`);
return false;
}
}
}
console.log(`User not found: ${username}`);
return false;
}