<commit_before>/*
 * Copyright 2014 Red Hat, Inc.
 *
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  and Apache License v2.0 which accompanies this distribution.
 *
 *  The Eclipse Public License is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  The Apache License v2.0 is available at
 *  http://www.opensource.org/licenses/apache2.0.php
 *
 *  You may elect to redistribute this code under either of these licenses.
 */

package io.vertx.ext.web.handler.impl;

import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.authentication.AuthenticationProvider;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
import io.vertx.ext.web.handler.AuthenticationHandler;

/**
 * @author <a href="http://tfox.org"><NAME></a>
 */
public abstract class AuthenticationHandlerImpl<T extends AuthenticationProvider> implements AuthenticationHandler {

  static final String AUTH_PROVIDER_CONTEXT_KEY = "io.vertx.ext.web.handler.AuthenticationHandler.provider";

  static final HttpStatusException UNAUTHORIZED = new HttpStatusException(401);
  static final HttpStatusException BAD_REQUEST = new HttpStatusException(400);
  static final HttpStatusException BAD_METHOD = new HttpStatusException(405);

  protected final String realm;
  protected final T authProvider;

  public AuthenticationHandlerImpl(T authProvider) {
    this(authProvider, null);
  }

  public AuthenticationHandlerImpl(T authProvider, String realm) {
    this.authProvider = authProvider;
    this.realm = realm == null ? null : realm
      // escape quotes
      .replaceAll("\"", "\\\"");

    if (this.realm != null &&
      (this.realm.indexOf('\r') != -1 || this.realm.indexOf('\n') != -1)) {
      throw new IllegalArgumentException("Not allowed [\\r|\\n] characters detected on realm name");
    }
  }

  @Override
  public void handle(RoutingContext ctx) {

    if (handlePreflight(ctx)) {
      return;
    }

    User user = ctx.user();
    if (user != null) {
      // proceed with the router
      postAuthentication(ctx);
      return;
    }
    // before starting any potential async operation here
    // pause parsing the request body. The reason is that
    // we don't want to loose the body or protocol upgrades
    // for async operations
    final boolean parseEnded = ctx.request().isEnded();
    if (!parseEnded) {
      ctx.request().pause();
    }
    // parse the request in order to extract the credentials object
    parseCredentials(ctx, res -> {
      if (res.failed()) {
        // resume as the error handler may allow this request to become valid again
        if (!parseEnded) {
          ctx.request().resume();
        }
        processException(ctx, res.cause());
        return;
      }
      // proceed to authN
      getAuthProvider(ctx).authenticate(res.result(), authN -> {
        if (authN.succeeded()) {
          User authenticated = authN.result();
          ctx.setUser(authenticated);
          Session session = ctx.session();
          if (session != null) {
            // the user has upgraded from unauthenticated to authenticated
            // session should be upgraded as recommended by owasp
            session.regenerateId();
          }
          // proceed with the router
          if (!parseEnded) {
            ctx.request().resume();
          }
          postAuthentication(ctx);
        } else {
          String header = authenticateHeader(ctx);
          if (header != null) {
            ctx.response()
              .putHeader("WWW-Authenticate", header);
          }
          // to allow further processing if needed
          if (authN.cause() instanceof HttpStatusException) {
            // resume as the error handler may allow this request to become valid again
            if (!parseEnded) {
              ctx.request().resume();
            }
            processException(ctx, authN.cause());
          } else {
            // resume as the error handler may allow this request to become valid again
            if (!parseEnded) {
              ctx.request().resume();
            }
            processException(ctx, new HttpStatusException(401, authN.cause()));
          }
        }
      });
    });<commit_msg>Resume only if not a websocket upgrade<commit_after>/*
 * Copyright 2014 Red Hat, Inc.
 *
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  and Apache License v2.0 which accompanies this distribution.
 *
 *  The Eclipse Public License is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  The Apache License v2.0 is available at
 *  http://www.opensource.org/licenses/apache2.0.php
 *
 *  You may elect to redistribute this code under either of these licenses.
 */

package io.vertx.ext.web.handler.impl;

import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.authentication.AuthenticationProvider;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
import io.vertx.ext.web.handler.AuthenticationHandler;

/**
 * @author <a href="http://tfox.org"><NAME></a>
 */
public abstract class AuthenticationHandlerImpl<T extends AuthenticationProvider> implements AuthenticationHandler {

  static final String AUTH_PROVIDER_CONTEXT_KEY = "io.vertx.ext.web.handler.AuthenticationHandler.provider";

  static final HttpStatusException UNAUTHORIZED = new HttpStatusException(401);
  static final HttpStatusException BAD_REQUEST = new HttpStatusException(400);
  static final HttpStatusException BAD_METHOD = new HttpStatusException(405);

  protected final String realm;
  protected final T authProvider;

  public AuthenticationHandlerImpl(T authProvider) {
    this(authProvider, null);
  }

  public AuthenticationHandlerImpl(T authProvider, String realm) {
    this.authProvider = authProvider;
    this.realm = realm == null ? null : realm
      // escape quotes
      .replaceAll("\"", "\\\"");

    if (this.realm != null &&
      (this.realm.indexOf('\r') != -1 || this.realm.indexOf('\n') != -1)) {
      throw new IllegalArgumentException("Not allowed [\\r|\\n] characters detected on realm name");
    }
  }

  @Override
  public void handle(RoutingContext ctx) {

    if (handlePreflight(ctx)) {
      return;
    }

    User user = ctx.user();
    if (user != null) {
      // proceed with the router
      postAuthentication(ctx);
      return;
    }
    // before starting any potential async operation here
    // pause parsing the request body. The reason is that
    // we don't want to loose the body or protocol upgrades
    // for async operations
    HttpServerRequest request = ctx.request();
    final boolean parseEnded = request.isEnded();
    if (!parseEnded) {
      request.pause();
    }
    // parse the request in order to extract the credentials object
    parseCredentials(ctx, res -> {
      if (res.failed()) {
        resume(request, parseEnded);
        processException(ctx, res.cause());
        return;
      }
      // proceed to authN
      getAuthProvider(ctx).authenticate(res.result(), authN -> {
        if (authN.succeeded()) {
          User authenticated = authN.result();
          ctx.setUser(authenticated);
          Session session = ctx.session();
          if (session != null) {
            // the user has upgraded from unauthenticated to authenticated
            // session should be upgraded as recommended by owasp
            session.regenerateId();
          }
          // proceed with the router
          resume(request, parseEnded);
          postAuthentication(ctx);
        } else {
          String header = authenticateHeader(ctx);
          if (header != null) {
            ctx.response()
              .putHeader("WWW-Authenticate", header);
          }
          // to allow further processing if needed
          resume(request, parseEnded);
          Throwable cause = authN.cause();
          processException(ctx, cause instanceof HttpStatusException?cause:new HttpStatusException(401, cause));
        }
      });
    });
  }

  private void resume(HttpServerRequest request, boolean parseEnded) {
    // resume as the error handler may allow this request to become valid again
    if (!parseEnded && !request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) {
      request.resume();
    }
{'fraction_non_alphanumeric': 0.10559149722735675, 'fraction_numerical': 0.006469500924214418, 'mean_word_length': 2.693259385665529, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4944226', 'n_tokens_mistral': 2396, 'n_tokens_neox': 2324, 'n_words': 687}