szurubooru/client/js/api.js

99 lines
3 KiB
JavaScript
Raw Normal View History

'use strict';
const request = require('superagent');
const config = require('./config.js');
const EventListener = require('./event_listener.js');
class Api {
2016-03-30 20:45:37 +02:00
constructor() {
this.user = null;
2016-03-30 20:45:37 +02:00
this.userName = null;
this.userPassword = null;
this.authenticated = new EventListener();
2016-03-30 20:45:37 +02:00
}
get(url) {
const fullUrl = this.getFullUrl(url);
2016-03-30 21:01:18 +02:00
return this._process(fullUrl, () => request.get(fullUrl));
}
post(url, data) {
const fullUrl = this.getFullUrl(url);
2016-03-30 21:01:18 +02:00
return this._process(fullUrl, () => request.post(fullUrl).send(data));
}
2016-03-30 21:01:18 +02:00
_process(url, requestFactory) {
return new Promise((resolve, reject) => {
let req = requestFactory();
if (this.userName && this.userPassword) {
req.auth(this.userName, this.userPassword);
}
req.set('Accept', 'application/json')
.end((error, response) => {
if (error) {
2016-04-02 18:57:17 +02:00
reject(response && response.body ? response.body : {
'title': 'Networking error',
'description': error.message});
} else {
resolve(response.body);
}
});
});
}
hasPrivilege(lookup) {
let minViableRank = null;
for (let privilege of Object.keys(config.privileges)) {
if (!privilege.startsWith(lookup)) {
continue;
}
const rankName = config.privileges[privilege];
const rankIndex = config.service.userRanks.indexOf(rankName);
if (minViableRank === null || rankIndex < minViableRank) {
minViableRank = rankIndex;
}
}
if (minViableRank === null) {
console.error('Bad privilege name: ' + lookup);
}
let myRank = this.user !== null ?
config.service.userRanks.indexOf(this.user.accessRank) :
0;
return myRank >= minViableRank;
2016-03-30 20:45:37 +02:00
}
login(userName, userPassword) {
2016-03-30 21:01:18 +02:00
return new Promise((resolve, reject) => {
this.userName = userName;
this.userPassword = userPassword;
this.get('/user/' + userName)
.then(response => {
this.user = response.user;
resolve();
this.authenticated.fire();
}).catch(response => {
2016-03-30 21:01:18 +02:00
reject(response.description);
this.logout();
this.authenticated.fire();
2016-03-30 21:01:18 +02:00
});
});
2016-03-30 20:45:37 +02:00
}
logout() {
this.user = null;
2016-03-30 20:45:37 +02:00
this.userName = null;
this.userPassword = null;
this.authenticated.fire();
2016-03-30 20:45:37 +02:00
}
isLoggedIn() {
return this.userName !== null;
}
getFullUrl(url) {
return (config.basic.apiUrl + '/' + url).replace(/([^:])\/+/g, '$1/');
}
}
module.exports = new Api();