PHP code example of pjiranuwattkku / yii2-eauth

1. Go to this page and download the library: Download pjiranuwattkku/yii2-eauth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pjiranuwattkku / yii2-eauth example snippets



...
	'components'=>array(
		'eauth' => array(
			'class' => 'nodge\eauth\EAuth',
			'popup' => true, // Use the popup window instead of redirecting.
			'cache' => false, // Cache component name or false to disable cache. Defaults to 'cache' on production environments.
			'cacheExpire' => 0, // Cache lifetime. Defaults to 0 - means unlimited.
			'httpClient' => array(
				// uncomment this to use streams in safe_mode
				//'useStreamsFallback' => true,
			),
			'services' => array( // You can change the providers and their classes.
				'google' => array(
					'class' => 'nodge\eauth\services\GoogleOpenIDService',
					//'realm' => '*.example.org', // your domain, can be with wildcard to authenticate on subdomains.
				),
				'yandex' => array(
					'class' => 'nodge\eauth\services\YandexOpenIDService',
					//'realm' => '*.example.org', // your domain, can be with wildcard to authenticate on subdomains.
				),
				'twitter' => array(
					// register your app here: https://dev.twitter.com/apps/new
					'class' => 'nodge\eauth\services\TwitterOAuth1Service',
					'key' => '...',
					'secret' => '...',
				),
				'google_oauth' => array(
					// register your app here: https://code.google.com/apis/console/
					'class' => 'nodge\eauth\services\GoogleOAuth2Service',
					'clientId' => '...',
					'clientSecret' => '...',
					'title' => 'Google (OAuth)',
				),
				'yandex_oauth' => array(
					// register your app here: https://oauth.yandex.ru/client/my
					'class' => 'nodge\eauth\services\YandexOAuth2Service',
					'clientId' => '...',
					'clientSecret' => '...',
					'title' => 'Yandex (OAuth)',
				),
				'facebook' => array(
					// register your app here: https://developers.facebook.com/apps/
					'class' => 'nodge\eauth\services\FacebookOAuth2Service',
					'clientId' => '...',
					'clientSecret' => '...',
				),
				'yahoo' => array(
					'class' => 'nodge\eauth\services\YahooOpenIDService',
					//'realm' => '*.example.org', // your domain, can be with wildcard to authenticate on subdomains.
				),
				'linkedin' => array(
					// register your app here: https://www.linkedin.com/secure/developer
					'class' => 'nodge\eauth\services\LinkedinOAuth1Service',
					'key' => '...',
					'secret' => '...',
					'title' => 'LinkedIn (OAuth1)',
				),
				'linkedin_oauth2' => array(
					// register your app here: https://www.linkedin.com/secure/developer
					'class' => 'nodge\eauth\services\LinkedinOAuth2Service',
					'clientId' => '...',
					'clientSecret' => '...',
					'title' => 'LinkedIn (OAuth2)',
				),
				'github' => array(
					// register your app here: https://github.com/settings/applications
					'class' => 'nodge\eauth\services\GitHubOAuth2Service',
					'clientId' => '...',
					'clientSecret' => '...',
				),
				'live' => array(
					// register your app here: https://account.live.com/developers/applications/index
					'class' => 'nodge\eauth\services\LiveOAuth2Service',
					'clientId' => '...',
					'clientSecret' => '...',
				),
				'steam' => array(
					'class' => 'nodge\eauth\services\SteamOpenIDService',
					//'realm' => '*.example.org', // your domain, can be with wildcard to authenticate on subdomains.
				),
				'vkontakte' => array(
					// register your app here: https://vk.com/editapp?act=create&site=1
					'class' => 'nodge\eauth\services\VKontakteOAuth2Service',
					'clientId' => '...',
					'clientSecret' => '...',
				),
				'mailru' => array(
					// register your app here: http://api.mail.ru/sites/my/add
					'class' => 'nodge\eauth\services\MailruOAuth2Service',
					'clientId' => '...',
					'clientSecret' => '...',
				),
				'odnoklassniki' => array(
					// register your app here: http://dev.odnoklassniki.ru/wiki/pages/viewpage.action?pageId=13992188
					// ... or here: http://www.odnoklassniki.ru/dk?st.cmd=appsInfoMyDevList&st._aid=Apps_Info_MyDev
					'class' => 'nodge\eauth\services\OdnoklassnikiOAuth2Service',
					'clientId' => '...',
					'clientSecret' => '...',
					'clientPublic' => '...',
					'title' => 'Odnoklas.',
				),
			),
		),
		
		'i18n' => array(
			'translations' => array(
				'eauth' => array(
					'class' => 'yii\i18n\PhpMessageSource',
					'basePath' => '@eauth/messages',
				),
			),
		),

		// (optionally) you can configure pretty urls
		'urlManager' => array(
			'enablePrettyUrl' => true,
			'showScriptName' => false,
			'rules' => array(
				'login/<service:google|facebook|etc>' => 'site/login',
			),
		),

		// (optionally) you can configure logging
		'log' => array(
			'targets' => array(
				array(
					'class' => 'yii\log\FileTarget',
					'logFile' => '@app/runtime/logs/eauth.log',
					'categories' => array('nodge\eauth\*'),
					'logVars' => array(),
				),
			),
		),
		...
	),
...


...
	/**
	 * @var array EAuth attributes
	 */
	public $profile;

	public static function findIdentity($id) {
		if (Yii::$app->getSession()->has('user-'.$id)) {
			return new self(Yii::$app->getSession()->get('user-'.$id));
		}
		else {
			return isset(self::$users[$id]) ? new self(self::$users[$id]) : null;
		}
	}

	/**
	 * @param \nodge\eauth\ServiceBase $service
	 * @return User
	 * @throws ErrorException
	 */
	public static function findByEAuth($service) {
		if (!$service->getIsAuthenticated()) {
			throw new ErrorException('EAuth user should be authenticated before creating identity.');
		}

		$id = $service->getServiceName().'-'.$service->getId();
		$attributes = array(
			'id' => $id,
			'username' => $service->getAttribute('name'),
			'authKey' => md5($id),
			'profile' => $service->getAttributes(),
		);
		$attributes['profile']['service'] = $service->getServiceName();
		Yii::$app->getSession()->set('user-'.$id, $attributes);
		return new self($attributes);
	}
...


	$identity = Yii::$app->getUser()->getIdentity();
	if (isset($identity->profile)) {
		VarDumper::dump($identity->profile, 10, true);
	}


...
	public function behaviors() {
    		return array(
    			'eauth' => array(
    				// 'login'),
    			),
    		);
    	}
...


...
	public function actionLogin() {
		$serviceName = Yii::$app->getRequest()->getQueryParam('service');
		if (isset($serviceName)) {
			/** @var $eauth \nodge\eauth\ServiceBase */
			$eauth = Yii::$app->get('eauth')->getIdentity($serviceName);
			$eauth->setRedirectUrl(Yii::$app->getUser()->getReturnUrl());
			$eauth->setCancelUrl(Yii::$app->getUrlManager()->createAbsoluteUrl('site/login'));

			try {
				if ($eauth->authenticate()) {
//					var_dump($eauth->getIsAuthenticated(), $eauth->getAttributes()); exit;

					$identity = User::findByEAuth($eauth);
					Yii::$app->getUser()->login($identity);

					// special redirect with closing popup window
					$eauth->redirect();
				}
				else {
					// close popup window and redirect to cancelUrl
					$eauth->cancel();
				}
			}
			catch (\nodge\eauth\ErrorException $e) {
				// save error to show it later
				Yii::$app->getSession()->setFlash('error', 'EAuthException: '.$e->getMessage());

				// close popup window and redirect to cancelUrl
//				$eauth->cancel();
				$eauth->redirect($eauth->getCancelUrl());
			}
		}

		// default authorization code through login/password ..
	}
...

...

	if (Yii::$app->getSession()->hasFlash('error')) {
		echo '<div class="alert alert-danger">'.Yii::$app->getSession()->getFlash('error').'</div>';
	}


	/** @var $eauth EAuthServiceBase */
	$eauth = Yii::$app->eauth->getIdentity('facebook');

	// to get protected resources user should be authenticated:
	if ($eauth->getIsAuthenticated()) {
		$eauth->callProtectedApiMethod();
		$eauth->callAnotherProtectedApiMethod();
	}

	// or you can get public resources at any time:
	$eauth->callPublicApiMethod();
	$eauth->callAnotherPublicApiMethod();


	class FacebookOAuth2Service extends \nodge\eauth\services\FacebookOAuth2Service
	{
		public function fooApiMethod($bar) {
			$api_method = 'me'; // ex. for Facebook this results to https://graph.facebook.com/me

			// get protected resource
			$response = $this->makeSignedRequest($api_method, [
				'query' => [ 'foo' => 'bar' ], // GET arguments
				'data' => [ 'foo' => 'bar' ], // POST arguments
				'headers' => [ 'X-Foo' => 'bar'  ], // Extra HTTP headers
			]);

			// you can get public resources with the same API:
			//$response = $this->makeRequest($api_method, $options);

			// process $response
			$data = process($response);

			// return results
			return $data;
		}
	}


...
	'components'=>array(
		'eauth' => array(
			'class' => 'nodge\eauth\EAuth',
			'tokenStorage' => array(
				'class' => '@app\eauth\DatabaseTokenStorage',
			),
		),
		...
	),
...


...
	'components'=>array(
		'i18n' => array(
			'translations' => array(
				'eauth' => array(
					'class' => 'yii\i18n\PhpMessageSource',
					'basePath' => '@eauth/messages',
				),
			),
		),
		...
	),
...
bash
$ curl -sS https://getcomposer.org/installer | php
$ php composer.phar install