<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class LoginForm extends CFormModel {

	public $source;

	public function rules() {
		return array(
//			array('source', 'exist', 'attributeName' => 'tag', 'className' => 'Source')
			array('source', 'authenticate')
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels() {
		return array(
			'source' => 'Viitaja tunnuskood',
		);
	}

	/**
	 * Authenticates the password.
	 */
	public function authenticate($attribute, $params) {
		if (!$this->hasErrors()) {  // we only want to authenticate when no input errors
			$identity = new UserIdentity($this->source);
			$identity->authenticate();
			switch ($identity->errorCode) {
				case UserIdentity::ERROR_NONE:
					$duration = 3600; // (false ? 3600 * 24 * 30 : 0); // 30 days
					Yii::app()->user->login($identity, $duration);
					break;
				default: // UserIdentity::ERROR_PASSWORD_INVALID
					$this->addError('password', 'Väär viitaja tunnuskood.');
					break;
			}
		}
	}

}
