const uuid = require('uuid'); const models = require('../models'); const constants = require('../constants'); class SessionServiceProvider { constructor({ models, constants, invitesService }) { this.models = models; this.constants = constants; this.invitesService = invitesService; } provide() { const createSession = async (sessionUuid) => { const currentTimestamp = new Date(); const expiryTimestamp = new Date(currentTimestamp.getTime()); expiryTimestamp.setSeconds( expiryTimestamp.getSeconds() + constants.DEFAULT_SESSION_DURATION_SECONDS ); return await this.models.SessionCreated.create({ uuid: sessionUuid, created_at: currentTimestamp.toISOString(), expires_at: expiryTimestamp.toISOString(), }); }; async function isSessionValid(sessionUuid) { const currentSession = await models.SessionCreated.findOne({ where: { uuid: sessionUuid, }, }); if (!currentSession) { return false; } if (currentSession.expires_at <= new Date()) { return false; } return true; } const relateSessionToPublicKey = async (sessionUuid, publicKey) => { if (!(await isSessionValid(sessionUuid))) { throw Error('Session is not valid anymore.'); } if (!(await this.invitesService.isPublicKeySignedUp(publicKey))) { throw Error('Public key is not signed up.'); } return models.SessionRelatedToPublickey.create({ uuid: uuid.v7(), session_uuid: sessionUuid, public_key: publicKey, created_at: new Date().toISOString(), }); }; async function isSessionAuthorized(sessionUuid) { const isSessionRelatedToPublicKey = await models.SessionRelatedToPublickey.findOne({ where: { session_uuid: sessionUuid, }, }); if (isSessionRelatedToPublicKey) { return true; } return false; } async function getPublicKeyRelatedToSession(sessionUuid) { const sessionRelatedToPublickey = await models.SessionRelatedToPublickey.findOne({ where: { session_uuid: sessionUuid, }, }); if (sessionRelatedToPublickey) { return sessionRelatedToPublickey.public_key; } return null; } return { createSession, isSessionValid, relateSessionToPublicKey, isSessionAuthorized, getPublicKeyRelatedToSession, }; } } module.exports = SessionServiceProvider;