import { Request, Response, NextFunction } from '../interfaces'; import { get, isArray, isEqual } from 'lodash'; import { response } from '../utils'; export default function(req: Request, res, next: NextFunction): void { if (get(this, 'options')) { const ips: string[] = get(this, 'options.cors.ips'); const origins: string[] = get(this, 'options.cors.origins'); const methods: string[] = get(this, 'options.cors.methods'); const headers: string[] = get(this, 'options.cors.headers'); const clientIP = req.connection.remoteAddress || req.headers['x-forwarded-for']; const clientMethod = req.method; let access: boolean = false; if (ips && isArray(ips)) { for (let i = 0, ip; ip = ips[i]; i++) { if (isEqual(ip, clientIP)) { access = true; } } } if (!access) return response(res, 403, null, { message: `No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '${get(req, 'headers.origin') || null}' is therefore not allowed access.` }); if (origins && isArray(origins)) { for (let i = 0, origin; origin = origins[i]; i++) { if (req.headers.origin && req.headers.origin.indexOf(origin) > -1) { res.header('Access-Control-Allow-Origin', origin); } } } access = false; if (methods && isArray(methods)) { let string: string = ''; for (let i = 0, method; method = methods[i]; i++) { if (isEqual(method, clientMethod)) access = true; if (i == (methods.length - 1)) { string += method; } else { string += `${method}, `; } } res.header("Access-Control-Allow-Methods", string); } if (!access) return response(res, 403, null, { message: `No 'Access-Control-Allow-Methods' header is present on the requested resource. Method '${clientMethod || null}' is therefore not allowed access.` }); if (headers && isArray(headers)) { let string: string = ''; for (let i = 0, header; header = headers[i]; i++) { if (i == (headers.length - 1)) { string += header; } else { string += `${header}, `; } } res.header("Access-Control-Allow-Headers", string); } res.header('Access-Control-Allow-Credentials', true); } next(); }