UNPKG

component-dbs-core

Version:

DTO objects shared among device backend

225 lines 9.3 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Auth0Service = void 0; const common_1 = require("@nestjs/common"); const envService_1 = require("../common_services/config/envService"); const identityDto_1 = require("../identity/dtos/identityDto"); const smsService_1 = require("./smsService"); const jwtValidator_1 = __importDefault(require("./utils/jwt/jwtValidator")); let Auth0Service = class Auth0Service { constructor(envService, http, smsService, jwtValidator) { this.envService = envService; this.http = http; this.smsService = smsService; this.jwtValidator = jwtValidator; this.contentType = 'application/json'; this.auth0ConnectionType = 'Username-Password-Authentication'; } /* Get Management API token */ getAdminToken() { const options = { client_id: this.envService.auth0ClientKey, client_secret: this.envService.auth0ClientSecret, audience: this.envService.auth0ManagementAudience, grant_type: 'client_credentials', }; return this.http .post(this.envService.auth0UrlGetToken, options) .toPromise(); } /* checkAccessToken functions */ checkAccessToken(input) { return this.jwtValidator.validate(input.accessToken); } /* identitySignUp */ createUser(input) { return __awaiter(this, void 0, void 0, function* () { try { const adminTokenResponse = yield this.getAdminToken(); const adminToken = adminTokenResponse.data.access_token; const headers = { 'Content-Type': this.contentType, authorization: `Bearer ${adminToken}`, }; const options = { email: input.email, password: input.password, connection: this.auth0ConnectionType, user_metadata: { deviceUuid: input.deviceUuid, }, }; const url = this.envService.auth0UrlCreateUser; yield this.http.post(url, options, { headers }).toPromise(); return Promise.resolve(true); } catch (e) { console.error(e); const errorMessage = e.response ? `${e.message}. Reason:${e.response.data.message}` : e.message; const error = new Error(errorMessage); return Promise.reject(error); } }); } /* identityLogin functions */ getUserToken(input) { // Get accessToken with a password or a refresh_token const grantType = input.refreshToken ? 'refresh_token' : 'password'; const headers = { 'Content-Type': this.contentType, }; const options = { grant_type: grantType, username: '', password: '', refresh_token: '', scope: 'offline_access openid profile email', audience: this.envService.auth0Audience, client_id: this.envService.auth0ClientKey, client_secret: this.envService.auth0ClientSecret, }; if (grantType === 'password') { options.username = input.email; options.password = input.password; } else { options.refresh_token = input.refreshToken; } return this.http.post(this.envService.auth0UrlGetToken, options, { headers, }); } getIdentity(input) { return __awaiter(this, void 0, void 0, function* () { try { const userTokens = yield this.getUserToken(input).toPromise(); const responseData = userTokens.data; return new identityDto_1.IdentityDto(true, responseData.access_token, responseData.refresh_token, responseData.id_token); } catch (e) { console.error(e); const errorMessage = e.response ? `${e.message}. Reason:${e.response.data.error_description}` : e.message; const error = new Error(errorMessage); return Promise.reject(error); } }); } /* identityChangePassword functions */ setNewPassword(input, adminToken) { const headers = { 'Content-Type': this.contentType, authorization: `Bearer ${adminToken}`, }; const options = { password: input.password, connection: this.auth0ConnectionType, }; const url = `${this.envService.auth0UrlChangePwd}${input.userId}`; return this.http.patch(url, options, { headers }).toPromise(); } changePassword(input) { return __awaiter(this, void 0, void 0, function* () { try { const adminTokenResponse = yield this.getAdminToken(); const adminToken = adminTokenResponse.data.access_token; yield this.setNewPassword(input, adminToken); return true; } catch (e) { console.error(e); return false; } }); } /* identityForgotPassword functions */ triggerForgotPasswordFlow(email) { const options = { email, connection: this.auth0ConnectionType, client_id: this.envService.auth0ClientKey, }; const headers = { 'Content-Type': this.contentType, }; return this.http.post(this.envService.auth0UrlForgotPwd, options, { headers, }); } forgotPassword(email) { return __awaiter(this, void 0, void 0, function* () { try { yield this.triggerForgotPasswordFlow(email).toPromise(); return true; } catch (e) { console.error(e); return false; } }); } phoneRegister(phone) { return __awaiter(this, void 0, void 0, function* () { // TODO: implement me -- generate code, get senderId and message pattern from env ? const verificationCode = 'Your verification code: 10240'; const senderId = 'Zeller'; // must be 1-11 alpha-numeric characters // try { yield this.smsService.sendSMS(phone, JSON.stringify(verificationCode), senderId); return Promise.resolve(new identityDto_1.PhoneRegistrationDto(true, new Date().toISOString())); } catch (e) { console.error(e); return Promise.reject(e); } }); } revokeRefreshToken(refreshToken) { return __awaiter(this, void 0, void 0, function* () { const headers = { 'Content-Type': this.contentType, }; const options = { token: refreshToken, client_id: this.envService.auth0ClientKey, client_secret: this.envService.auth0ClientSecret, }; return this.http.post(this.envService.auth0UrlRevokeToken, options, { headers, }); }); } }; Auth0Service = __decorate([ common_1.Injectable(), __metadata("design:paramtypes", [envService_1.EnvironmentService, common_1.HttpService, smsService_1.SmsService, jwtValidator_1.default]) ], Auth0Service); exports.Auth0Service = Auth0Service; //# sourceMappingURL=auth0Service.js.map