forked from Tech-Challenge-7SOAT/serverless-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.js
66 lines (56 loc) · 1.56 KB
/
handler.js
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
const { Client } = require('pg');
const { getSecrets } = require('./secrets');
const effects = {
ALLOW: 'Allow',
DENY: 'Deny'
};
const policyResponse = (effect, resource) => {
return {
principalId: 'user',
policyDocument: {
Version: '2012-10-17',
Statement: [{
Action: 'execute-api:Invoke',
Effect: effect,
Resource: resource
}]
}
};
}
const getDatabaseSecrets = async () => {
const secrets = await getSecrets();
const { host, port, dbName, user, password } = JSON.parse(secrets);
return {
host,
port,
password,
username: user,
database: dbName
};
}
exports.handler = async (event, context) => {
const { authorization, methodArn } = event;
if (!authorization) {
console.log('Authorization token not found');
return policyResponse(effects.DENY, methodArn);
}
const dbConfig = await getDatabaseSecrets();
console.log('Database configuration:', dbConfig);
const client = new Client(dbConfig);
try {
await client.connect();
const query = 'SELECT id FROM tb_customers WHERE cpf = $1';
const result = await client.query(query, [authorization]);
console.log('Query result:', result.rows);
if (result.rows.length === 0) {
console.log('User not found with cpf:', authorization);
return policyResponse(effects.DENY, methodArn);
}
return policyResponse(effects.ALLOW, methodArn);
} catch (error) {
console.error('Error executing query', error);
return policyResponse(effects.DENY, methodArn);
} finally {
await client.end();
}
}