@amirmarmul/waba-common
Version:

80 lines (79 loc) • 2.17 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenGuard = void 0;
const WrongCredentialsError_1 = __importDefault(require("../../../core/errors/WrongCredentialsError"));
class TokenGuard {
/**
* The request instance.
*/
_req;
/**
* The user provider implementation.
*/
_provider;
/**
* The currently authenticated user.
*/
_user;
/**
* Create a new authtentication guard.
*/
constructor(provider, req) {
this._provider = provider;
this._req = req;
}
/**
* Determine if the current user is authenticated. If not, throw an error.
*/
async authenticate() {
const user = await this.user();
if (user) {
return user;
}
throw new WrongCredentialsError_1.default();
}
async check() {
return !!(await this.user());
}
async guest() {
return !(await this.check);
}
async setUser(user) {
// this._user = user;
}
async setRequest(req) {
this._req = req;
}
async user() {
// if (this._user) {
// return this._user;
// }
let user = null;
let token = this.getTokenFromRequest();
if (token) {
user = await this._provider.getByToken(token);
}
return user;
// return this._user = user!;
}
getTokenFromRequest() {
let token = this._req.query['api_token'];
if (!token) {
token = this._req.body['api_token'];
}
if (!token && this._req.header('API-Token')) {
token = this._req.header('API-Token');
}
if (!token && this._req.header('Authorization')) {
const authorization = this._req.header('Authorization');
let [_, bearerToken] = authorization.split(' ');
token = bearerToken;
}
return token;
}
}
exports.TokenGuard = TokenGuard;
exports.default = TokenGuard;