embark/lib/modules/authenticator/index.js

57 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-09-06 15:30:06 +00:00
const uuid = require('uuid/v1');
2018-09-06 20:06:07 +00:00
const ERROR_OBJ = {error: __('Wrong authentication token. Get your token from the Embark console by typing `token`')};
2018-09-06 15:30:06 +00:00
2018-09-06 20:06:07 +00:00
class Authenticator {
2018-09-06 15:30:06 +00:00
constructor(embark, _options) {
this.authToken = uuid();
2018-09-06 17:33:15 +00:00
this.embark = embark;
this.logger = embark.logger;
2018-09-06 20:06:07 +00:00
this.events = embark.events;
2018-09-06 15:30:06 +00:00
2018-09-06 17:33:15 +00:00
this.registerCalls();
2018-09-06 20:06:07 +00:00
this.registerEvents();
2018-09-06 17:33:15 +00:00
}
2018-09-06 15:30:06 +00:00
2018-09-06 17:33:15 +00:00
registerCalls() {
this.embark.registerAPICall(
2018-09-06 15:30:06 +00:00
'post',
2018-09-06 20:06:07 +00:00
'/embark-api/authorize',
2018-09-06 15:30:06 +00:00
(req, res) => {
if (req.body.token !== this.authToken) {
2018-09-06 20:06:07 +00:00
this.logger.warn(__('Someone tried and failed to authorize to the backend'));
2018-09-06 17:33:15 +00:00
this.logger.warn(__('- User-Agent: %s', req.headers['user-agent']));
this.logger.warn(__('- Referer: %s', req.headers.referer));
2018-09-06 20:06:07 +00:00
return res.send(ERROR_OBJ);
2018-09-06 15:30:06 +00:00
}
res.send();
}
);
2018-09-06 17:33:15 +00:00
this.embark.registerConsoleCommand((cmd, _options) => {
return {
match: () => cmd === "token",
process: (callback) => {
callback(null, __('Your authorisation token: %s', this.authToken));
}
};
});
2018-09-06 15:30:06 +00:00
}
2018-09-06 20:06:07 +00:00
registerEvents() {
this.events.once('outputDone', () => {
this.logger.info(__('Access the web backend with the following url: %s',
('http://localhost:8000/embark?token=' + this.authToken).underline));
});
this.events.setCommandHandler('api:authorize', (token, cb) => {
if (token !== this.authToken) {
return cb(ERROR_OBJ);
}
cb();
});
}
2018-09-06 15:30:06 +00:00
}
module.exports = Authenticator;