AuthAction.php 7.12 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\authclient;

use yii\base\Action;
use yii\base\Exception;
use yii\base\NotSupportedException;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use Yii;

/**
 * Class AuthAction
 *
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
class AuthAction extends Action
{
	/**
26
	 * @var string name of the auth client collection application component.
27
	 */
28
	public $clientCollection = 'auth';
29
	/**
30
	 * @var string name of the GET param, which is used to passed auth client id to this action.
31
	 */
32
	public $clientIdGetParamName = 'authclient';
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
	/**
	 * @var callable PHP callback, which should be triggered in case of successful authentication.
	 */
	public $successCallback;
	/**
	 * @var string the redirect url after successful authorization.
	 */
	private $_successUrl = '';
	/**
	 * @var string the redirect url after unsuccessful authorization (e.g. user canceled).
	 */
	private $_cancelUrl = '';

	/**
	 * @param string $url successful URL.
	 */
	public function setSuccessUrl($url)
	{
		$this->_successUrl = $url;
	}

	/**
	 * @return string successful URL.
	 */
	public function getSuccessUrl()
	{
		if (empty($this->_successUrl)) {
			$this->_successUrl = $this->defaultSuccessUrl();
		}
		return $this->_successUrl;
	}

	/**
	 * @param string $url cancel URL.
	 */
	public function setCancelUrl($url)
	{
		$this->_cancelUrl = $url;
	}

	/**
	 * @return string cancel URL.
	 */
	public function getCancelUrl()
	{
		if (empty($this->_cancelUrl)) {
			$this->_cancelUrl = $this->defaultCancelUrl();
		}
		return $this->_cancelUrl;
	}

	/**
	 * Creates default {@link successUrl} value.
	 * @return string success URL value.
	 */
	protected function defaultSuccessUrl()
	{
		return Yii::$app->getUser()->getReturnUrl();
	}

	/**
	 * Creates default {@link cancelUrl} value.
	 * @return string cancel URL value.
	 */
	protected function defaultCancelUrl()
	{
		return Yii::$app->getRequest()->getAbsoluteUrl();
	}

	/**
	 * Runs the action.
	 */
	public function run()
	{
107 108 109 110 111 112
		if (!empty($_GET[$this->clientIdGetParamName])) {
			$clientId = $_GET[$this->clientIdGetParamName];
			/** @var \yii\authclient\Collection $collection */
			$collection = Yii::$app->getComponent($this->clientCollection);
			if (!$collection->hasClient($clientId)) {
				throw new NotFoundHttpException("Unknown auth client '{$clientId}'");
113
			}
114 115
			$client = $collection->getClient($clientId);
			return $this->auth($client);
116 117 118 119 120 121
		} else {
			throw new NotFoundHttpException();
		}
	}

	/**
122 123 124
	 * @param mixed $client auth client instance.
	 * @return \yii\web\Response response instance.
	 * @throws \yii\base\NotSupportedException on invalid client.
125
	 */
126
	protected function auth($client)
127
	{
128 129 130 131 132 133
		if ($client instanceof OpenId) {
			return $this->authOpenId($client);
		} elseif ($client instanceof OAuth2) {
			return $this->authOAuth2($client);
		} elseif ($client instanceof OAuth1) {
			return $this->authOAuth1($client);
134
		} else {
135
			throw new NotSupportedException('Provider "' . get_class($client) . '" is not supported.');
136 137 138 139 140 141 142
		}
	}

	/**
	 * @param mixed $provider
	 * @return \yii\web\Response
	 */
143
	protected function authSuccess($provider)
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
	{
		call_user_func($this->successCallback, $provider);
		return $this->redirectSuccess();
	}

	/**
	 * Redirect to the given URL or simply close the popup window.
	 * @param mixed $url URL to redirect, could be a string or array config to generate a valid URL.
	 * @param boolean $enforceRedirect indicates if redirect should be performed even in case of popup window.
	 * @return \yii\web\Response response instance.
	 */
	public function redirect($url, $enforceRedirect = true)
	{
		$viewData = [
			'url' => $url,
			'enforceRedirect' => $enforceRedirect,
		];
161
		$viewFile = __DIR__ . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'redirect.php';
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

		$response = Yii::$app->getResponse();
		$response->content = Yii::$app->getView()->renderFile($viewFile, $viewData);
		return $response;
	}

	/**
	 * Redirect to the URL. If URL is null, {@link successUrl} will be used.
	 * @param string $url URL to redirect.
	 * @return \yii\web\Response response instance.
	 */
	public function redirectSuccess($url = null)
	{
		if ($url === null) {
			$url = $this->getSuccessUrl();
		}
		return $this->redirect($url);
	}

	/**
	 * Redirect to the {@link cancelUrl} or simply close the popup window.
	 * @param string $url URL to redirect.
	 * @return \yii\web\Response response instance.
	 */
	public function redirectCancel($url = null)
	{
		if ($url === null) {
			$url = $this->getCancelUrl();
		}
		return $this->redirect($url, false);
	}

	/**
195
	 * @param OpenId $client provider instance.
196 197 198 199
	 * @return \yii\web\Response action response.
	 * @throws Exception on failure
	 * @throws \yii\web\HttpException
	 */
200
	protected function authOpenId($client)
201 202 203 204
	{
		if (!empty($_REQUEST['openid_mode'])) {
			switch ($_REQUEST['openid_mode']) {
				case 'id_res':
205 206
					if ($client->validate()) {
						return $this->authSuccess($client);
207
					} else {
208
						throw new HttpException(400, 'Unable to complete the authentication because the required data was not received.');
209 210 211 212 213 214 215 216 217 218
					}
					break;
				case 'cancel':
					$this->redirectCancel();
					break;
				default:
					throw new HttpException(400);
					break;
			}
		} else {
219
			$url = $client->buildAuthUrl();
220 221 222 223 224 225 226 227 228
			return Yii::$app->getResponse()->redirect($url);
		}
		return $this->redirectCancel();
	}

	/**
	 * @param OAuth1 $provider
	 * @return \yii\web\Response
	 */
229
	protected function authOAuth1($provider)
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
	{
		// user denied error
		if (isset($_GET['denied'])) {
			return $this->redirectCancel();
		}

		if (isset($_REQUEST['oauth_token'])) {
			$oauthToken = $_REQUEST['oauth_token'];
		}

		if (!isset($oauthToken)) {
			// Get request token.
			$requestToken = $provider->fetchRequestToken();
			// Get authorization URL.
			$url = $provider->buildAuthUrl($requestToken);
			// Redirect to authorization URL.
			return Yii::$app->getResponse()->redirect($url);
		} else {
			// Upgrade to access token.
			$accessToken = $provider->fetchAccessToken();
250
			return $this->authSuccess($provider);
251 252 253 254 255 256 257 258
		}
	}

	/**
	 * @param OAuth2 $provider
	 * @return \yii\web\Response
	 * @throws \yii\base\Exception
	 */
259
	protected function authOAuth2($provider)
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
	{
		if (isset($_GET['error'])) {
			if ($_GET['error'] == 'access_denied') {
				// user denied error
				return $this->redirectCancel();
			} else {
				// request error
				if (isset($_GET['error_description'])) {
					$errorMessage = $_GET['error_description'];
				} elseif (isset($_GET['error_message'])) {
					$errorMessage = $_GET['error_message'];
				} else {
					$errorMessage = http_build_query($_GET);
				}
				throw new Exception('Auth error: ' . $errorMessage);
			}
		}

		// Get the access_token and save them to the session.
		if (isset($_GET['code'])) {
			$code = $_GET['code'];
			$token = $provider->fetchAccessToken($code);
			if (!empty($token)) {
283
				return $this->authSuccess($provider);
284 285 286 287 288 289 290 291 292
			} else {
				return $this->redirectCancel();
			}
		} else {
			$url = $provider->buildAuthUrl();
			return Yii::$app->getResponse()->redirect($url);
		}
	}
}