Ejemplo n.º 1
0
 public function login()
 {
     Config::set('database.default', Input::get('server'));
     $db = Input::get('server');
     $credentials = array('memb___id' => Input::get('id'), 'password' => Input::get('pass'), 'bloc_code' => 0);
     $ip = Request::getClientIp();
     $suspect = LoginAttempt::find($ip);
     if (is_null($suspect)) {
         $newlogin = new LoginAttempt();
         $newlogin->ip = $ip;
         $newlogin->attempt = 1;
         $newlogin->save();
         if (Auth::attempt($credentials)) {
             Session::put('db', $db);
             $webuser_id = Auth::user()->webuser_id;
             if ($webuser_id != 0) {
                 Session::put('WebUserId', $webuser_id);
             }
             return Redirect::to(Input::get('url'))->with('message', 'Bạn đã đăng nhập thành công!');
         } else {
             return Redirect::to(Input::get('url'))->with('message', 'Thông tin tài khoản không chính xác!')->withError(10);
         }
     } else {
         $updated_at = $suspect->updated_at;
         $attempt = $suspect->attempt;
         $nowless5 = date('Y-m-d H:i:s', time() - 300);
         if ($updated_at > $nowless5) {
             if ($suspect->attempt > 5) {
                 return Redirect::to(Input::get('url'))->with('message', 'Wait another 5 minutes to login!')->withError(10);
             } else {
                 if (Auth::attempt($credentials)) {
                     Session::put('db', $db);
                     $webuser_id = Auth::user()->webuser_id;
                     if ($webuser_id != 0) {
                         Session::put('WebUserId', $webuser_id);
                     }
                     return Redirect::to(Input::get('url'))->with('message', 'Bạn đã đăng nhập thành công!');
                 } else {
                     $suspect->attempt = $suspect->attempt + 1;
                     $suspect->save();
                     return Redirect::to(Input::get('url'))->with('message', 'Thông tin tài khoản không chính xác!')->withError(10);
                 }
             }
         } else {
             if (Auth::attempt($credentials)) {
                 Session::put('db', $db);
                 $webuser_id = Auth::user()->webuser_id;
                 if ($webuser_id != 0) {
                     Session::put('WebUserId', $webuser_id);
                 }
                 return Redirect::to(Input::get('url'))->with('message', 'Bạn đã đăng nhập thành công!');
             } else {
                 $suspect->attempt = 1;
                 $suspect->save();
                 $suspect->touch();
                 return Redirect::to(Input::get('url'))->with('message', 'Thông tin tài khoản không chính xác!')->withError(10);
             }
         }
     }
 }
Ejemplo n.º 2
0
 /**
  * Overrides init() in Zend_Form
  * 
  * @access public
  * @return void
  */
 public function init()
 {
     // init the parent
     parent::init();
     // set the form's method
     $this->setMethod('post');
     $username = new Zend_Form_Element_Text('username');
     // $this->t = Zend_Registry::get('Zend_Translate');
     $username->setOptions(array('label' => $this->t('Username'), 'required' => true, 'filters' => array('StringTrim', 'StripTags'), 'validators' => array('NotEmpty')));
     $this->addElement($username);
     $password = new Zend_Form_Element_Password('password');
     $password->setOptions(array('label' => $this->t('Password'), 'required' => true, 'filters' => array('StringTrim', 'StripTags'), 'validators' => array('NotEmpty')));
     $this->addElement($password);
     $authentification = new LoginAttempt();
     if ($authentification->canAttemptToLogin() == FALSE) {
         $captcha = new Zend_Form_Element_Captcha('captcha', array('label' => $this->t("no humain"), 'captcha' => array("captcha" => "Image", "wordLen" => 4, "font" => "font/tahoma.ttf", "height" => 100, "width" => 300, "fontSize" => 50, "imgDir" => "data/captchas", "imgUrl" => "data/captchas")));
         $this->addElement($captcha);
     }
     $connexion = new Zend_Form_Element_Submit('Connexion');
     $connexion->setOptions(array('label' => $this->t('Log In')));
     $connexion->setDecorators(array('ViewHelper', array('HtmlTag', array('tag' => 'dd', 'openOnly' => true))));
     $this->addElement($connexion);
     $inscription = new Zend_Form_Element_Submit('inscription');
     $inscription->setOptions(array('label' => $this->t('Sign Up')));
     $inscription->setDecorators(array('ViewHelper', array('HtmlTag', array('tag' => 'dd', 'closeOnly' => true))));
     $this->addElement($inscription);
     $this->clearDecorators();
 }
 /**
  * Method to authenticate an user
  *
  * @param array $RAW_data Raw data to authenticate the user
  * @param Form $form Optional: If passed, better error messages can be
  *                             produced by using
  *                             {@link Form::sessionMessage()}
  * @return bool|Member Returns FALSE if authentication fails, otherwise
  *                     the member object
  * @see Security::setDefaultAdmin()
  */
 public static function authenticate($RAW_data, Form $form = null)
 {
     if (array_key_exists('Email', $RAW_data) && $RAW_data['Email']) {
         $SQL_user = Convert::raw2sql($RAW_data['Email']);
     } else {
         return false;
     }
     $isLockedOut = false;
     $result = null;
     // Default login (see Security::setDefaultAdmin())
     if (Security::check_default_admin($RAW_data['Email'], $RAW_data['Password'])) {
         $member = Security::findAnAdministrator();
     } else {
         $member = DataObject::get_one("Member", "\"" . Member::get_unique_identifier_field() . "\" = '{$SQL_user}' AND \"Password\" IS NOT NULL");
         if ($member) {
             $result = $member->checkPassword($RAW_data['Password']);
         } else {
             $result = new ValidationResult(false, _t('Member.ERRORWRONGCRED'));
         }
         if ($member && !$result->valid()) {
             $member->registerFailedLogin();
             $member = false;
         }
     }
     // Optionally record every login attempt as a {@link LoginAttempt} object
     /**
      * TODO We could handle this with an extension
      */
     if (Security::login_recording()) {
         $attempt = new LoginAttempt();
         if ($member) {
             // successful login (member is existing with matching password)
             $attempt->MemberID = $member->ID;
             $attempt->Status = 'Success';
             // Audit logging hook
             $member->extend('authenticated');
         } else {
             // failed login - we're trying to see if a user exists with this email (disregarding wrong passwords)
             $existingMember = DataObject::get_one("Member", "\"" . Member::get_unique_identifier_field() . "\" = '{$SQL_user}'");
             if ($existingMember) {
                 $attempt->MemberID = $existingMember->ID;
                 // Audit logging hook
                 $existingMember->extend('authenticationFailed');
             } else {
                 // Audit logging hook
                 singleton('Member')->extend('authenticationFailedUnknownUser', $RAW_data);
             }
             $attempt->Status = 'Failure';
         }
         if (is_array($RAW_data['Email'])) {
             user_error("Bad email passed to MemberAuthenticator::authenticate(): {$RAW_data['Email']}", E_USER_WARNING);
             return false;
         }
         $attempt->Email = $RAW_data['Email'];
         $attempt->IP = Controller::curr()->getRequest()->getIP();
         $attempt->write();
     }
     // Legacy migration to precision-safe password hashes.
     // A login-event with cleartext passwords is the only time
     // when we can rehash passwords to a different hashing algorithm,
     // bulk-migration doesn't work due to the nature of hashing.
     // See PasswordEncryptor_LegacyPHPHash class.
     if ($member && self::$migrate_legacy_hashes && array_key_exists($member->PasswordEncryption, self::$migrate_legacy_hashes)) {
         $member->Password = $RAW_data['Password'];
         $member->PasswordEncryption = self::$migrate_legacy_hashes[$member->PasswordEncryption];
         $member->write();
     }
     if ($member) {
         Session::clear('BackURL');
     } else {
         if ($form && $result) {
             $form->sessionMessage($result->message(), 'bad');
         }
     }
     return $member;
 }
Ejemplo n.º 4
0
<?php

require "LoginAttempt.php";
if (!empty($_POST["username"]) && !empty($_POST["password"])) {
    $dsn = "mysql:host=localhost;dbname=test";
    $pdo = new PDO($dsn, "root", "");
    try {
        $attempt = new LoginAttempt($_POST["username"], $_POST["password"], $pdo);
        $attempt->whenReady(function ($success) {
            echo $success ? "Valid" : "Invalid";
        });
    } catch (Exception $e) {
        if ($e->getCode() == 503) {
            header("HTTP/1.1 503 Service Unavailable");
            exit;
        } else {
            if ($e->getCode() == 403) {
                header("HTTP/1.1 403 Forbidden");
                exit;
            } else {
                echo "Error: " . $e->getMessage();
            }
        }
        // Note here that it may be advisable to show the
        // same response for error messages that you show
        // for invalid requests. That way it'll be less
        // obvious to attackers that their requests are
        // being rejected rather than processed and
        // invalidated.
    }
} else {
 /**
  * Log login attempt
  * TODO We could handle this with an extension
  *
  * @param array $data
  * @param Member $member
  * @param bool $success
  */
 protected static function record_login_attempt($data, $member, $success)
 {
     if (!Security::config()->login_recording) {
         return;
     }
     // Check email is valid
     $email = isset($data['Email']) ? $data['Email'] : null;
     if (is_array($email)) {
         throw new InvalidArgumentException("Bad email passed to MemberAuthenticator::authenticate(): {$email}");
     }
     $attempt = new LoginAttempt();
     if ($success) {
         // successful login (member is existing with matching password)
         $attempt->MemberID = $member->ID;
         $attempt->Status = 'Success';
         // Audit logging hook
         $member->extend('authenticated');
     } else {
         // Failed login - we're trying to see if a user exists with this email (disregarding wrong passwords)
         $attempt->Status = 'Failure';
         if ($member) {
             // Audit logging hook
             $attempt->MemberID = $member->ID;
             $member->extend('authenticationFailed');
         } else {
             // Audit logging hook
             singleton('Member')->extend('authenticationFailedUnknownUser', $data);
         }
     }
     $attempt->Email = $email;
     $attempt->IP = Controller::curr()->getRequest()->getIP();
     $attempt->write();
 }
 /**
  * Writes a message to the audit log
  *
  * @param object  $member       The member if found in the database
  * @param string  $anchor       The login name if the user
  * @param string  $action_type  What was tried?
  * @param string  $because      Reason for success
  * @param boolean $success      Did we succeed
  * @param string  $source_id    For which source
  **/
 public static function AuditLog($member, $anchor, $action_type, $because, $success, $source_id)
 {
     if (self::getAuditLogSStripe()) {
         //Use built-in mechanism
         $attempt = new LoginAttempt();
         if ($member) {
             $attempt->MemberID = $member->ID;
         } else {
             $attempt->MemberID = 0;
         }
         if ($success) {
             $attempt->Status = 'Success';
         } else {
             $attempt->Status = 'Failure';
         }
         $attempt->IP = Controller::curr()->getRequest()->getIP();
         $attempt->Email = $anchor . '@' . $source_id;
         $attempt->write();
     }
     if (!is_bool(self::getAuditLogFile())) {
         $logmessage = date(DATE_RFC822) . ' - ';
         if ($success) {
             $logmessage .= '[SUCCESS] ';
         } else {
             $logmessage .= '[FAILURE] ';
         }
         $logmessage .= 'action ' . $action_type . ' for user ' . $anchor . ' at ' . Controller::curr()->getRequest()->getIP() . ' from source ' . $source_id;
         if (!is_null($because)) {
             $logmessage .= ' because ' . $because;
         }
         if (!@error_log($logmessage . "\n", 3, self::getAuditLogFile())) {
             trigger_error('Unable to write logon attempt to ' . self::getAuditLogFile(), E_USER_ERROR);
         }
     }
 }
Ejemplo n.º 7
0
 /**
  * Method to authenticate an user
  *
  * @param array $RAW_data Raw data to authenticate the user
  * @param Form $form Optional: If passed, better error messages can be
  *                             produced by using
  *                             {@link Form::sessionMessage()}
  * @return bool|Member Returns FALSE if authentication fails, otherwise
  *                     the member object
  * @see Security::setDefaultAdmin()
  */
 public static function authenticate($RAW_data, Form $form = null)
 {
     $SQL_user = Convert::raw2sql($RAW_data['Email']);
     $isLockedOut = false;
     // Default login (see Security::setDefaultAdmin())
     if (Security::check_default_admin($RAW_data['Email'], $RAW_data['Password'])) {
         $member = Security::findAnAdministrator();
     } else {
         $member = DataObject::get_one("Member", "Email = '{$SQL_user}' AND Password IS NOT NULL");
         if ($member && $member->checkPassword($RAW_data['Password']) == false) {
             if ($member->isLockedOut()) {
                 $isLockedOut = true;
             }
             $member->registerFailedLogin();
             $member = null;
         }
     }
     // Optionally record every login attempt as a {@link LoginAttempt} object
     /**
      * TODO We could handle this with an extension
      */
     if (Security::login_recording()) {
         $attempt = new LoginAttempt();
         if ($member) {
             // successful login (member is existing with matching password)
             $attempt->MemberID = $member->ID;
             $attempt->Status = 'Success';
             // Audit logging hook
             $member->extend('authenticated');
         } else {
             // failed login - we're trying to see if a user exists with this email (disregarding wrong passwords)
             $existingMember = DataObject::get_one("Member", "Email = '{$SQL_user}'");
             if ($existingMember) {
                 $attempt->MemberID = $existingMember->ID;
                 // Audit logging hook
                 $existingMember->extend('authenticationFailed');
             } else {
                 // Audit logging hook
                 singleton('Member')->extend('authenticationFailedUnknownUser', $RAW_data);
             }
             $attempt->Status = 'Failure';
         }
         if (is_array($RAW_data['Email'])) {
             user_error("Bad email passed to MemberAuthenticator::authenticate(): {$RAW_data['Email']}", E_USER_WARNING);
             return false;
         }
         $attempt->Email = $RAW_data['Email'];
         $attempt->IP = Controller::curr()->getRequest()->getIP();
         $attempt->write();
     }
     if ($member) {
         Session::clear("BackURL");
     } else {
         if ($isLockedOut) {
             if ($form) {
                 $form->sessionMessage(_t('Member.ERRORLOCKEDOUT', "Your account has been temporarily disabled because of too many failed attempts at logging in. Please try again in 20 minutes."), "bad");
             }
         } else {
             if ($form) {
                 $form->sessionMessage(_t('Member.ERRORWRONGCRED', "That doesn't seem to be the right e-mail address or password. Please try again."), "bad");
             }
         }
     }
     return $member;
 }
 public static function login(array $post)
 {
     $callbackObj = new \stdClass();
     $callbackObj->user = null;
     $callbackObj->status = false;
     $callbackObj->code = null;
     $callbackObj->tentativas_restantes = null;
     $user = self::find_by_username($post['username']);
     if (!is_null($user)) {
         $password = \HXPHP\System\Tools::hashHX($post['password'], $user->salt);
         if ($user->status === 1) {
             if (LoginAttempt::ExistemTentativas($user->id)) {
                 if ($password['password'] === $user->password) {
                     $callbackObj->user = $user;
                     $callbackObj->status = true;
                     LoginAttempt::LimparTentativas($user->id);
                 } else {
                     if (LoginAttempt::TentativasRestantes($user->id) <= 3) {
                         $callbackObj->code = 'tentativas-esgotando';
                         $callbackObj->tentativas_restantes = LoginAttempt::TentativasRestantes($user->id);
                     } else {
                         $callbackObj->code = 'dados-incorretos';
                     }
                     LoginAttempt::RegistrarTentativa($user->id);
                 }
             } else {
                 $callbackObj->code = 'usuario-bloqueado';
                 $user->status = 0;
                 $user->save(false);
             }
         } else {
             $callbackObj->code = 'usuario-bloqueado';
         }
     } else {
         $callbackObj->code = 'usuario-inexistente';
     }
     return $callbackObj;
 }
Ejemplo n.º 9
0
 public function dologin()
 {
     Config::set('database.default', Input::get('server'));
     $db = Input::get('server');
     $id = Input::get('id');
     $credentials = array('memb___id' => $id, 'password' => Input::get('password1'), 'bloc_code' => 0);
     $ip = Request::getClientIp();
     $suspect = LoginAttempt::find($ip);
     $destination = Session::get('fromfilter');
     if (is_null($destination)) {
         $destination = 'DashBoard';
     }
     if (is_null($suspect)) {
         $newlogin = new LoginAttempt();
         $newlogin->ip = $ip;
         $newlogin->attempt = 1;
         $newlogin->save();
         if (Auth::attempt($credentials)) {
             Session::put('db', $db);
             $webuser_id = Auth::user()->webuser_id;
             if ($webuser_id == 0) {
                 return Redirect::to('ManageAcc');
             }
             $webU = WebUser::find($webuser_id);
             $name = $webU->username;
             $group = $webU->role;
             $coin = $this->getCoin($id);
             Session::put('nameCok', $name);
             Session::put('groupCok', $group);
             Session::put('ipCok', $ip);
             Session::put('WebUserId', $webuser_id);
             Session::put('idCok', $id);
             Session::put('coinCok', $coin);
             return Redirect::to($destination);
         } else {
             return Redirect::to('login')->with('message', 'Incorrect account/password!');
         }
     } else {
         $updated_at = $suspect->updated_at;
         $attempt = $suspect->attempt;
         $nowless5 = date('Y-m-d H:i:s', time() - 300);
         if ($updated_at > $nowless5) {
             if ($suspect->attempt > 5) {
                 return Redirect::to('/login')->withInput()->with('message', 'Wait another 5 minutes to login!');
             } else {
                 if (Auth::attempt($credentials)) {
                     Session::put('db', $db);
                     $webuser_id = Auth::user()->webuser_id;
                     if ($webuser_id == 0) {
                         return Redirect::to('ManageAcc');
                     }
                     $webU = WebUser::find($webuser_id);
                     $name = $webU->username;
                     $group = $webU->role;
                     $coin = $this->getCoin($id);
                     Session::put('nameCok', $name);
                     Session::put('groupCok', $group);
                     Session::put('ipCok', $ip);
                     Session::put('WebUserId', $webuser_id);
                     Session::put('idCok', $id);
                     Session::put('coinCok', $coin);
                     return Redirect::to($destination);
                 } else {
                     $suspect->attempt = $suspect->attempt + 1;
                     $suspect->save();
                     return Redirect::to('login')->withInput()->with('message', 'Incorrect account/password!');
                 }
             }
         } else {
             if (Auth::attempt($credentials)) {
                 Session::put('db', $db);
                 $webuser_id = Auth::user()->webuser_id;
                 if ($webuser_id == 0) {
                     return Redirect::to('ManageAcc');
                 }
                 $webU = WebUser::find($webuser_id);
                 $name = $webU->username;
                 $group = $webU->role;
                 $coin = $this->getCoin($id);
                 Session::put('nameCok', $name);
                 Session::put('groupCok', $group);
                 Session::put('ipCok', $ip);
                 Session::put('WebUserId', $webuser_id);
                 Session::put('idCok', $id);
                 Session::put('coinCok', $coin);
                 return Redirect::to($destination);
             } else {
                 $suspect->attempt = 1;
                 $suspect->save();
                 $suspect->touch();
                 return Redirect::to('login')->with('message', 'Incorrect account/password!');
             }
         }
     }
 }