@rhinojs/auth
Version:
Estrutura de autenticacao de usuario
163 lines (142 loc) • 4.12 kB
JavaScript
class Auth {
/**
* Construtor da classe.
*/
constructor() {
this.constructor.obj = this;
this.constructor.request = null;
this.constructor.$user = null;
this.constructor.$token = null;
this.constructor.$userProvider = null;
}
/**
* Setar user provider para recuperar um usuario pelo token.
*
* @param {Object} provider
*/
static setUserProvider(provider) {
this.$userProvider = provider;
}
/**
* Retorna o usuario logado.
*
* @returns Retorna o usuario logado ou null
*/
static async user() {
// Recuperar token
this.$token = this._getAccessToken();
if (this.$token == null) {
return null;
}
// Verificar se user jah foi recuperado
if (this.$user != null) {
return this.$user;
}
// Verificar se userProvider foi definido
if (this.$userProvider == null) {
return null;
}
// Carregar usuario pelo token
this.$user = await this.$userProvider(this, this.$token);
return this.$user;
}
/**
* Verifica se tem um usuario logado.
*
* @returns Retorna se usuario esta logado
*/
static async check() {
return (await this.user() !== null);
}
/**
* Verificar se nao ha um usuario logado.
*
* @returns Retorna se usuario esta NÃO logado
*/
static async guest() {
return (await this.user() === null);
}
/**
* Limpar informacoes do usuario logado.
*/
static clear() {
this.$user = null;
this.$token = null;
}
/**
* Retorna o accessToken utilizado para fazer o login.
*
* @returns Retorna a string com o access token ou null
*/
static async getAccessToken() {
if (await this.check()) {
return this.$token;
}
return null;
}
/**
* Recuperar access token.
*
* @private
* @returns Retorna o access token informados via headers ou query, senão retorna null
*/
static _getAccessToken() {
// Veriifcar se request foi informado
if (!this.request) {
return null;
}
// Verificar se veio via header
var token = this.request.get('Authorization');
if (token != null) {
return token;
}
// Verificar se veio via query
token = this.request.query.access_token;
if (token != null) {
return token;
}
return null;
}
/**
* Middleware para garantir que algumas rotas só seja permitido se usuario logado.
*/
static isAuthenticated() {
return (req, res, next) => {
Auth.request = req;
Auth.check().then((ret) => {
if (!ret) {
res.error('Nao autorizado', 4001);
Auth.clear();
} else {
next();
}
}).catch((err) => {
res.error('Nao autorizado', 4001);
Auth.clear();
});
}
}
/**
* Middleware para garantir que algumas rotas só seja permitido se NENHUM usuario estaja logado.
*/
static isGuest() {
return (req, res, next) => {
Auth.request = req;
Auth.check().then((ret) => {
if (ret) {
res.error('Execucao nao autorizada para um usuario logado', 3999);
Auth.clear();
} else {
next();
Auth.clear();
}
}).catch((err) => {
res.error('Execucao nao autorizada para um usuario logado', 3999);
});
}
}
}
/**
* Exports.
*/
module.exports = Auth;