Exemple #1
0
 public function login()
 {
     if ($this->check_session()) {
         return true;
     }
     $restTransportInstance = new \RestTransport(\Config::get('yousendit.host'), \Config::get('yousendit.api_key'));
     \Session::set('ysi.sTr', $restTransportInstance);
     $authInstance = new \Authentication(\Config::get('yousendit.host'), \Config::get('yousendit.api_key'), \Session::get('ysi.sTr'));
     $auth = $authInstance->login(\Config::get('yousendit.email'), \Config::get('yousendit.password'));
     $errorStatus = $auth->getErrorStatus();
     $token = $auth->getAuthToken();
     if (!empty($errorStatus)) {
         $this->errorcode = $errorStatus->getMessage();
         $this->errormessage = $errorStatus->getCode();
         return false;
     } else {
         if (empty($token)) {
             $this->errormessage = 'Invalid apikey or hostname!';
             return false;
         } else {
             \Session::set('ysi.sEmail', \Config::get('yousendit.email'));
             \Session::set('ysi.sPass', \Config::get('yousendit.password'));
             \Session::set('ysi.sToken', $token);
             \Session::set('ysi.sApp', \Config::get('yousendit.api_key'));
             \Session::set('ysi.sHost', \Config::get('yousendit.host'));
             \Session::set('ysi.sUserAgent', 'we');
             return true;
         }
     }
     return false;
 }
 public static function fromXML(SimpleXMLElement $xml = null)
 {
     $auth = null;
     if (!empty($xml)) {
         $auth = new Authentication();
         $auth->setType((string) $xml->type);
         if ($data = Data::fromXML($xml->data)) {
             $auth->setData($data);
         }
     }
     return $auth;
 }
 protected function authenticate()
 {
     $auth = new Authentication();
     if (($user = $auth->authenticate($_POST['Login']['Username'], hash('sha512', $_POST['Login']['Password']))) !== false) {
         if (!isset($_SESSION['Authenticated'])) {
             $_SESSION['Authentication'] = array();
         }
         $_SESSION['Authentication']['User'] = $user;
         $_SESSION['Authentication']['LoggedIn'] = true;
     } else {
         $GLOBALS['Smarty']->assign('errormessage', 'Login fehlgeschlagen');
     }
 }
 function StoreAuth($table)
 {
     $auth = new Authentication();
     $this->message = "NOT Authenticated";
     if (isset($_REQUEST['username']) && isset($_REQUEST['password'])) {
         $email = $_REQUEST['username'];
         $password = $_REQUEST['password'];
         if ($auth->credentials($email, $password, $table)) {
             $this->message = "Authenticated";
             StoreSession::loginPage('indexauth.php', $email);
         } else {
             $this->message = "NOT Authenticated";
         }
     }
 }
 /**
  *
  *
  * @return void
  */
 public function callback()
 {
     $config = Config::get('opauth');
     $Opauth = new Opauth($config, FALSE);
     if (!session_id()) {
         session_start();
     }
     $response = isset($_SESSION['opauth']) ? $_SESSION['opauth'] : array();
     $err_msg = null;
     unset($_SESSION['opauth']);
     if (array_key_exists('error', $response)) {
         $err_msg = 'Authentication error:Opauth returns error auth response.';
     } else {
         if (empty($response['auth']) || empty($response['timestamp']) || empty($response['signature']) || empty($response['auth']['provider']) || empty($response['auth']['uid'])) {
             $err_msg = 'Invalid auth response: Missing key auth response components.';
         } elseif (!$Opauth->validate(sha1(print_r($response['auth'], true)), $response['timestamp'], $response['signature'], $reason)) {
             $err_msg = 'Invalid auth response: ' . $reason;
         }
     }
     if ($err_msg) {
         return Redirect::to('account/login')->with('error', $err_msg);
     } else {
         $email = $response['auth']['info']['email'];
         $authentication = new Authentication();
         $authentication->provider = $response['auth']['provider'];
         $authentication->provider_uid = $response['auth']['uid'];
         $authentication_exist = Authentication::where('provider', $authentication->provider)->where('provider_uid', '=', $authentication->provider_uid)->first();
         if (!$authentication_exist) {
             if (Sentry::check()) {
                 $user = Sentry::getUser();
                 $authentication->user_id = $user->id;
             } else {
                 try {
                     $user = Sentry::getUserProvider()->findByLogin($email);
                 } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
                     $user = Sentry::register(array('first_name' => $response['auth']['info']['first_name'], 'last_name' => $response['auth']['info']['last_name'], 'email' => $email, 'password' => Str::random(14)), TRUE);
                 }
                 $authentication->user_id = $user->id;
             }
             $authentication->save();
         } else {
             $user = Sentry::getUserProvider()->findById($authentication_exist->user_id);
             Sentry::login($user);
             Session::put('user_image', $response['auth']['info']['image']);
             return Redirect::to('/');
         }
     }
 }
 protected function _run($request)
 {
     if ($this->requestMethod == 'POST' && count($request) == 0) {
         // User tries to login
         Authentication::login($_POST['username'], $_POST['password']);
         if (!Authentication::authenticated()) {
             Headers::sendStatusUnauthorized();
             return;
         } else {
             Headers::sendStatusOk();
             echo "login succeeded<br>";
             return;
         }
     } else {
         Authentication::authenticate();
         if (!Authentication::authenticated()) {
             Headers::sendStatusUnauthorized();
             return;
         }
         if ($this->requestMethod == 'GET' && count($request) > 0) {
             // User info requested
             echo "requesting userinfo of user " . $request[0];
         } else {
             // Bad request
             Headers::sendStatusMethodNotAllowed();
             echo "Method not allowed<br>";
             print_r($request);
         }
     }
 }
 public static function processLogin()
 {
     if (isset($_REQUEST['submit'])) {
         //check for submission
         $user = new User();
         $username = $_REQUEST['username'];
         $password = $_REQUEST['password'];
         $loaded = $user->load_by_username($username);
         if ($loaded) {
             if ($user->verify_password($password)) {
                 if ($user->isActivated === '1') {
                     Authentication::setAuthentication(True);
                     self::performLoginActions($user->username);
                 } else {
                     echo "<span style='color:red;'>Your Account has not yet been activated, please contact your system administrator</span>";
                 }
             } else {
                 //password may not have been hashed yet
                 $user->passwordHash = User::encodePassword($user->passwordHash);
                 if ($user->verify_password($password)) {
                     $user->save();
                     Authentication::setAuthentication(TRUE);
                     self::performLoginActions($user->username);
                 } else {
                     //if here, password is wrong
                     echo "<h4 style='color:red;'>Invalid password</h4>";
                 }
             }
             //continue processing
         } else {
             //handling for wrong username, allow registration
             echo "<h4 style='color:red;'>Invalid username</h4>";
         }
     }
 }
 /**
  *	Fetch Member
  *
  *	@return	array
  */
 public static function fetchMember()
 {
     if (!self::$member) {
         self::$member = Authentication::GetAuthData();
     }
     return self::$member;
 }
 /**
  * @param string          $message
  * @param \Exception|null $previous
  */
 public function __construct($message = null, $previous = null)
 {
     if (empty($message)) {
         $message = 'Failed to list user accounts';
     }
     parent::__construct($message, $previous);
 }
 public function login()
 {
     try {
         $this->User->validate = $this->User->validate_login;
         $_POST = Utils::sanitazeArray($_POST);
         $this->User->data = $_POST[$this->User->name];
         if ($this->User->validates()) {
             $this->User->data['senha'] = Authentication::password($this->User->data['senha']);
             /**
              * toda a minha validação de status da conta, usuario ou empresa está na procedure.
              * referencia MODEL/USUARIOS.PHP
              * metodo LOGAR
              */
             $usuario[$this->User->name] = $this->User->logar($this->User->data['email'], $this->User->data['senha']);
             if (count($usuario[$this->User->name]) > 0 && $usuario[$this->User->name]['status'] == true) {
                 echo json_encode(array('erro' => false, 'usuario' => array_shift($usuario)));
             } else {
                 throw new Exception('Não foi possivel logar, verifique usuário e senha, ou verifique seu e-mail para ativar sua conta!');
             }
         } else {
             echo json_encode(array('erro' => true, 'erros' => $this->User->validateErros));
         }
     } catch (Exception $ex) {
         echo json_encode(array('erro' => true, 'mensagem' => utf8_decode($ex->getMessage())));
     }
 }
Exemple #11
0
 function __construct()
 {
     Authentication::require_admin();
     $this->is_admin_page = true;
     // updates?
     $this->update_judge_status();
 }
 /**
  * Log user in
  */
 function login()
 {
     $params = $this->request->get('params', false);
     if ($params) {
         $rsa = new Crypt_RSA();
         $my_pub_key = ConfigOptions::getValue('frosso_auth_my_pub_key');
         $my_pri_key = ConfigOptions::getValue('frosso_auth_my_pri_key');
         $rsa->loadKey($my_pri_key);
         $decrypted_params = $rsa->decrypt($params);
         if ($decrypted_params) {
             list($email, $token, $timestamp) = explode(';', $decrypted_params);
             if ($email && $token && $timestamp) {
                 if ($token == ConfigOptions::getValue('frosso_auth_my_pri_token') && time() - 60 * 10 < $timestamp && $timestamp < time() + 60 * 10) {
                     Authentication::useProvider('FrossoProvider', false);
                     Authentication::getProvider()->initialize(array('sid_prefix' => AngieApplication::getName(), 'secret_key' => AngieApplication::getAdapter()->getUniqueKey()));
                     Authentication::getProvider()->authenticate($email);
                 } else {
                     $this->response->forbidden();
                 }
                 // token non valido
             } else {
                 $this->response->badRequest(array('message' => 'Parametri non '));
             }
             // parametri non validi
         } else {
             $this->response->badRequest(array('message' => 'Parametri non validi'));
         }
     } else {
         $this->response->badRequest(array('message' => 'Parametri non settati'));
     }
     // parametri non settati
 }
Exemple #13
0
 /**
  * filters field values like checkbox conversion and date conversion
  *
  * @param array unfiltered values
  * @return array filtered values
  * @see DbConnector::filterFields
  */
 public function filterFields($fields)
 {
     $authentication = Authentication::getInstance();
     $userId = $authentication->getUserId();
     $fields['usr_id'] = $userId['id'];
     return $fields;
 }
Exemple #14
0
 public function cadastro($created)
 {
     /**
      * criar uma pessoa
      */
     $modelPessoa = new Pessoa();
     $pessoasId = $modelPessoa->genericInsert(array('tipo_pessoa' => 1, 'created' => $created));
     /**
      * criar uma pessoa fisica
      */
     $ModelPF = new Fisica();
     $ModelPF->genericInsert(array('pessoas_id' => $pessoasId, 'cpf' => '00000000000', 'nome' => $this->getNome()));
     /**
      * criar um contato
      */
     $modelContato = new Contato();
     $contatoId = $modelContato->genericInsert(array('telefone' => Utils::returnNumeric($this->getPhone()), 'tipo' => 1));
     $modelContato->inserirContato($pessoasId, $contatoId);
     /**
      * criar um email
      */
     $modelEmail = new Email();
     $modelEmail->inserirEmailPessoa($pessoasId, $this->getEmail());
     /**
      * criar um usuario
      */
     $modelUsuario = new Usuario();
     $usuarioId = $modelUsuario->genericInsert(array('roles_id' => 1, 'pessoas_id' => $pessoasId, 'status' => 1, 'perfil_teste' => 0, 'created' => $created, 'email' => $this->getEmail(), 'login' => $this->getEmail(), 'senha' => Authentication::password($this->getPhone()), 'chave' => Authentication::uuid(), 'facebook_id' => $this->getFacebookId()));
     $modelCliente = new Cliente();
     $modelCliente->genericInsert(array('pessoas_id' => $pessoasId, 'status' => 1, 'sexo' => 0));
     return $modelCliente->recuperaCliente($this->getNome(), $this->getPhone());
 }
Exemple #15
0
 private function initialize()
 {
     $auth = Authentication::getInstance();
     if (!$auth->isLogin() || !$auth->isRole(SystemUser::ROLE_ADMIN)) {
         throw new Exception('Access denied');
     }
 }
Exemple #16
0
 private function saveToDb($params)
 {
     $objAuth = Authentication::getInstance();
     $user_id = $objAuth->user_id;
     $objForm = new FormModel();
     $saveData = array();
     $saveData['form_id'] = $params['formSubmit']['id'];
     $saveData['user_id'] = $user_id;
     $saveData['fromPage'] = !empty($params['returnUrlRequest']) ? $params['returnUrlRequest'] : false;
     if (!empty($params['formSubmit']['fields'])) {
         foreach ($params['formSubmit']['fields'] as $fieldId => $value) {
             $fieldInfo = array();
             $fieldInfo['field_id'] = intval($fieldId);
             $fieldInfo['value'] = $value;
             $saveData['fields'][] = $fieldInfo;
         }
     }
     if (!empty($params['formSubmit']['userfields'])) {
         foreach ($params['formSubmit']['userfields'] as $fieldId => $value) {
             $fieldInfo = array();
             $fieldInfo['field_id'] = intval($fieldId);
             $fieldInfo['value'] = $value;
             $saveData['fields'][] = $fieldInfo;
         }
     }
     $submission_id = $objForm->saveSubmission($saveData);
     return $submission_id;
 }
 public static function install($data, &$fail, &$errno, &$error)
 {
     if (!$fail) {
         $auth = new Authentication();
         $salt = $auth->generateSalt();
         $passwordHash = $auth->hashPassword($data['DB']['db_passwd_insert'], $salt);
         $sql = "INSERT INTO `User` (`U_id`, `U_username`, `U_email`, `U_lastName`, `U_firstName`, `U_title`, `U_password`, `U_flag`, `U_salt`, `U_failed_logins`, `U_externalId`, `U_studentNumber`, `U_isSuperAdmin`, `U_comment`) VALUES (NULL, '{$data['DB']['db_user_insert']}', '{$data['DB']['db_email_insert']}', '{$data['DB']['db_last_name_insert']}', '{$data['DB']['db_first_name_insert']}', NULL, '{$passwordHash}', 1, '{$salt}', 0, NULL, NULL, 1, NULL);";
         $result = DBRequest::request($sql, false, $data);
         if ($result["errno"] !== 0) {
             $fail = true;
             $errno = $result["errno"];
             $error = isset($result["error"]) ? $result["error"] : '';
         }
     }
     return null;
 }
Exemple #18
0
 public function registerObjects()
 {
     $key = 'class';
     if (!$this->parameterExists($key)) {
         throw new Exception("Parameter '{$key}' not set\n");
     }
     $classname = $this->getParameter($key);
     // user must log in
     $auth = Authentication::getInstance();
     $key = 'username';
     if (!$this->parameterExists($key)) {
         throw new Exception("Parameter '{$key}' not set\n");
     }
     $username = $this->getParameter($key);
     $key = 'password';
     if (!$this->parameterExists($key)) {
         throw new Exception("Parameter '{$key}' not set\n");
     }
     $password = $this->getParameter($key);
     $auth->login($username, $password, false);
     // user must have backend rights
     if ($auth->isLogin() && !$auth->isRole(SystemUser::ROLE_BACKEND)) {
         throw new Exception('Access denied.');
     }
     try {
         $this->director->pluginManager->loadPlugin($classname);
     } catch (Exception $e) {
         // normal plugin failed, try to load admin plugin
         $this->director->adminManager->loadPlugin($classname);
         //throw new Exception($e->getMessage());
     }
 }
Exemple #19
0
 function __construct()
 {
     // find active entity
     parent::__construct();
     Authentication::require_admin();
     $this->is_admin_page = true;
 }
 /**
  * Constructor
  * 
  * @access public 
  */
 public function __construct()
 {
     self::$config = config_load('authentication');
     $this->db = new Database();
     $this->session = new Session();
     $this->auto_login();
     $this->delete_inactive_users();
 }
 static function Instance()
 {
     if (!isset(self::$mrInstance)) {
         $class_name = __CLASS__;
         self::$mrInstance = new $class_name();
     }
     return self::$mrInstance;
 }
Exemple #22
0
 function getInstance()
 {
     if (!isset(self::$instance)) {
         $c = __CLASS__;
         self::$instance = new $c();
     }
     return self::$instance;
 }
Exemple #23
0
 function write_rejudge_all()
 {
     if (Authentication::is_admin() and $this->entity->submitable()) {
         $this->write_block_begin('Rejudge submissions');
         $this->write_form_begin($this->nav_script(null) . $this->entity->path() . "?rejudge_all=1", 'post');
         $this->write_form_end('Rejudge all submissions for this entity');
         $this->write_block_end();
     }
 }
 private function setInformations()
 {
     try {
         $model = new UserModel();
         self::$informations = $model->getUser(Authentication::getInstance()->getUserId());
     } catch (InputNotSetException $e) {
         $e->getMessage();
     }
 }
Exemple #25
0
 public static function registerUser(AuthenticationUser $object)
 {
     if (isset(self::$instance)) {
         throw new Exception(__CLASS__ . " is already initialized.");
     }
     if (!isset(self::$authenticationUser)) {
         self::$authenticationUser = $object;
     }
 }
Exemple #26
0
 function __construct($user_id = '')
 {
     parent::__construct();
     $this->permissions = new PermissionsModel();
     $this->objAuthentication = Authentication::getInstance();
     if (!empty($user_id)) {
         $this->setUserId($user_id);
     }
 }
Exemple #27
0
/**
 * Smarty {form} function plugin
 *
 * Type:     function<br>
 * Name:     form<br>
 * Purpose:  generates form from database<br>
 * @author Nathan Gardner <*****@*****.**>
 */
function smarty_function_form($localparams, &$smarty)
{
    global $params;
    if (!empty($localparams['identifier'])) {
        $objForm = new FormModel();
        $objAuth = Authentication::getInstance();
        $objTemplate = new TemplatesModel();
        $objUser = new UserModel($objAuth->user_id);
        $userInfo = $objUser->getInfo();
        $form_id = $objForm->getFormId($localparams['identifier']);
        if ($form_id) {
            $formInfo = $objForm->loadForm($form_id);
            $templateInfo = $objTemplate->loadTemplateFromKeyname('form');
            // assign values if already submitted
            if (!empty($params['formSubmit']['fields']) && !empty($formInfo['fields'])) {
                foreach ($formInfo['fields'] as &$formField) {
                    foreach ($params['formSubmit']['fields'] as $submittedId => $submittedValue) {
                        if ($formField['id'] == $submittedId) {
                            if ($formField['type'] == 'checkbox' || $formField['type'] == 'radio') {
                                $formField['checked'] = 'checked';
                            } else {
                                $formField['value'] = $submittedValue;
                            }
                            break;
                        }
                    }
                }
            }
            // assign error flag and message if invalid
            if (!empty($params['formErrors']) && !empty($formInfo['fields'])) {
                foreach ($params['formErrors'] as $formError) {
                    foreach ($formInfo['fields'] as &$formField) {
                        if ($formError['field_id'] == $formField['id']) {
                            $formField['hasError'] = true;
                            $formField['errorMsg'] = $formError['errorMsg'];
                            break;
                        }
                    }
                }
            }
            // assign var to template
            if (!empty($params['formSubmitted'])) {
                $smarty->assign('formSubmitted', 1);
            }
            if (!empty($params['formErrors'])) {
                $smarty->assign('formErrors', $params['formErrors']);
            }
            $smarty->assign('formInfo', $formInfo);
            $output = $smarty->fetch('fromstring:' . $templateInfo['content']);
        } else {
            return 'Unknown form identifier';
        }
    } else {
        return 'Must pass an identifier';
    }
    return $output;
}
Exemple #28
0
 function __construct()
 {
     Authentication::require_admin();
     $this->is_admin_page = true;
     // find active entity
     parent::__construct();
     // debugging
     $this->debug = false;
 }
Exemple #29
0
 /**
  * Model constructor.
  * @param $title
  */
 public function __construct($title)
 {
     $this->title = $title;
     $this->isAuthenticated = Authentication::isAuthenticated();
     if ($this->isAuthenticated) {
         $this->authenticatedUserEntity = Authentication::getUserEntity();
     }
     $this->pageMenu = PageMenu::getPageMenu();
 }
		public static function getByUserID($id)
		{
			global $db;
			$authSQL = "SELECT * FROM authentication WHERE userid=?";
			$values = array($id);
			$auth = $db->qwv($authSQL, $values);
			
			return Authentication::wrap($auth);
		}