deno.land / x / lume@v2.1.4 / middlewares / basic_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
50
51
52
53
import { merge } from "../core/utils/object.ts";
import type { Middleware, RequestHandler } from "../core/server.ts";
export interface Options { realm: string; users: Record<string, string>;}
export const defaults: Options = { realm: "Basic Authentication", users: {},};
// Code from https://deno.land/x/basic_auth@v1.0.1/mod.tsexport default function BasicAuth( userOptions?: Partial<Options>,): Middleware { const options = merge(defaults, userOptions);
return async (request: Request, next: RequestHandler) => { const authorization = request.headers.get("authorization"); if (authorization && checkAuthorization(authorization, options.users)) { return await next(request); }
return new Response("401 Unauthorized", { status: 401, statusText: "Unauthorized", headers: { "www-authenticate": `Basic realm="${options.realm}"`, }, }); };}
function checkAuthorization( authorization: string, users: Record<string, string>,): boolean { const match = authorization.match(/^Basic\s+(.*)$/); if (match) { const [user, pw] = atob(match[1]).split(":"); for (const [u, p] of Object.entries(users)) { if (user === u && pw == p) { return true; } } }
return false;}
lume

Version Info

Tagged at
7 months ago