-
Notifications
You must be signed in to change notification settings - Fork 1
/
createAuthFile.ts
42 lines (34 loc) · 1.07 KB
/
createAuthFile.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
import { outputFile, pathExists } from "fs-extra";
import { join } from "path";
import { createHash } from "@utils/createHash";
import { htpasswd } from "@utils/htpasswd";
import settings from "@utils/settings";
import { Auth } from "@models/config";
/**
* Creates an htpasswd file in `settings.authPath`
* The name of the file is a hash of the contents
* @param users an array of {@link Auth} objects
* @returns {object} An object containing the filepath and the hash
*/
export const createAuthFile = async (
users: Auth[],
defaultUsername: string
): Promise<{ filepath: string; hash: string }> => {
const authUsers = users.map((user) =>
"password" in user
? {
...user,
username: user.username || defaultUsername
}
: user.raw
);
const hash = createHash(JSON.stringify(authUsers));
const filepath = join(settings.authPath, hash);
if (!(await pathExists(filepath))) {
const content = authUsers
.map((user) => (typeof user == "string" ? user : htpasswd(user)))
.join("\n");
await outputFile(filepath, content);
}
return { filepath, hash };
};