UNPKG

@dodi-smart/nuki-graphql-api

Version:
77 lines 3.48 kB
"use strict"; 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.createNukiOAuthCallback = void 0; const api_1 = require("./api"); const node_fetch_1 = __importDefault(require("node-fetch")); const createNukiOAuthCallback = (req, res, createApiKey = !!process.env.NUKI_API_KEY_CREATE || false) => __awaiter(void 0, void 0, void 0, function* () { const { query } = req; const url = new URL(`${req.protocol}://${req.header('host')}${req.originalUrl}`); const pathname = url.pathname == '/' ? '' : url.pathname; if (!(query === null || query === void 0 ? void 0 : query.code)) { console.error("The request does not have 'code' query parameter. Skipping..."); res.sendStatus(400); return null; } const body = new URLSearchParams({ client_id: process.env.NUKI_CLIENT_ID, client_secret: process.env.NUKI_CLIENT_SECRET, grant_type: 'authorization_code', code: query.code, redirect_uri: `${url.origin}${pathname}` }); const response = yield (0, node_fetch_1.default)('https://api.nuki.io/oauth/token', { method: 'post', body, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); const token = (yield response.json()); if (createApiKey) { const nukiClient = new api_1.NukiClient({ TOKEN: token.access_token }); const apiKeys = yield nukiClient.apiKey.getApiKeys(); if (apiKeys.length) { const apiKey = apiKeys[0]; const apiKeyToken = yield nukiClient.apiKey.createApiKeyToken(apiKey.apiKeyId, { description: 'Autogenerated by Nuki GraphQL API for Hasura Remote Schema', scopes: [ 'account', 'notification', 'smartlock.create', 'smartlock', 'smartlock.readOnly', 'smartlock.action', 'smartlock.auth', 'smartlock.config', 'smartlock.log' ] }); res.status(200).json(); return { accessToken: token.access_token, refreshToken: token.refresh_token, apiKeyToken: apiKeyToken.accessToken }; } else { console.error('The Nuki Account does not have API Keys yet.'); } } res.status(200).json(); return { accessToken: token.access_token, refreshToken: token.refresh_token }; }); exports.createNukiOAuthCallback = createNukiOAuthCallback; //# sourceMappingURL=oauth.js.map