-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
67 lines (53 loc) · 1.68 KB
/
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict';
import bcrypt from 'bcryptjs';
import { IConfig, Loader as ConfigLoader } from './config';
import { Callback, Context, APIGatewayTokenAuthorizerEvent } from 'aws-lambda';
async function validate(username: string, password: string) {
const config: IConfig = await ConfigLoader.load();
const passwordHash = config.auth_backends.predefined.users[username];
if (!passwordHash) {
return false;
}
return bcrypt.compare(password, passwordHash);
}
function generatePolicy(principalId: string, effect: string, resource: string) {
const authResponse: any = {
principalId: principalId
};
if (effect && resource) {
authResponse.policyDocument = {
Version: '2012-10-17',
Statement: [
{
Action: 'execute-api:Invoke',
Effect: effect,
Resource: resource
}
]
};
}
return authResponse;
}
async function checkCredentials(event: APIGatewayTokenAuthorizerEvent) {
const token = event.authorizationToken.split(/\s+/).pop() || '';
const auth = new Buffer(token, 'base64').toString();
const parts = auth.split(/:/);
const username = parts[0] || '';
const password = parts[1] || '';
if (!token) {
return false;
}
return await validate(username, password);
}
export async function auth (
event: APIGatewayTokenAuthorizerEvent,
context: Context,
callback: Callback
) {
const isAuthorized = await checkCredentials(event);
if (!isAuthorized) {
callback('Unauthorized');
return;
}
return generatePolicy('user', 'Allow', event.methodArn);
}