<commit_before>/**
 * Original work: SecureSocial (https://github.com/jaliss/securesocial)
 * Copyright 2013 <NAME> (jaliss at g<EMAIL> dot com) - twitter: @jaliss
 *
 * Derivative work: Silhouette (https://github.com/mohiva/play-silhouette)
 * Modifications Copyright 2014 Mohiva Organisation (license at mohiva dot com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mohiva.play.silhouette.core.providers

import java.net.URLEncoder
import java.util.UUID
import play.api.Logger
import play.api.mvc.{RequestHeader, Results, Result}
import play.api.libs.ws.Response
import play.api.libs.json._
import play.api.libs.functional.syntax._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import com.mohiva.play.silhouette.core.utils.{HTTPLayer, CacheLayer}
import com.mohiva.play.silhouette.core._
import OAuth2Provider._

/**
 * Base class for all OAuth2 providers.
 *
 * @param settings The provider settings.
 * @param cacheLayer The cache layer implementation.
 * @param httpLayer The HTTP layer implementation.
 */
abstract class OAuth2Provider(
    settings: OAuth2Settings,
    cacheLayer: CacheLayer,
    httpLayer: HTTPLayer)
  extends SocialProvider[OAuth2Info] {

  /**
   * Converts the JSON into a [[com.mohiva.play.silhouette.core.providers.OAuth2Info]] object.
   */
  implicit val infoReads = (
    (__ \ AccessToken).read[String] and
    (__ \ TokenType).readNullable[String]and
    (__ \ ExpiresIn).readNullable[Int] and
    (__ \ RefreshToken).readNullable[String]
  )(OAuth2Info.apply _)

  /**
   * Starts the authentication process.
   *
   * @param request The request header.
   * @return Either a Result or the auth info from the provider.
   */
  def doAuth()(implicit request: RequestHeader): Future[Either[Result, OAuth2Info]] = {
    request.queryString.get(Error).flatMap(_.headOption).map {
      case e @ AccessDenied => throw new AccessDeniedException(AuthorizationError.format(id, e))
      case error => throw new AuthenticationException(AuthorizationError.format(id, error))
    }

    request.queryString.get(Code).flatMap(_.headOption) match {
      // We're being redirected back from the authorization server with the access code
      case Some(code) => cachedState.map { case (cacheID, cachedState) => cachedState == requestState }.flatMap {
        case false => throw new AuthenticationException(StateIsNotEqual.format(id))
        case true => getAccessToken(code).map(oauth2Info => Right(oauth2Info))
      }
      // There's no code in the request, this is the first step in the OAuth flow
      case None =>
        val state = UUID.randomUUID().toString
        val cacheID = request.session.get(CacheKey).getOrElse(UUID.randomUUID().toString)
        var params = List(
          (ClientID, settings.clientID),
          (RedirectURI, settings.redirectURL),
          (ResponseType, Code),
          (State, state))
        settings.scope.foreach(s => { params = (Scope, s) :: params })
        val url = settings.authorizationURL + params.map(p => p._1 + "=" + URLEncoder.encode(p._2, "UTF-8")).mkString("?", "&", "")
        val redirect = Results.Redirect(url).withSession(request.session + (CacheKey, cacheID))
        if (Logger.isDebugEnabled) {<commit_msg>Fix: Adapting argument list by creating a 2-tuple warning<commit_after>/**
 * Original work: SecureSocial (https://github.com/jaliss/securesocial)
 * Copyright 2013 <NAME> (jaliss at gmail dot com) - twitter: @jaliss
 *
 * Derivative work: Silhouette (https://github.com/mohiva/play-silhouette)
 * Modifications Copyright 2014 Mohiva Organisation (license at mohiva dot com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mohiva.play.silhouette.core.providers

import java.net.URLEncoder
import java.util.UUID
import play.api.Logger
import play.api.mvc.{RequestHeader, Results, Result}
import play.api.libs.ws.Response
import play.api.libs.json._
import play.api.libs.functional.syntax._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import com.mohiva.play.silhouette.core.utils.{HTTPLayer, CacheLayer}
import com.mohiva.play.silhouette.core._
import OAuth2Provider._

/**
 * Base class for all OAuth2 providers.
 *
 * @param settings The provider settings.
 * @param cacheLayer The cache layer implementation.
 * @param httpLayer The HTTP layer implementation.
 */
abstract class OAuth2Provider(
    settings: OAuth2Settings,
    cacheLayer: CacheLayer,
    httpLayer: HTTPLayer)
  extends SocialProvider[OAuth2Info] {

  /**
   * Converts the JSON into a [[com.mohiva.play.silhouette.core.providers.OAuth2Info]] object.
   */
  implicit val infoReads = (
    (__ \ AccessToken).read[String] and
    (__ \ TokenType).readNullable[String]and
    (__ \ ExpiresIn).readNullable[Int] and
    (__ \ RefreshToken).readNullable[String]
  )(OAuth2Info.apply _)

  /**
   * Starts the authentication process.
   *
   * @param request The request header.
   * @return Either a Result or the auth info from the provider.
   */
  def doAuth()(implicit request: RequestHeader): Future[Either[Result, OAuth2Info]] = {
    request.queryString.get(Error).flatMap(_.headOption).map {
      case e @ AccessDenied => throw new AccessDeniedException(AuthorizationError.format(id, e))
      case error => throw new AuthenticationException(AuthorizationError.format(id, error))
    }

    request.queryString.get(Code).flatMap(_.headOption) match {
      // We're being redirected back from the authorization server with the access code
      case Some(code) => cachedState.map { case (cacheID, cachedState) => cachedState == requestState }.flatMap {
        case false => throw new AuthenticationException(StateIsNotEqual.format(id))
        case true => getAccessToken(code).map(oauth2Info => Right(oauth2Info))
      }
      // There's no code in the request, this is the first step in the OAuth flow
      case None =>
        val state = UUID.randomUUID().toString
        val cacheID = request.session.get(CacheKey).getOrElse(UUID.randomUUID().toString)
        var params = List(
          (ClientID, settings.clientID),
          (RedirectURI, settings.redirectURL),
          (ResponseType, Code),
          (State, state))
        settings.scope.foreach(s => { params = (Scope, s) :: params })
        val url = settings.authorizationURL + params.map(p => p._1 + "=" + URLEncoder.encode(p._2, "UTF-8")).mkString("?", "&", "")
        val redirect = Results.Redirect(url).withSession(request.session + (CacheKey -> cacheID))
        if (Logger.isDebugEnabled) {
{'fraction_non_alphanumeric': 0.10941408821593153, 'fraction_numerical': 0.0067149440421329825, 'mean_word_length': 3.7238805970149254, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 27, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, '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': '828889', 'n_tokens_mistral': 2226, 'n_tokens_neox': 2189, 'n_words': 632}