CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/next/lib/share/authenticate.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
/*
7
Authentication.
8
*/
9
10
import type { Request, Response } from "express";
11
import basicAuth from "basic-auth";
12
import { verify } from "password-hash";
13
import { isArray } from "lodash";
14
//import { getLogger } from "@cocalc/backend/logger";
15
import { VirtualHostInfo, Auth } from "./get-vhost-info";
16
//const dbg = getLogger("virtual-hosts:authenticate");
17
18
interface Options {
19
req: Request;
20
res: Response;
21
path: string;
22
auth?: VirtualHostInfo;
23
}
24
25
export default function isAuthenticated({
26
req,
27
res,
28
path,
29
auth,
30
}: Options): boolean {
31
if (auth == null) {
32
return true; // no authentication needed
33
}
34
35
// strip any /'s from beginning of path (auth path's are assumed relative)
36
while (path[0] === "/") {
37
path = path.slice(1);
38
}
39
40
let authInfo: Auth[] | undefined = undefined;
41
for (const p in auth) {
42
if (path.startsWith(p)) {
43
authInfo = auth[p];
44
break;
45
}
46
}
47
48
if (authInfo == null) {
49
// don't need auth for this path
50
return true;
51
}
52
53
if (!isArray(authInfo)) {
54
// do a double check...
55
res.statusCode = 401;
56
res.end(
57
"auth is misconfigured -- invalid auth field in the public_paths database."
58
);
59
return false;
60
}
61
62
const credentials = basicAuth(req);
63
let fail: boolean = true;
64
if (credentials?.name && credentials?.pass) {
65
for (const { name, pass } of authInfo) {
66
if (name == credentials.name) {
67
if (verify(credentials.pass, pass)) {
68
fail = false;
69
}
70
break;
71
}
72
}
73
}
74
75
if (fail) {
76
res.statusCode = 401;
77
res.setHeader("WWW-Authenticate", 'Basic realm="cocalc.com"');
78
res.end("Access denied");
79
return false;
80
}
81
82
// access granted
83
return true;
84
}
85
86