@@ -41,6 +41,10 @@ function initApp(config, callback) {
41
41
app . server = http . createServer ( app . express ) ;
42
42
app . webservice = createClient ( webserviceUrl ) ;
43
43
44
+ // Apply basic authentication if necessary
45
+ loadBasicAuth ( app , config ) ;
46
+
47
+ // Load middleware
44
48
loadMiddleware ( app ) ;
45
49
46
50
// View engine
@@ -63,6 +67,34 @@ function defaultConfig(config) {
63
67
return config ;
64
68
}
65
69
70
+ function loadBasicAuth ( app , config ) {
71
+ app . express . use ( ( request , response , next ) => {
72
+ const protection = config . protection . enabled || false ;
73
+ if ( protection ) {
74
+ const auth = request . headers . authorization ;
75
+ if ( ! auth ) {
76
+ // Prompt the user for credentials
77
+ response . set ( 'WWW-Authenticate' , 'Basic realm="401"' ) ;
78
+ return response . status ( 401 ) . send ( 'Authentication required.' ) ;
79
+ }
80
+
81
+ const credentials = Buffer . from ( auth . split ( ' ' ) [ 1 ] , 'base64' ) . toString ( ) . split ( ':' ) ;
82
+ const [ username , password ] = credentials ;
83
+
84
+ // Use credentials from config
85
+ const USER = config . protection . user || '' ;
86
+ const PASS = config . protection . pass || '' ;
87
+
88
+ if ( username === USER && password === PASS ) {
89
+ return next ( ) ; // Proceed to the next middleware or route
90
+ }
91
+ response . set ( 'WWW-Authenticate' , 'Basic realm="401"' ) ; // Prompt again
92
+ return response . status ( 401 ) . send ( 'Authentication required.' ) ;
93
+ }
94
+ return next ( ) ;
95
+ } ) ;
96
+ }
97
+
66
98
function loadMiddleware ( app ) {
67
99
app . express . use ( compression ( ) ) ;
68
100
0 commit comments