UNPKG

@omneedia/client-js

Version:

Isomorphic Javascript client for Omneedia

90 lines 3.78 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const constants_1 = require("./constants"); const cookies_1 = require("./cookies"); class OmneediaAuthAPI { constructor(auth) { this.cookieOptions = Object.assign({}, constants_1.COOKIE_OPTIONS); this.auth = auth; } /** * Set/delete the auth cookie based on the AuthChangeEvent. * Works for Next.js & Express (requires cookie-parser middleware). */ setAuth(req, res, body) { if (req.method !== 'POST') { res.setHeader('Allow', 'POST'); res.status(405).end('Method Not Allowed'); } var { event, session } = req.body; if (!event) event = body.event; if (!session) session = body.session; if (!event) throw new Error('Auth event missing!'); if (event === 'REFRESH_TOKEN') { (0, cookies_1.setCookie)(req, res, { name: this.cookieOptions.name, value: session, domain: this.cookieOptions.domain, maxAge: this.cookieOptions.lifetime, path: this.cookieOptions.path, sameSite: this.cookieOptions.sameSite, }); } if (event === 'SIGNED_IN') { if (!session) throw new Error('Auth session missing!'); (0, cookies_1.setCookie)(req, res, { name: this.cookieOptions.name, value: session.access_token, domain: this.cookieOptions.domain, maxAge: this.cookieOptions.lifetime, path: this.cookieOptions.path, sameSite: this.cookieOptions.sameSite, }); } if (event === 'SIGNED_OUT') (0, cookies_1.deleteCookie)(req, res, this.cookieOptions.name); res.status(200).json({}); } /** * Get user by reading the cookie from the request. * Works for Next.js & Express (requires cookie-parser middleware). */ getUser(req) { return __awaiter(this, void 0, void 0, function* () { try { if (req.cookie) { if (!req.cookies) req.cookies = {}; req.cookies[req.cookie.name] = req.cookie.value; } else { if (!req.cookies) throw new Error('Not able to parse cookies! When using Express make sure the cookie-parser middleware is in use!'); if (!req.cookies[this.cookieOptions.name]) throw new Error('No cookie found!'); } const token = req.cookies[this.cookieOptions.name]; const o = yield this.auth.getUser(token); return { user: o, data: null, error: null }; } catch (error) { return { user: null, data: null, error }; } }); } } exports.default = OmneediaAuthAPI; //# sourceMappingURL=auth_api.js.map