szurubooru/client/js/controllers/users_controller.js

104 lines
3.2 KiB
JavaScript
Raw Normal View History

'use strict';
const cookies = require('js-cookie');
const page = require('page');
const api = require('../api.js');
2016-04-07 19:03:49 +02:00
const events = require('../events.js');
const topNavController = require('../controllers/top_nav_controller.js');
const RegistrationView = require('../views/registration_view.js');
const UserView = require('../views/user_view.js');
class UsersController {
constructor() {
this.registrationView = new RegistrationView();
this.userView = new UserView();
}
registerRoutes() {
page('/register', () => { this.createUserRoute(); });
page('/users', () => { this.listUsersRoute(); });
page(
'/user/:name',
2016-04-06 22:34:21 +02:00
(ctx, next) => { this.loadUserRoute(ctx, next); },
(ctx, next) => { this.showUserRoute(ctx, next); });
page(
'/user/:name/edit',
2016-04-06 22:34:21 +02:00
(ctx, next) => { this.loadUserRoute(ctx, next); },
(ctx, next) => { this.editUserRoute(ctx, next); });
page.exit('/user/', (ctx, next) => { this.user = null; });
}
listUsersRoute() {
topNavController.activate('users');
}
createUserRoute() {
topNavController.activate('register');
this.registrationView.render({register: (...args) => {
return this._register(...args);
}});
}
_register(name, password, email) {
const data = {
'name': name,
'password': password,
'email': email
};
return new Promise((resolve, reject) => {
api.post('/users/', data).then(() => {
api.login(name, password).then(() => {
cookies.set('auth', {'user': name, 'password': password});
resolve();
page('/');
2016-04-07 19:03:49 +02:00
events.notify(events.Success, 'Welcome aboard!');
}).catch(response => {
reject(response.description);
});
}).catch(response => {
reject(response.description);
});
});
}
2016-04-06 22:34:21 +02:00
loadUserRoute(ctx, next) {
if (ctx.state.user) {
next();
} else if (this.user && this.user.name == ctx.params.name) {
ctx.state.user = this.user;
next();
} else {
api.get('/user/' + ctx.params.name).then(response => {
ctx.state.user = response.user;
ctx.save();
this.user = response.user;
next();
}).catch(response => {
this.userView.empty();
2016-04-07 19:03:49 +02:00
events.notify(events.Error, response.description);
2016-04-06 22:34:21 +02:00
});
}
}
_show(user, section) {
const isPrivate = api.isLoggedIn() && user.name == api.userName;
if (isPrivate) {
topNavController.activate('account');
} else {
topNavController.activate('users');
}
2016-04-06 22:34:21 +02:00
this.userView.render({
user: user, section: section, isPrivate: isPrivate});
}
2016-04-06 22:34:21 +02:00
showUserRoute(ctx, next) {
this._show(ctx.state.user, 'summary');
}
editUserRoute(ctx, next) {
this._show(ctx.state.user, 'edit');
}
}
module.exports = new UsersController();