UNPKG

@w3lcome/feathers-refresh-token

Version:
76 lines 3.2 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.issueRefreshToken = void 0; const common_1 = require("./common"); const debug_1 = __importDefault(require("debug")); const debug = debug_1.default('feathers-refresh-token'); // After hook with authentication service // result - authResult which will return to user, contains access token, sub and strategy exports.issueRefreshToken = () => { return async (context) => { const { app, data, result, method } = context; const config = common_1.loadConfig(app); if (method !== 'create') { throw new Error('refreshAccessToken hook must be used with create method!'); } debug(`Issue Refresh token with auth result`, result); const { entity, service, userEntity, userEntityId, authService, jwtOptions, secret } = config; let userId; let user = result[userEntity]; if (user) { userId = user[userEntityId]; } else if (userEntityId in result) { userId = result[userEntityId]; } else { // userIdField must be presented in result debug(`${userEntityId} doesn't exist in auth result`, result); throw new Error(`Could not find userId`); } // ! get the deviceId from client const { deviceId } = data; let query = { userId }; if (deviceId) { query = { ...query, deviceId }; } const { existingToken } = await common_1.lookupRefreshToken(context, config, query); debug(`existing token`, existingToken); // ! if refresh token already exists, simply return if (existingToken) { Object.assign(result, { [entity]: existingToken['refreshToken'] }); return context; } // ! no refresh-token created yet, need to generate a new refresh-token for this login // Use authentication service to generate the refresh token with user ID const refreshToken = await app.service(authService).createAccessToken({ sub: `${userId}` // refresh token subject is set to user ID }, jwtOptions, // refresh token options secret // refresh token secret, should be different than access token ); let refreshTokenData = { refreshToken, userId: `${userId}`, isValid: true }; // ! get the deviceId from client if (data === null || data === void 0 ? void 0 : data.deviceId) { refreshTokenData = { ...refreshTokenData, deviceId: data.deviceId }; } // save the refresh token ID const token = await app.service(service).create(refreshTokenData); debug(`Token ID and refresh token`, token, refreshToken); // return refresh token in result Object.assign(result, { [entity]: refreshToken }); return context; }; }; //# sourceMappingURL=issue-refresh-token.js.map