szurubooru/static/js/controllers/auth_controller.js

57 lines
1.8 KiB
JavaScript
Raw Normal View History

'use strict';
2016-03-30 21:01:18 +02:00
const cookies = require('js-cookie');
const page = require('page');
const api = require('../api.js');
const topNavController = require('../controllers/top_nav_controller.js');
const LoginView = require('../views/login_view.js');
class AuthController {
constructor() {
this.loginView = new LoginView();
2016-03-30 21:01:18 +02:00
const auth = cookies.getJSON('auth');
if (auth && auth.user && auth.password) {
api.login(auth.user, auth.password).catch(errorMessage => {
2016-03-30 21:01:18 +02:00
cookies.remove('auth');
2016-03-31 22:33:49 +02:00
page('/');
this.loginView.notifyError(
'An error happened while trying to log you in: ' +
errorMessage);
2016-03-30 21:01:18 +02:00
});
}
}
loginRoute() {
topNavController.activate('login');
2016-03-28 00:19:44 +02:00
this.loginView.render({
2016-03-30 21:01:18 +02:00
login: (name, password, doRemember) => {
return new Promise((resolve, reject) => {
api.login(name, password)
2016-03-30 21:01:18 +02:00
.then(() => {
const options = {};
if (doRemember) {
2016-03-30 21:01:18 +02:00
options.expires = 365;
}
2016-03-30 21:01:18 +02:00
cookies.set(
'auth',
{'user': name, 'password': password},
options);
resolve();
page('/');
2016-03-31 22:33:49 +02:00
this.loginView.notifySuccess('Logged in');
2016-03-30 21:01:18 +02:00
}).catch(errorMessage => { reject(errorMessage); });
});
2016-03-28 00:19:44 +02:00
}});
}
logoutRoute() {
api.logout();
2016-03-30 21:01:18 +02:00
cookies.remove('auth');
page('/');
2016-03-31 22:33:49 +02:00
this.loginView.notifySuccess('Logged out');
}
}
module.exports = new AuthController();