-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
71 lines (53 loc) · 1.7 KB
/
index.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
67
68
69
70
71
'use strict';
const basicAuth = require('basic-auth');
const passwordGenerator = require('generate-password');
const PLUGIN_NAME = 'BS Authorization';
/**
* @param {Object} opts
* @param {BrowserSync} bs
*/
module.exports['plugin'] = (opts, bs) => {
opts = Object.assign({
generatePassword: {
length: 7,
numbers: true
},
user: 'browsersync',
pass: false,
use: true
}, opts);
if (!opts.use) {
return void 0;
}
let logger = bs.getLogger(PLUGIN_NAME).info('Access Info:');
if (typeof opts.logLevel !== 'undefined') {
logger.setLevel(opts.logLevel);
}
if (typeof opts.pass === 'undefined' || !opts.pass) {
Object.assign(opts, {
pass: passwordGenerator.generate(opts.generatePassword)
});
}
// Set bs-auth options in global Browsersync options
bs.setOption('bsAuth', opts);
console.log(' -------------------------------------');
console.log(` user: ${opts.user}`);
console.log(` password: ${opts.pass}`);
console.log(' -------------------------------------');
if (opts.use) {
// add middleware for Authorization
bs.addMiddleware('', (req, res, next) => {
let auth = basicAuth(req);
if (auth && auth.name === opts.user && auth.pass === opts.pass) {
return next();
} else {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', `Basic realm="${PLUGIN_NAME}"`);
res.end('Access denied');
}
}, {
id: 'Browsersync Server Authorization Middleware',
override: true
});
}
}