handlePreFlight function

Request handlePreFlight (
  1. Request req,
  2. Cors cors
)

Implementation

Request handlePreFlight(Request req, Cors cors) {
  if (req.method != 'OPTIONS') {
    var res = req.response;
    res.messenger.addError(('[cors] Preflight aborted. ${req.method}!="OPTIONS'));
    res.send.serverError();
    return req;
  }

  req.innerRequest.response.headers.add(HttpHeaders.varyHeader, 'Origin');
  req.innerRequest.response.headers
      .add(HttpHeaders.varyHeader, 'Access-Control-Request-Method');
  req.innerRequest.response.headers
      .add(HttpHeaders.varyHeader, 'Access-Control-Request-Headers');

  final origin = req.headers.value('Origin');
  if (origin == null || origin == '') {
    var res = req.response;
    res.messenger.addError('[cors] Preflight aborted. Empty origin.');
    res.send.badRequest();
    return req;
  }

  if (!cors.isAllowedOrigin(origin)) {
    var res = req.response;
    res.messenger.addError('[cors] Preflight aborted. Not an allowed origin.');
    res.send.badRequest();
    return req;
  }

  final method = req.headers.value('Access-Control-Request-Method');
  if (method == null || !cors.isAllowedMethod(method)) {
    var res = req.response;
    res.messenger.addError('[cors] Preflight aborted. Not an allowed method.');
    res.send.badRequest();
    return req;
  }

  final headers = req.headers.value('Access-Control-Request-Headers');
  List<String> parsedHeaders = List<String>();
  if (headers != null && headers != '') {
    List<String> split = headers.split(',');
    for (int i = 0; i < split.length; i++) {
      parsedHeaders.add(recase.ReCase(split[i].trim()).headerCase);
    }
  }

  if (parsedHeaders.length == 0 || !cors.areAllowedHeaders(parsedHeaders)) {
    var res = req.response;
    res.messenger.addError('[cors] Preflight aborted. Not an allowed header.');
    res.send.badRequest();
    return req;
  }

  req.innerRequest.response.headers.add('Access-Control-Allow-Origin', origin);
  req.innerRequest.response.headers
      .add('Access-Control-Allow-Methods', method.toUpperCase());
  if (parsedHeaders.length > 0) {
    req.innerRequest.response.headers
        .add('Access-Control-Allow-Headers', parsedHeaders.join(', '));
  }

  if (cors.allowCredentials != null && cors.allowCredentials) {
    req.innerRequest.response.headers
        .add('Access-Control-Allow-Credentials', 'true');
  }

  if (cors.maxAge != null && cors.maxAge > 0) {
    req.innerRequest.response.headers
        .add('Access-Control-Max-Age', cors.maxAge.toString());
  }

  req.innerRequest.response.statusCode = 200;
  req.cancel();
  return req;
}