Skip to content
This repository was archived by the owner on Mar 31, 2025. It is now read-only.

Commit f379a24

Browse files
committed
First implementationof basic authorizer
1 parent cb24f0f commit f379a24

File tree

6 files changed

+1974
-0
lines changed

6 files changed

+1974
-0
lines changed

.eslintrc.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"extends": "standard",
3+
"env": {
4+
"mocha": true
5+
},
6+
"rules": {
7+
"semi": [
8+
"error",
9+
"always"
10+
],
11+
"no-unused-vars": [
12+
"warn"
13+
]
14+
}
15+
}

src/config.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"username": "USERNAME",
3+
"password_salt": "SALT",
4+
"password_hash": "PASSWORD_HASH"
5+
}

src/index.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
'use strict';
2+
3+
const crypto = require('crypto');
4+
5+
const UnauthorizedResponse = {
6+
status: '401',
7+
headers: {
8+
'www-authenticate': [{
9+
key: 'WWW-Authenticate',
10+
value: 'Basic realm="Secure Area"'
11+
}]
12+
}
13+
};
14+
15+
exports.handler = async (event) => {
16+
const request = event.Records[0].cf.request;
17+
18+
if (request.headers.authorization === undefined) {
19+
return UnauthorizedResponse;
20+
}
21+
22+
const authorizationToken = request.headers.authorization[0].value;
23+
24+
const credentials = decodeAuthToken(authorizationToken);
25+
if (credentials === null) {
26+
return UnauthorizedResponse;
27+
}
28+
29+
const config = this.loadConfiguration();
30+
31+
const username = credentials.username;
32+
const passwordHash = hashedPassword(credentials.password, config.password_salt);
33+
34+
if (username !== config.username || passwordHash !== config.password_hash) {
35+
return UnauthorizedResponse;
36+
}
37+
38+
return request;
39+
};
40+
41+
function decodeAuthToken (authToken) {
42+
if (!authToken.startsWith('Basic ')) {
43+
console.log('Wrong header value: ' + authToken);
44+
return null;
45+
}
46+
47+
var parts = Buffer.from(authToken.substring(6), 'base64').toString().split(':');
48+
49+
if (parts.length !== 2) {
50+
console.log('Wrong format: Expected 2 parts but found ' + parts.length);
51+
return null;
52+
}
53+
54+
return {
55+
username: parts[0],
56+
password: parts[1]
57+
};
58+
}
59+
60+
function hashedPassword (password, salt) {
61+
const hash = crypto.createHash('sha256');
62+
hash.update(password + salt);
63+
return hash.digest('hex');
64+
}
65+
66+
exports.loadConfiguration = () => {
67+
return require('./config.json');
68+
};

0 commit comments

Comments
 (0)