1
1
'use strict'
2
- const { HAPI_SERVER_PORT , HAPI_SERVER_ADDRESS } = process . env
2
+ const { HAPI_SERVER_PORT , HAPI_SERVER_ADDRESS , HAPI_VALID_USERS } = process . env
3
3
4
4
const Hapi = require ( '@hapi/hapi' )
5
+ const Bcrypt = require ( 'bcrypt' )
5
6
6
7
const routes = require ( './routes' )
7
8
const { workerService } = require ( './services' )
8
9
10
+ const validate = async ( request , username , password ) => {
11
+ if ( ! HAPI_VALID_USERS ) return { credentials : null , isValid : false }
12
+
13
+ const users = JSON . parse ( HAPI_VALID_USERS || '[]' )
14
+ const user = users . find ( user => user . username === username )
15
+
16
+ if ( ! user ) {
17
+ return { credentials : null , isValid : false }
18
+ }
19
+
20
+ const saltRounds = 10
21
+ const hashPassword = await Bcrypt . hash ( user . password , saltRounds )
22
+ const isValid = await Bcrypt . compare ( password , hashPassword )
23
+ const credentials = { id : users . indexOf ( user ) , name : user . username }
24
+
25
+ return { isValid, credentials }
26
+ }
27
+
9
28
const init = async ( ) => {
10
29
const server = Hapi . server ( {
11
30
port : HAPI_SERVER_PORT ,
@@ -16,6 +35,10 @@ const init = async () => {
16
35
debug : { request : [ 'handler' ] }
17
36
} )
18
37
38
+ await server . register ( require ( '@hapi/basic' ) )
39
+
40
+ server . auth . strategy ( 'simple' , 'basic' , { validate } )
41
+
19
42
server . route ( routes )
20
43
21
44
await server . start ( )
0 commit comments