UNPKG

integreat

Version:
84 lines 2.95 kB
import ms from 'ms'; import { isAction, isObject } from '../utils/is.js'; import { IdentType, } from '../types.js'; const metaFromOptions = ({ id, cid, gid, ident, dispatchedAt, queue, queuedAt, auth, options, jobId, stepId, ...meta } = {}) => meta; const metaFromAction = ({ meta: { ident, cid, id, queue, ...meta } = {}, }) => ({ ...meta, ident, cid, }); const createActionFromOptions = (options, action) => options ? { type: options.action, payload: options.payload, meta: { ...metaFromOptions(options.meta), ...(action ? metaFromAction(action) : { ident: { id: 'anonymous', type: IdentType.Anon } }), }, } : null; function calculateExpire(expire, expireIn) { if (typeof expire === 'number') { return expire; } if (typeof expireIn === 'string') { const expireMs = ms(expireIn); return typeof expireMs === 'number' ? Date.now() + expireMs : undefined; } if (typeof expireIn === 'number') { return Date.now() + expireIn; } return undefined; } const isValidAuthData = (data) => isObject(data) && (isObject(data.auth) || data.auth === null || data.auth === undefined); const actionAuth = { async authenticate(options, action, dispatch) { const authAction = createActionFromOptions(options, action); if (!isAction(authAction)) { return { status: 'refused', error: 'The options did not define a valid action', }; } const response = await dispatch(authAction); if (response.status !== 'ok') { return { status: 'refused', error: `Auth action failed. [${response.status}] ${response.error}`, }; } if (!isValidAuthData(response.data)) { return { status: 'refused', error: 'Auth action responded without a valid data object', }; } const expire = calculateExpire(response.data.expire, options?.expireIn); return { status: 'granted', auth: response.data.auth ?? {}, ...(expire ? { expire } : {}), }; }, isAuthenticated(authentication, _options, _action) { return (authentication?.status === 'granted' && (typeof authentication.expire !== 'number' || authentication.expire > Date.now())); }, authentication: { asObject(authentication) { return actionAuth.isAuthenticated(authentication, null, null) && isObject(authentication?.auth) ? authentication.auth : {}; }, asHttpHeaders(authentication) { return actionAuth.authentication.asObject(authentication); }, }, }; export default actionAuth; //# sourceMappingURL=action.js.map