<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class provides oauth capability
 *
 * @package    OAuth
 * @category   Controllers
 * @author     Deon George
 * @copyright  (c) 2009-2013 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
class Controller_Oauth extends Controller_TemplateDefault {
	protected $auth_required = FALSE;
	protected $secure_actions = array(
		'link'=>TRUE,
	);

	public function action_login() {
		// Make sure we are called with a valid oauth plugin
		$oo = ORM::factory('Oauth',array('name'=>$this->request->param('id')));
		if (! $oo->loaded() OR ! $oo->status)
			HTTP::redirect('login');

		$auth = Auth::instance($oo);

		if (! $auth->logged_in())
			HTTP::redirect($auth->login_url());

		$aoo = $oo->account_oauth->where('userid','=',$auth->user_id())->find();

		// If we have an ID, we have been linked, redirect to login
		if ($aoo->loaded() AND $auth->login($aoo->account,$auth->user_id(),$auth))
			return $this->login();

		// We need to link the ID
		Session::instance()->set('login-no-oauth',TRUE);

		Style::factory()
			->type('file')
			->data('media/theme/baseadmin/css/pages/login.css');

		$this->template->content = View::factory('oauth/link')
			->set('type',$oo->name);
		$this->template->shownavbar = FALSE;
	}

	public function action_link() {
		// Make sure we are called with a valid oauth plugin
		$oo = ORM::factory('Oauth',array('name'=>$this->request->param('id')));
		if (! $oo->loaded() OR ! $oo->status)
			HTTP::redirect('login');

		// Since we have logged in, get our user details
		$ao = Auth::instance()->get_user();

		$auth = Auth::instance($oo);
		if (! $auth->logged_in())
			HTTP::redirect('login');

		if ($auth->login($ao,$auth->user_id(),$auth))
			return $this->login();
	}

	/**
	 * When our login is complete and satisified, we execute here
	 */
	private function login() {
		// Redirect to the user account
		if ($redir = Session::instance()->get('afterlogin')) {
			Session::instance()->delete('afterlogin');
			HTTP::redirect($redir);

		} else 
			HTTP::redirect(URL::link('user','welcome/index'));
	}
}
?>