Modules

Controller_OAuth_Live
extends Controller_OAuth_Base
extends Template
extends Gleez_Template
extends Controller
extends Kohana_Controller

OAuth Live Controller

package
Gleez\OAuth\Controller
author
Sandeep Sangamreddi - Gleez
copyright
© 2011-2013 Gleez Technologies
license
http://gleezcms.org/license

Class declared in MODPATH/user/classes/controller/oauth/live.php on line 10.

Properties

public boolean $auto_render

Auto render template?

public boolean $debug

Turn debugging on?

public Request $request

Request that created the controller

public Response $response

The response that will be returned from controller

public string $site_name

The site name

public string $template

Page template

public string $title

The page title

public string $title_separator

The delimiter page header and site name

protected array $_accept_formats

List all supported formats for this controller (accept-type => path to format template)

protected boolean $_ajax

Is ajax request?

protected object $_auth

The Auth Object

protected array $_benchmark

Profiling

protected Kohana_Config $_config

The configuration settings

protected array $_desti

The destination url

protected Format $_format

An Format instance

protected boolean $_internal

is internal request?

protected string $_page_class

Current page class

protected string $_page_id

Current page id, defaults to controller name

protected array $_regions

The sidebar content

protected string $_response_format

Hold the response format for this request

protected boolean $_sidebars

Enable sidebars for this request? For example: add or edit page don't requires sidebars

protected array $_tabs

Tabs navigation

protected object $_widgets

The Widgets Object

protected $client

protected $code

protected $content

protected $provider

protected array $redirect

The destination url

protected $route

protected $session

protected $token

Methods

public action_index( ) (defined in Controller_OAuth_Live)

Source Code

public function action_index()
{
               //Message::debug( Debug::vars($this) );
               $url = $this->route->uri(array('controller' => 'live', 'action' => 'login'));
	$img = HTML::image('media/images/live.jpg', array('title' => __('Sign in with Windows Live')) );

               $this->content = HTML::anchor($url, $img, array('title' => __('Sign in with Windows Live') ) );
}

public action_callback( ) (defined in Controller_OAuth_Base)

Source Code

public function action_callback()
{
  try
  {
    // Attempt to complete signin
    if ($code = Arr::get($_REQUEST, 'code'))
    {
      // We will need a callback URL for the user to return to
      $callback = URL::site($this->route->uri(
        array(
          'controller' => $this->provider->name,
          'action' => 'callback'
        )),
      'http');

      // Add the callback URL to the consumer
      $this->client->callback($callback);

      // Exchange the authorization code for an access token
      $tokens = $this->provider->get_tokens($this->client, $code);
      $token = $tokens->param('access_token');
      $r_token = $tokens->param('refresh_token');

      // Store the access token
      $this->session->set($this->key('access'), $token);
      $this->session->set($this->key('refresh'), $r_token);

      // Refresh the page to prevent errors
      $this->request->redirect($this->request->uri());
    }

    if ($this->token)
    {
      // Redirect to the provider's index page
      $this->request->redirect( $this->route->uri(
        array(
          'controller' => $this->provider->name,
          'action' => 'complete'
        ))
      );
    }

    Kohana::$log->add(LOG::ERROR, 'Error retrieving code/tokens');
    Message::info(__('Coudn\'t login. Either you deny or network error!'));

    // Redirect to the provider's index page
    $this->request->redirect($this->route->uri(
      array(
        'controller' => $this->provider->name
      ))
    );
  }
  catch( Exception $e)
  {
    Kohana::$log->add(LOG::ERROR, (string) $e);

    // Redirect to the provider's index page
    $this->request->redirect( $this->route->uri(
        array('controller' => $this->provider->name, 'action' => 'index')));
  }
}

public action_complete( ) (defined in Controller_OAuth_Base)

Source Code

public function action_complete()
{
  try
  {
    // Login succesful
    $response = $this->provider->access_profile($this->token);

    //make sure the response is valid by checking id
    if (isset($response['id']))
    {
      // Check whether that id exists in our identities table (provider_id field)
      $user = User::check_identity( $response['id'], $this->provider->name);

      //inisiate the provider specefic process to login
      $data = $this->response_process($response);

      if(isset($data['email']))
      {
        // @see Controller_OAuth_Base::sso_signup
        $this->sso_signup( $data, $user );
      }

      //$this->content = Debug::vars( "{$this->provider->name} Data:", $response );
      $this->request->redirect('user/profile');
    }
  }
  catch( Exception $e )
  {
    Kohana::$log->add(LOG::ERROR, (string) $e);

    // Redirect to the provider's index page
    $this->request->redirect( $this->route->uri(
      array(
        'controller' => $this->provider->name,
        'action' => 'index'
      ))
    );

  }
}

public action_login( ) (defined in Controller_OAuth_Base)

Source Code

public function action_login()
{
  try
  {
    // We will need a callback URL for the user to return to
    $callback = URL::site($this->route->uri(
      array(
        'controller' => $this->provider->name,
        'action' => 'callback'
      )),
    'http');

    // Add the callback URL to the consumer
    $this->client->callback($callback);

    // Get the login URL from the provider
    $url = $this->provider->authorize_url($this->client, $this->client->scope);

    // Redirect to the provider's login page
    $this->request->redirect($url);
  }
  catch( Exception $e)
  {
    Kohana::$log->add(LOG::ERROR, (string) $e);
  }
}

public after( ) (defined in Controller_OAuth_Base)

The after() method is called after controller action.

Return Values

  • void

Source Code

public function after()
{
  $this->response->body($this->content);

  return parent::after();
}

public before( ) (defined in Controller_OAuth_Base)

The before() method is called before controller action.

Tags

Source Code

public function before()
{
  parent::before();

  // If loggedin redirect to profile
  if(Auth::instance()->logged_in())
  {
    $this->request->redirect(Route::get('user')->uri(array('action' => 'profile')), 200);
  }

  // Load the session
  $this->session = Session::instance();

  // Set the provider controller
  $provider = strtolower($this->request->controller());
  $providers = Kohana::$config->load('auth.providers');

  // Throw exception if the provider is disabled
  if(! array_key_exists($provider, array_filter($providers)))
  {
    throw new Http_Exception_404('Unsupported provider', NULL);
  }

  $this->route = $this->request->route();

  // Load the provider
  $this->provider = OAuth2_Provider::factory($provider);

  // Load the client
  $this->client = OAuth2_Client::factory(Kohana::$config->load("oauth.{$provider}"));

  if ($token = $this->session->get($this->key('access')))
  {
    // Make the access token available
    $this->token = $token;
  }
}

public key( ) (defined in Controller_OAuth_Base)

Source Code

public function key($name)
{
  return "api_{$this->provider->name}_{$name}";
}

public is_frontpage( ) (defined in Gleez_Template)

Is frontpage?

Tags

Return Values

  • boolean

Source Code

public function is_frontpage()
{
	$uri = preg_replace("#(/p\d+)+$#uD", '', rtrim($this->request->uri(), '/'));

	return (empty($uri) OR ($uri === $this->_config->front_page));
}

public valid_post( [ string|NULL $submit = NULL ] ) (defined in Gleez_Template)

Returns TRUE if the POST has a valid CSRF

Usage:
if ($this->valid_post('upload_photo')) { ... }

Parameters

  • string|NULL $submit = NULL - Submit value [Optional]

Tags

Return Values

  • boolean - Return TRUE if it's valid $_POST

Source Code

public function valid_post($submit = NULL)
{
	if ( ! $this->request->is_post())
	{
		return FALSE;
	}

	if (Request::post_max_size_exceeded())
	{
		Message::error(__('Max file size of :max Bytes exceeded!',
			array(':max' => Request::get_post_max_size())
		));
		return FALSE;
	}

	if ( ! is_null($submit) )
	{
		if ( ! isset($_POST[$submit]))
		{
			Message::error(__('This form has altered. Please try submitting it again.'));
			return FALSE;
		}
	}

	$_token  = $this->request->post('_token');
	$_action = $this->request->post('_action');

	$has_csrf = ! empty($_token) AND ! empty($_action);
	$valid_csrf = $has_csrf AND CSRF::valid($_token, $_action);

	if ($has_csrf AND ! $valid_csrf)
	{
		// CSRF was submitted but expired
		Message::error(__('This form has expired. Please try submitting it again.'));
		return FALSE;
	}

	if (isset($_POST['_captcha']))
	{
		$captcha = $this->request->post('_captcha');
		if (empty($captcha))
		{
			// CSRF was not entered
			Message::error(__('The security code can\'t be empty.'));
			return FALSE;
		}
		elseif ( ! Captcha::valid($captcha))
		{
			Message::error(__('The security answer was wrong.'));
			return FALSE;
		}
	}

	return $has_csrf AND $valid_csrf;
}

public __construct( Request $request , Response $response ) (defined in Kohana_Controller)

Creates a new controller instance. Each controller must be constructed with the request object that created it.

Parameters

  • Request $request required - Request that created the controller
  • Response $response required - The request's response

Return Values

  • void

Source Code

public function __construct(Request $request, Response $response)
{
	// Assign the request to the controller
	$this->request = $request;

	// Assign a response to the controller
	$this->response = $response;
}

protected response_process( ) (defined in Controller_OAuth_Live)

Source Code

protected function response_process($response)
{
	$data = array();

	//make sure the response is valid
	if ( $response AND !array_key_exists('error', $response) )
	{
		if( $response['emails'] )
		{
			$data['id'] = $response['id'];
			$data['email'] = $response['emails']['account']; //only account email is used
			$data['nick'] = $response['name'];
			$data['link'] = $response['link'];
			$data['gender'] = ($response['gender'] != NULL) ? $response['gender'] : FALSE;
		}
	}

	return $data;
       }

protected sso_signup( ) (defined in Controller_OAuth_Base)

Source Code

protected function sso_signup($data, $user = FALSE)
{
  // If not, store the new provider_id (as a new user) or attach to existing user
  try
  {
    //vars for processing stuff
    $signup = $creation = FALSE;

    $provider = array();
    $provider['provider'] = $this->provider->name;
    $provider['provider_id'] = $data['id'];
    $provider['refresh_token'] = $this->session->get($this->key('refresh'));

    if($user instanceof Model_User)
    {
      // If they're loaded, they're a member. Login if not logged
      if($user->loaded() AND ! Auth::instance()->logged_in())
      {
        // Log in as this user
        Auth::instance()->force_login($user);

        Message::success(__('Welcome back, :nick logged in via (:provider).',
          array(
            ':nick' => $user->nick,
            ':provider' => $this->provider->name
          ))
        );
      }
    }
    else
    {
      $signup = TRUE;

      // Otherwise, if we're here, this identity isn't associated with any one yet.
      // Are they currently logged in?
      if (Auth::instance()->logged_in())
      {
        // Associate their new oAuth with their current account.
        $user = Auth::instance()->get_user();
      }
      else
      {
        // Check whether the email exists or Otherwise, they need a new account
        $user = ORM::factory('user')->where('mail', '=', $data['email'])->find();

        if(! $user->loaded())
        {
          $creation = TRUE;
        }
      }
    }

    if($signup)
    {
      // @see Model_Auth_User::sso_signup for create new account/associate this OAuth
      $user->sso_signup($data, $provider);

      if($creation)
      {
        Message::success(__('Thank you :nick for registering via (:provider).',
          array(
            ':nick' => $user->nick,
            ':provider' =>  $this->provider->name
          ))
        );
      }
      else
      {
        Message::success(__('Attached identity :nick (:provider) to your account.',
          array(
            ':nick' => $user->nick,
            ':provider' => $this->provider->name
          ))
        );
      }
    }

  }
  catch(Exception $e)
  {
    Kohana::$log->add(LOG::ERROR, (string) $e);

    // Redirect to the provider's index page
    $this->request->redirect( $this->route->uri(
      array(
        'controller' => $this->provider->name,
        'action' => 'index'
      ))
    );
  }

  // If yes, log the user in and give him a normal auth session.
  Auth::instance()->force_login($user);
}

protected _set_column_class( ) (defined in Gleez_Template)

Add sidebar column class

This method is chainable.

Source Code

protected function _set_column_class()
{
	$sidebar_left  = $this->template->sidebar_left;
	$sidebar_right = $this->template->sidebar_right;

	if ( ! empty($sidebar_left) AND ! empty($sidebar_right))
	{
		$this->template->column_class = 'main-both';
		$this->template->main_column  = 6;
	}
	else
	{
		if ( ! empty($sidebar_left))
		{
			$this->template->column_class = 'main-left';
			$this->template->main_column  = 9;
		}
		if ( ! empty($sidebar_right))
		{
			$this->template->column_class = 'main-right';
			$this->template->main_column  = 9;
		}
	}

	return $this;
}

protected _set_default_css( ) (defined in Gleez_Template)

Set default CSS

Tags

Source Code

protected function _set_default_css()
{
	Assets::css('bootstrap', 'media/css/bootstrap.min.css', NULL, array('weight' => -15));
	Assets::css('font-awesome', 'media/css/font-awesome.min.css', array('weight' => -13));
	Assets::css('default', 'media/css/default.css', NULL, array('weight' => 0));
	Assets::css('style', 'media/css/style.css', array('default'), array('weight' => 1));
}

protected _set_default_js( ) (defined in Gleez_Template)

Set default JavaScript

Tags

Source Code

protected function _set_default_js()
{
	Assets::js('bootstrap', 'media/js/bootstrap.min.js', array('jquery'), FALSE, array('weight' => 5));

	// Google js only in production and not in admin section
	if (Kohana::PRODUCTION === Kohana::$environment AND Theme::$is_admin === FALSE)
	{
		$ua = $this->_config->get('google_ua', NULL);
		if ( ! is_null($ua))
		{
			Assets::google_stats($ua);
		}
	}
}

Set the default meta links

Used configuration settings.

Tags

Source Code

protected function _set_default_meta_links()
{
	$meta  = $this->_config->get('meta', array());
	$links = Arr::get($meta, 'links');

	if ($links)
	{
		foreach ($links as $url => $attributes)
		{
			Meta::links($url, $attributes);
		}
	}
}

protected _set_default_meta_tags( ) (defined in Gleez_Template)

Set the default meta tags

Using configuration settings.

Tags

Source Code

protected function _set_default_meta_tags()
{
	$meta = $this->_config->get('meta', array());
	$tags = Arr::get($meta, 'tags');

	if ($tags)
	{
		foreach ($tags as $handle => $value)
		{
			$conditional = NULL;

			if (is_array($value))
			{
				$conditional = Arr::get($value, 'conditional');
				$value       = Arr::get($value, 'value', '');
			}

			$attrs = array();

			if (isset($conditional))
			{
				$attrs['conditional'] = $conditional;
			}

			Meta::tags($handle, $value, $attrs);
		}
	}
}

protected _set_default_server_headers( ) (defined in Gleez_Template)

Set the default server headers

Source Code

protected function _set_default_server_headers()
{
	$headers = $this->_config->get('headers', array());
	$headers['X-Gleez-Version'] = 'Gleez CMS v ' . Gleez::VERSION . ' (' . Gleez::CODENAME . ')';

	$xmlrpc = $this->_config->get('xmlrpc', NULL);

	/** @var $xmlrpc string|NULL */
	if ( ! is_null($xmlrpc))
	{
		$headers['X-Pingback'] = URL::site($xmlrpc, TRUE);
	}

	$this->_set_server_headers($headers);
}

protected _set_head_title( ) (defined in Gleez_Template)

Set the page title

Source Code

protected function _set_head_title()
{
	if ($this->title)
	{
		$head_title = array(
			strip_tags($this->title),
			$this->template->site_name
		);
	}
	else
	{
		$head_title = array(
			$this->template->site_name
		);

		if ($this->template->site_slogan)
		{
			$head_title[] = $this->template->site_slogan;
		}
	}

	$this->template->head_title = implode($this->title_separator, $head_title);
}

protected _set_profiler_stats( ) (defined in Gleez_Template)

Set the profiler stats into template.

Tags

Source Code

protected function _set_profiler_stats()
{
	$queries = 0;

	if (Kohana::$profiling)
	{
		// DB queries
		foreach (Profiler::groups() as $group => $benchmarks)
		{
			if (strpos($group, 'database') === 0)
			{
				$queries += count($benchmarks);
			}
		}
	}

	// Get the total memory and execution time
	$total = array(
		'{memory_usage}'     => number_format((memory_get_peak_usage() - KOHANA_START_MEMORY) / 1024 / 1024, 2) . 'MB',
		'{gleez_version}'    => Gleez::VERSION,
		'{execution_time}'   => number_format(microtime(TRUE) - KOHANA_START_TIME, 3) . ' seconds',
		'{included_files}'   => count(get_included_files()),
		'{database_queries}' => $queries
	);

	// Insert the totals into the response
	$this->template = strtr((string) $this->template, $total);
}

protected _set_server_headers( array $headers ) (defined in Gleez_Template)

Set the server headers

Parameters

  • array $headers required - An associative array of server headers

Source Code

protected function _set_server_headers($headers)
{
	if (is_array($headers) AND ! empty($headers))
	{
		$this->response->headers($headers);
	}
}

protected _set_sidebars( ) (defined in Gleez_Template)

Add sidebars

This method is chainable.

Source Code

protected function _set_sidebars()
{
	if ($this->_sidebars !== FALSE)
	{
		$this->template->sidebar_left  = $this->_widgets->render('left');
		$this->template->sidebar_right = $this->_widgets->render('right');
	}

	return $this;
}
Documentation comments powered by Disqus