Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/next/lib/share/authenticate.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45/*6Authentication.7*/89import type { Request, Response } from "express";10import basicAuth from "basic-auth";11import { verify } from "password-hash";12import { isArray } from "lodash";13//import { getLogger } from "@cocalc/backend/logger";14import { VirtualHostInfo, Auth } from "./get-vhost-info";15//const dbg = getLogger("virtual-hosts:authenticate");1617interface Options {18req: Request;19res: Response;20path: string;21auth?: VirtualHostInfo;22}2324export default function isAuthenticated({25req,26res,27path,28auth,29}: Options): boolean {30if (auth == null) {31return true; // no authentication needed32}3334// strip any /'s from beginning of path (auth path's are assumed relative)35while (path[0] === "/") {36path = path.slice(1);37}3839let authInfo: Auth[] | undefined = undefined;40for (const p in auth) {41if (path.startsWith(p)) {42authInfo = auth[p];43break;44}45}4647if (authInfo == null) {48// don't need auth for this path49return true;50}5152if (!isArray(authInfo)) {53// do a double check...54res.statusCode = 401;55res.end(56"auth is misconfigured -- invalid auth field in the public_paths database."57);58return false;59}6061const credentials = basicAuth(req);62let fail: boolean = true;63if (credentials?.name && credentials?.pass) {64for (const { name, pass } of authInfo) {65if (name == credentials.name) {66if (verify(credentials.pass, pass)) {67fail = false;68}69break;70}71}72}7374if (fail) {75res.statusCode = 401;76res.setHeader("WWW-Authenticate", 'Basic realm="cocalc.com"');77res.end("Access denied");78return false;79}8081// access granted82return true;83}848586