integreat
Version:
Node.js integration layer
74 lines • 2.54 kB
JavaScript
import { isObject } from '../utils/is.js';
function getTypeAndToken(authentication) {
const { status, token, type, encode } = authentication || {};
if (status !== 'granted' || !token) {
return {};
}
return {
token: encode ? Buffer.from(token).toString('base64') : token,
type,
};
}
function getAuthHeader(action) {
const headers = action?.payload?.headers;
if (isObject(headers)) {
return headers.authorization || headers.Authorization;
}
return undefined;
}
const compareAuthHeader = (header, type, token) => header === (type ? `${type} ${token}` : token);
function isValidAuthHeader(header, type, token) {
if (typeof header === 'string') {
return Array.isArray(token)
? token.some((tok) => compareAuthHeader(header, type, tok))
: compareAuthHeader(header, type, token);
}
return false;
}
const tokenAuth = {
async authenticate(options) {
const { type, encode = false } = options || {};
const token = Array.isArray(options?.token)
? options.token[0]
: options?.token;
return token
? { status: 'granted', token, type, encode }
: { status: 'refused' };
},
isAuthenticated(authentication, _options, _action) {
return !!(authentication &&
authentication.status === 'granted' &&
authentication.token);
},
async validate(_authentication, options, action) {
const { identId, type, token } = options || {};
const authHeader = getAuthHeader(action);
if (isValidAuthHeader(authHeader, type, token)) {
return { status: 'ok', access: { ident: { id: identId } } };
}
else {
return authHeader
? {
status: 'autherror',
error: 'Invalid credentials',
reason: 'invalidauth',
}
: {
status: 'noaccess',
error: 'Authentication required',
reason: 'noauth',
};
}
},
authentication: {
asObject(authentication) {
return getTypeAndToken(authentication);
},
asHttpHeaders(authentication) {
const { type, token } = getTypeAndToken(authentication);
return token ? { Authorization: type ? `${type} ${token}` : token } : {};
},
},
};
export default tokenAuth;
//# sourceMappingURL=token.js.map