aboutsummaryrefslogtreecommitdiff
path: root/src/server/apis/google/CredentialsLoader.ts
blob: a6e0644c3a44f95fc1c7803eaaf7a0c466b49b93 (plain)
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
54
55
56
57
58
59
60
61
62
63
64
import { readFile, readFileSync } from 'fs';
import { SecureContextOptions } from 'tls';
import { blue, red } from 'colors';
import { pathFromRoot } from '../../ActionUtilities';

export namespace GoogleCredentialsLoader {
    export interface InstalledCredentials {
        client_id: string;
        project_id: string;
        auth_uri: string;
        token_uri: string;
        auth_provider_x509_cert_url: string;
        client_secret: string;
        redirect_uris: string[];
    }

    export let ProjectCredentials: InstalledCredentials;

    export async function loadCredentials() {
        ProjectCredentials = await new Promise<InstalledCredentials>(resolve => {
            // eslint-disable-next-line no-path-concat
            readFile(__dirname + '/google_project_credentials.json', (err, content) => {
                if (err) {
                    console.log('Error loading client secret file: ' + err);
                    return;
                }
                resolve(JSON.parse(content.toString()).installed);
            });
        });
    }
}

export namespace SSL {
    export let Credentials: SecureContextOptions = {};
    export let Loaded = false;

    const suffixes = {
        privateKey: '.key',
        certificate: '.crt',
        caBundle: '-ca.crt',
    };

    export async function loadCredentials() {
        const { serverName } = process.env;
        const cert = (suffix: string) => readFileSync(pathFromRoot(`./${serverName}${suffix}`)).toString();
        try {
            Credentials.key = cert(suffixes.privateKey);
            Credentials.cert = cert(suffixes.certificate);
            Credentials.ca = cert(suffixes.caBundle);
            Loaded = true;
        } catch (e) {
            Credentials = {};
            Loaded = false;
        }
    }

    export function exit() {
        console.log(red('Running this server in release mode requires the following SSL credentials in the project root:'));
        const serverName = process.env.serverName ? process.env.serverName : '{process.env.serverName}';
        Object.values(suffixes).forEach(suffix => console.log(blue(`${serverName}${suffix}`)));
        console.log(red('Please ensure these files exist and restart, or run this in development mode.'));
        process.exit(0);
    }
}