check() public static method

Check the given plain value against a hash.
public static check ( string $value, string $hashedValue, array $options = [] ) : boolean
$value string
$hashedValue string
$options array
return boolean
 public function login()
 {
     if (Auth::check()) {
         echo json_encode(array('succcess' => false, 'state' => 200, 'errMsg' => array('inputMsg' => '该用户已登录,请不要重复登录'), 'no' => 2));
         exit;
     }
     $account = Input::get('user_email');
     $password = Input::get('user_psw');
     $rememberMe = Input::get('user_remember');
     $captcha = Input::get('user_auth');
     $ip = $this->getIP();
     $codeKey = md5($ip);
     $captchaCode = Cache::tags('register', 'code')->get($codeKey);
     if ($captcha != $captchaCode) {
         echo json_encode(array('success' => false, 'state' => 200, 'errMsg' => array('inputMsg' => '验证码验证失败'), 'no' => 1));
         exit;
     }
     $accountCheck = $this->accountCheck($account);
     if (!is_object($accountCheck)) {
         echo json_encode(array('success' => false, 'state' => 200, 'errMsg' => array('inputMsg' => '用户不存在'), 'no' => 1));
         exit;
     }
     $passwordCheck = Hash::check($password, $accountCheck->user->password);
     if ($passwordCheck) {
         if ($rememberMe == 'true') {
             Auth::login($accountCheck, true);
         } else {
             Auth::login($accountCheck);
         }
     } else {
         echo json_encode(array('succcess' => false, 'state' => 200, 'errMsg' => array('inputMsg' => '密码验证失败'), 'no' => 2));
     }
     echo json_encode(array('success' => true, 'state' => 200, 'nextSrc' => url('usercenter')));
 }
Beispiel #2
0
 public function login()
 {
     $validaciones = Usuario::validacioneslogin(Input::all());
     if ($validaciones->fails()) {
         return Redirect::to('/')->withErrors($validaciones)->withInput();
     } else {
         $email = Input::get('email');
         $clave = Input::get('clave');
         $usuario = Usuario::where('login', '=', $email)->get();
         // no se hace new xq necesitamos la misma instancia
         if ($usuario->count() == 1) {
             if (Hash::check($clave, $usuario[0]->clave)) {
                 Session::put('id', $usuario[0]->id);
                 Session::put('nombre', $usuario[0]->nombre);
                 Session::put('login', $usuario[0]->login);
                 Session::put('email', $usuario[0]->email);
                 Session::put('rol', $usuario[0]->rol);
                 Session::put('estatus', $usuario[0]->estatus);
                 Session::put('logged', TRUE);
                 //MANDA  una variable q indica logeado
                 Session::put('familia_id', $usuario[0]->familia->id);
                 return Redirect::to('/dashboard');
             } else {
                 Session::flash('message', 'La clave no es válida');
                 Session::flash('class', 'danger');
             }
         } else {
             Session::flash('message', 'El Usuario no está registrado');
             Session::flash('class', 'danger');
         }
         return Redirect::to('/');
     }
 }
 /**
  * Handle a POST request to remind a user of their password.
  *
  * @return Response
  */
 public function postConfirmation()
 {
     // 3 error cases - user already confirmed, email does not exist, password not correct
     // (prevents people from brute-forcing email addresses to see who is registered)
     $email = Input::get('email');
     $password = Input::get('password');
     $user = User::where('email', $email)->first();
     if (!isset($user)) {
         return Response::json($this->growlMessage('That email does not exist.', 'error'), 400);
     }
     if (empty($user->token)) {
         return Response::json($this->growlMessage('That user was already confirmed.', 'error'), 400);
     }
     if (!Hash::check($password, $user->password)) {
         return Response::json($this->growlMessage('The password for that email is incorrect.', 'error'), 400);
     }
     $token = $user->token;
     $email = $user->email;
     $fname = $user->fname;
     //Send email to user for email account verification
     Mail::queue('email.signup', array('token' => $token), function ($message) use($email, $fname) {
         $message->subject('Welcome to the Madison Community');
         $message->from('*****@*****.**', 'Madison');
         $message->to($email);
     });
     return Response::json($this->growlMessage('An email has been sent to your email address.  Please follow the instructions in the email to confirm your email address before logging in.', 'warning'));
 }
Beispiel #4
0
 /**
  * Add a menu item
  *
  * @param string $path dot separated path in the array.
  * @param array $options menu options array
  * @return void
  */
 public static function add($menu, $path, $options = array())
 {
     // Juggle argument for backward compatibility
     if (is_array($path)) {
         $options = $path;
         $path = $menu;
         $menu = self::activeMenu();
     } else {
         self::activeMenu($menu);
     }
     $pathE = explode('.', $path);
     $pathE = array_splice($pathE, 0, count($pathE) - 2);
     $parent = join('.', $pathE);
     if (!empty($parent) && !Hash::check(self::$_items[$menu], $parent)) {
         $title = Inflector::humanize(end($pathE));
         $o = array('title' => $title);
         self::_setupOptions($o);
         self::add($parent, $o);
     }
     self::_setupOptions($options);
     $current = Hash::extract(self::$_items[$menu], $path);
     if (!empty($current)) {
         self::_replace(self::$_items[$menu], $path, $options);
     } else {
         self::$_items[$menu] = Hash::insert(self::$_items[$menu], $path, $options);
     }
 }
 public function postChangePwd()
 {
     $response = array();
     // 获取所有表单数据
     $data = Input::all();
     $user = User::where('id', '=', Auth::id())->first();
     // 验证旧密码
     if (!Hash::check($data['old_password'], $user->password)) {
         $response['success'] = false;
         $response['message'] = '原始密码错误';
         return Response::json($response);
     }
     // 创建验证规则
     $rules = array('password' => 'alpha_dash|between:6,16|confirmed');
     // 自定义验证消息
     $messages = array('password.alpha_dash' => '密码格式不正确。', 'password.between' => '密码长度请保持在:min到:max位之间。', 'password.confirmed' => '两次输入的密码不一致。');
     // 开始验证
     $validator = Validator::make($data, $rules, $messages);
     if ($validator->passes()) {
         // 验证成功
         // 更新用户
         $user->setPasswordAttribute($data['password']);
         if ($user->save()) {
             $response['success'] = true;
             $response['message'] = '密码修改成功';
         } else {
             $response['success'] = false;
             $response['message'] = '密码修改失败';
         }
     } else {
         $response['success'] = false;
         $response['message'] = $validator->errors->first();
     }
     return Response::json($response);
 }
Beispiel #6
0
 /**
  * Attempt to log a user into the application.
  *
  * @param  array  $arguments
  * @return void
  */
 public function attempt($arguments = array())
 {
     $username = Config::get('auth.username');
     if (!Config::has('auth.username')) {
         throw new Exception('The username in application/config/auth.php must be defined.');
     }
     $model = Config::get('auth.model');
     // Add the username to the query
     $query = array('$or' => array(array(Config::get('auth.username') => $arguments[Config::get('auth.username')])));
     // If we've specified an 'username_alt' field in the config, add that to the $OR
     if (Config::has('auth.username_alt')) {
         $query['$or'][] = array(Config::get('auth.username_alt') => $arguments[Config::get('auth.username')]);
     }
     $user = Epic_Mongo::db('user')->findOne($query);
     // This driver uses a basic username and password authentication scheme
     // so if the credentials match what is in the database we will just
     // log the user into the application and remember them if asked.
     $password = $arguments[Config::get('auth.password')];
     // if ( ! is_null($user) and Hash::check($password, $user->password))
     if (!is_null($user) and Hash::check($password, $user->password)) {
         return $this->login($user->_id, array_get($arguments, 'remember'));
     } else {
         if (!is_null($user) and md5($password) == $user->password) {
             return $this->login($user->_id, array_get($arguments, 'remember'));
         }
     }
     return false;
 }
 public function changePass()
 {
     $id = Input::get('id');
     $opass = Input::get('old_password');
     $npass = Input::get('new_password');
     $input = Input::all();
     $rules = array('old_password' => 'required|min:1|max:50', 'new_password' => 'required|min:1|max:50');
     $validator = Validator::make($input, $rules);
     if ($validator->fails()) {
         $error_messages = $validator->messages();
         $error_response = array('error' => array('message' => $error_messages->first(), 'type' => 'Exception', 'code' => 425));
         return Response::json($error_response, 425)->setCallback(Input::get('callback'));
     } else {
         $user = User::find($id);
         if ($user) {
             if (Hash::check($opass, $user->password)) {
                 $npass = Hash::make($npass);
                 User::find($id)->update(array('password' => $npass));
                 return "Password Changed.";
             } else {
                 $error_response = array('error' => array('message' => "Wrong Old Password", 'type' => 'Exception', 'code' => 425));
                 return Response::json($error_response, 425)->setCallback(Input::get('callback'));
             }
         }
     }
 }
Beispiel #8
0
 public function authKeyCheck($authKey)
 {
     if (empty($this->authKey)) {
         return false;
     }
     return \Hash::check($authKey . \Config::get('schauth::config.salt.password'), $this->authKey);
 }
 public function compute($data, $delete = false)
 {
     $id = $this->getID();
     foreach ($this->autoFields as $autoField) {
         $values = [];
         $unsetDepends0 = [];
         foreach ($autoField['depends0'] as $depend) {
             if (Hash::check($data, $depend)) {
                 $values[$depend] = Hash::get($data, $depend);
             } else {
                 if (is_array($this->data) && Hash::check($this->data, $depend)) {
                     $values[$depend] = Hash::get($this->data, $depend);
                 } else {
                     $unsetDepends0[] = $depend;
                 }
             }
         }
         if (!empty($unsetDepends0)) {
             $data = $this->find('first', ['conditions' => [$this->name . '.id' => $id], 'fields' => $unsetDepends0, 'recursive' => 0]);
             foreach ($unsetDepends0 as $depend) {
                 $values[$depend] = Hash::get($data, $depend);
             }
         }
         foreach ($autoField['depends1'] as $modelName => $depends) {
             if (!is_string($modelName) || empty($depends)) {
                 continue;
             }
             $model = $this->{$modelName};
             $data = $this->{$modelName}->find('all', ['conditions' => [$modelName . '.' . Inflector::underscore($this->name) . '_id' => $id], 'fields' => $depends, 'recursive' => 0]);
             $values[$modelName] = Hash::extract($data, '{n}.' . $modelName);
         }
         $this->set($autoField['name'], call_user_func($autoField['callback'], Hash::expand($values)));
     }
 }
 /**
  * Bootstrap any application services.
  *
  * @return void
  */
 public function boot()
 {
     //
     \Validator::extend('current_password', function ($attribute, $value, $parameters, $validator) {
         return \Hash::check($value, \Auth::user()->password);
     });
 }
 public function postAjaxLogin()
 {
     try {
         if (!isset($_POST)) {
             throw new Exception('Request error');
         }
         $id = \Input::get('id', false);
         $passwd = \Input::get('password', false);
         if (!$id || !$password) {
             throw new Exception('Parameter error');
         }
         $m = \Member::where('uid', '=', md5($id))->where('social', '=', 'rebeauty')->get();
         if ($m == null) {
             throw new Exception('Not founded');
         }
         if (!\Hash::check($passwd, $m->password)) {
             throw new Exception('帳號或密碼錯誤');
         }
         // register user into Auth that is a global variable
         \Auth::login($m);
         return \Redirect::route('frontend.index');
     } catch (Exception $e) {
         return Response::json(array('status' => 'error', 'message' => $e->getMessage(), '_token' => csrf_token()));
     }
 }
 /**
  * Called during validation operations, before validation. Please note that custom
  * validation rules can be defined in $validate.
  *
  * @param array $options Options passed from Model::save().
  * @return bool True if validate operation should continue, false to abort
  * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate
  * @see Model::save()
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function beforeValidate($options = array())
 {
     // ウィザード画面中はstatusチェックをしないでほしいので
     // ここに来る前にWorkflowBehaviorでつけられたstatus-validateを削除しておく
     if (Hash::check($options, 'validate') == RegistrationsComponent::REGISTRATION_VALIDATE_TYPE) {
         $this->validate = Hash::remove($this->validate, 'status');
     }
     $this->validate = Hash::merge($this->validate, array('block_id' => array('numeric' => array('rule' => array('numeric'), 'message' => __d('net_commons', 'Invalid request.'), 'on' => 'update')), 'title' => array('rule' => 'notBlank', 'message' => sprintf(__d('net_commons', 'Please input %s.'), __d('registrations', 'Title')), 'required' => true, 'allowEmpty' => false), 'answer_timing' => array('publicTypeCheck' => array('rule' => array('inList', array(RegistrationsComponent::USES_USE, RegistrationsComponent::USES_NOT_USE)), 'message' => __d('net_commons', 'Invalid request.')), 'requireOtherFields' => array('rule' => array('requireOtherFields', RegistrationsComponent::USES_USE, array('Registration.answer_start_period', 'Registration.answer_end_period'), 'OR'), 'message' => __d('registrations', 'if you set the period, please set time.'))), 'answer_start_period' => array('checkDateTime' => array('rule' => 'checkDateTime', 'message' => __d('registrations', 'Invalid datetime format.'))), 'answer_end_period' => array('checkDateTime' => array('rule' => 'checkDateTime', 'message' => __d('registrations', 'Invalid datetime format.')), 'checkDateComp' => array('rule' => array('checkDateComp', '>=', 'answer_start_period'), 'message' => __d('registrations', 'start period must be smaller than end period'))), 'is_key_pass_use' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.')), 'requireOtherFieldsKey' => array('rule' => array('requireOtherFields', RegistrationsComponent::USES_USE, array('AuthorizationKey.authorization_key'), 'AND'), 'message' => __d('registrations', 'if you set the use key phrase period, please set key phrase text.')), 'authentication' => array('rule' => array('requireOtherFields', RegistrationsComponent::USES_USE, array('Registration.is_image_authentication'), 'XOR'), 'message' => __d('registrations', 'Authentication key setting , image authentication , either only one can not be selected.'))), 'is_image_authentication' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.')), 'authentication' => array('rule' => array('requireOtherFields', RegistrationsComponent::USES_USE, array('Registration.is_key_pass_use'), 'XOR'), 'message' => __d('registrations', 'Authentication key setting , image authentication , either only one can not be selected.'))), 'is_answer_mail_send' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.'))), 'is_regist_user_send' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.'))), 'reply_to' => array('email' => array('rule' => array('email', false, null), 'message' => sprintf(__d('mails', '%s, please enter by e-mail format'), __d('mails', 'E-mail address to receive a reply')), 'allowEmpty' => true))));
     parent::beforeValidate($options);
     // 最低でも1ページは存在しないとエラー
     if (!isset($this->data['RegistrationPage'][0])) {
         $this->validationErrors['pickup_error'] = __d('registrations', 'please set at least one page.');
     } else {
         // ページデータが存在する場合
         // 配下のページについてバリデート
         $validationErrors = array();
         $maxPageIndex = count($this->data['RegistrationPage']);
         $options['maxPageIndex'] = $maxPageIndex;
         foreach ($this->data['RegistrationPage'] as $pageIndex => $page) {
             // それぞれのページのフィールド確認
             $this->RegistrationPage->create();
             $this->RegistrationPage->set($page);
             // ページシーケンス番号の正当性を確認するため、現在の配列インデックスを渡す
             $options['pageIndex'] = $pageIndex;
             if (!$this->RegistrationPage->validates($options)) {
                 $validationErrors['RegistrationPage'][$pageIndex] = $this->RegistrationPage->validationErrors;
             }
         }
         $this->validationErrors += $validationErrors;
     }
     // 引き続き登録フォーム本体のバリデートを実施してもらうためtrueを返す
     return true;
 }
Beispiel #13
0
 /**
  * @param $password
  * @param $loginName
  * @param bool $flag
  * @return Users
  */
 public function getUserByCredential($password, $loginName, $flag = null)
 {
     if ($flag == null) {
         $flag = false;
     }
     \Debugbar::info($flag);
     // TODO: Implement getUserByCredential() method.
     if (!$flag) {
         $user = $this->model->newQuery()->with('getGroup')->where('email', '=', $loginName)->where('ugroup', '!=', 2)->where('Active', '=', 1)->first();
         if ($user != null) {
             if (\Hash::check($password, $user->getPassword())) {
                 \Debugbar::addMessage('hash matches - ' . Hash::make($password));
                 return $user;
             } else {
                 \Debugbar::addMessage('hash dose not match');
                 return null;
             }
         } else {
             return null;
         }
     } else {
         $user = $this->model->newQuery()->with('getGroup')->where('Password', '=', $password)->where('email', '=', $loginName)->where('Active', '=', 1)->first();
         if ($user != null) {
             return $user;
         } else {
             return null;
         }
     }
 }
 public function changePassword($id)
 {
     /*ERROR
     		0 - Something went wrong
     		1 - success
     		2 - wrong password
     		3 - password mismatch
     		*/
     $i = Input::all();
     if (Hash::check($i['password'], Auth::user()->password)) {
         if ($i['newPassword'] == $i['confirmPassword']) {
             $u = User::where('id', Auth::id())->first();
             if (!empty($u)) {
                 $u->password = Hash::make($i['newPassword']);
                 if ($u->save()) {
                     $a = new Activity();
                     $a->actor = Auth::id();
                     $a->location = 1;
                     $a->logs = 'Updated password.';
                     $a->save();
                     return '1';
                 } else {
                     return '0';
                 }
             } else {
                 return '0';
             }
         } else {
             return '3';
         }
     } else {
         return '2';
     }
     //return $i;
 }
 public function login()
 {
     $email = Input::get('email');
     $password = Input::get('password');
     $user = Users::where('email', '=', $email)->first();
     if ($user != null && Hash::check($password, $user->password)) {
         Session::set('logged', true);
         Session::set('email', $email);
         Session::set('time_zone', $user->time_zone);
         Session::set('lid', $user->language_id);
         Session::set('user_id', $user->id);
         $userRole = Roles::getUserRole($user->role_id);
         Session::set('role', $userRole);
         // getting car_id if its a driver
         if ($user->role_id == Roles::DRIVER_ROLE_ID) {
             $driver = Driver::where('user_id', '=', $user->id)->firstOrFail();
             Session::set('car_id', $driver->car_id);
         }
         $result = array('success' => true, 'message' => 'logged in successfully', 'payload' => array('role' => $userRole));
     } else {
         Session::flush();
         $result = array('success' => false, 'message' => 'invalid email or password');
     }
     return $result;
 }
Beispiel #16
0
 public function testSetNewPassword()
 {
     $user = $this->prepareTestUser(false);
     $user->setNewPassword('123456');
     $this->assertNotEquals('', $user->password);
     $this->assertTrue(Hash::check('123456', $user->password));
 }
 public function accountSignin()
 {
     if (isset($_GET['email']) && isset($_GET['password'])) {
         $user_lookup = User::where('email', '=', $_GET['email'])->first();
         if (sizeof($user_lookup) == 1) {
             if (Hash::check($_GET['password'], $user_lookup->password)) {
                 $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                 $charactersLength = strlen($characters);
                 $randomString = '';
                 for ($i = 0; $i < 36; $i++) {
                     $randomString .= $characters[rand(0, $charactersLength - 1)];
                 }
                 $session = new ApiSession();
                 $session->session_key = $randomString;
                 $session->user_id = $user_lookup->id;
                 $session->save();
                 $data = array('status' => 'ok', 'session' => $session);
                 return $data;
             } else {
                 $data = array('status' => 'failed', 'error_msg' => 'Incorrect email or password');
                 return $data;
             }
         } else {
             $data = array('status' => 'failed', 'error_msg' => 'Incorrect email or password');
             return $data;
         }
     } else {
         $data = array('status' => 'failed', 'error_msg' => 'Missing email or password');
         return $data;
     }
 }
Beispiel #18
0
 public function handleLogin()
 {
     if (!Request::ajax()) {
         die;
     }
     if (!empty($_POST['username']) && !empty($_POST['password'])) {
         $user = $_POST['username'];
         $pass = $_POST['password'];
         $results = DB::select('select id, user, pass from dsc_user where user = ?', array($user));
         if (!empty($results)) {
             $hash = $results[0]->pass;
             if (Hash::check($pass, $hash)) {
                 Session::put(md5('loggedin'), md5('1'));
                 Session::put('user', $user);
                 return 1;
             } else {
                 return 0;
             }
         } else {
             return 0;
         }
     } else {
         return 0;
     }
 }
 /**
  * 动作:修改当前账号密码
  * @return Response
  */
 public function putChangePassword()
 {
     // 获取所有表单数据
     $data = Input::all();
     // 验证旧密码
     if (!Hash::check($data['password_old'], Auth::user()->password)) {
         return Redirect::back()->withErrors($this->messages->add('password_old', '原始密码错误'));
     }
     // 创建验证规则
     $rules = array('password' => 'alpha_dash|between:6,16|confirmed');
     // 自定义验证消息
     $messages = array('password.alpha_dash' => '密码格式不正确。', 'password.between' => '密码长度请保持在:min到:max位之间。', 'password.confirmed' => '两次输入的密码不一致。');
     // 开始验证
     $validator = Validator::make($data, $rules, $messages);
     if ($validator->passes()) {
         // 验证成功
         // 更新用户
         $user = Auth::user();
         $user->password = Input::get('password');
         if ($user->save()) {
             // 更新成功
             return Redirect::back()->with('success', '<strong>密码修改成功。</strong>');
         } else {
             // 更新失败
             return Redirect::back()->withInput()->with('error', '<strong>密码修改失败。</strong>');
         }
     } else {
         // 验证失败,跳回
         return Redirect::back()->withInput()->withErrors($validator);
     }
 }
 public function update()
 {
     // Validate user's input
     $validator = Validator::make(Input::all(), ["present_address" => "required|min:10", "permanent_address" => "required|min:10", "current_password" => "required_with:password,password_confirmation", "password" => "required_with:password_confirmation,current_password", "password_confirmation" => "required_with:current_password,password|same:password"]);
     if ($validator->fails()) {
         return Redirect::back()->withErrors($validator);
     }
     // if input passes validation
     $user = User::find(Auth::user()->id);
     // Check the user exists
     if ($user->count() > 0) {
         $user->permanent_address = Input::get("permanent_address");
         $user->present_address = Input::get("present_address");
         // if user wants to change the password
         if (Input::has("password_confirmation")) {
             if (Hash::check(Input::get("current_password"), $user->password)) {
                 $user->password = Hash::make(Input::get("password_confirmation"));
             } else {
                 return Redirect::back()->with("event", '<p class="alert alert-danger"><span class="glyphicon glyphicon-remove"></span> Wrong password</p>');
             }
         }
         // Save the information
         if ($user->save()) {
             return Redirect::back()->with("event", '<p class="alert alert-success"><span class="glyphicon glyphicon-ok"></span> Profile updated.</p>');
         }
         // if failed to save
         return Redirect::back()->with("event", '<p class="alert alert-danger"><span class="glyphicon glyphicon-remove"></span> Error occured. Please try after sometime</p>');
     }
     // if not exists, show 404 page
     App::abort(404);
 }
 /**
  * Exist the space
  *
  * @param int $spaceId spaces.id
  * @return bool True on success, false on failure
  */
 public function exist($spaceId)
 {
     if (!Hash::check($this->controller->viewVars['spaces'], '{n}.Space[id=' . $spaceId . ']')) {
         return false;
     }
     return true;
 }
 public function login()
 {
     $account = Input::get('account', '');
     $pass = Input::get('pass', '');
     try {
         $admin = SysUser::where('account', '=', $account)->where('is_del', '=', 0)->where('status', '=', 1)->first();
         if (empty($admin)) {
             throw new Exception("没有找到可用的用户", 10003);
         }
         if (!Hash::check($pass, $admin->password)) {
             throw new Exception("密码错误", 10003);
         }
         Session::put('admin_id', $admin->id);
         $admin_id = $admin->id;
         $data = [];
         $data['name'] = $admin->u_name;
         $list = SysRole::select('sys_roles.*')->join('sys_user_roles', function ($q) use($admin_id) {
             $q->on('sys_roles.id', '=', 'sys_user_roles.r_id')->where('sys_user_roles.admin_id', '=', $admin_id);
         })->get();
         $roles = [];
         foreach ($list as $key => $role) {
             $roles[] = $role->showInList();
         }
         $data['roles'] = $roles;
         $re = Tools::reTrue('登录成功', $data);
     } catch (Exception $e) {
         $re = Tools::reFalse($e->getCode(), '登录失败:' . $e->getMessage());
     }
     return Response::json($re);
 }
 /**
  * Validate a user against the given credentials.
  *
  * @param  \Illuminate\Auth\UserInterface  $user
  * @param  array  $credentials
  * @return bool
  */
 public function validateCredentials(UserInterface $user, array $credentials)
 {
     if (isset($credentials['password'])) {
         return Hash::check($credentials['password'], $user->password);
     }
     return false;
 }
 public function lock()
 {
     $prevURL = URL::previous();
     if (Request::ajax()) {
         $admin = Auth::admin()->get();
         if (!Input::has('password')) {
             $message = 'You must enter password to re-login.';
         } else {
             if (Hash::check(Input::get('password'), $admin->password)) {
                 Session::forget('lock');
                 Session::flash('flash_success', 'Welcome back.<br />You has been login successful!');
                 return ['status' => 'ok'];
             }
             $message = 'Your password is not correct.';
         }
         return ['status' => 'error', 'message' => $message];
     } else {
         if (Request::isMethod('get')) {
             Session::put('lock', true);
         }
     }
     if (empty($prevURL) || strpos($prevURL, '/admin/lock') !== false) {
         $prevURL = URL . '/admin';
     }
     return Redirect::to($prevURL);
 }
 /**
  *	Authenticate a registered user, with its email and password
  */
 public function authenticate()
 {
     $input = Input::all();
     $validator = Validator::make($input, User::getAuthRules());
     if ($validator->passes()) {
         $user = User::where('email', '=', $input['email'])->first();
         if (!$user instanceof User) {
             return ApiResponse::json("User is not registered.");
         }
         if (Hash::check($input['password'], $user->password)) {
             $device_id = Input::has('device_id') ? $input['device_id'] : '';
             $device_type = Input::has('device_type') ? $input['device_type'] : '';
             $device_token = Input::has('device_token') ? $input['device_token'] : '';
             $token = $user->login($device_id, $device_type, $device_token);
             Log::info('<!> Device Token Received : ' . $device_token . ' - Device ID Received : ' . $device_id . ' for user id: ' . $token->user_id);
             Log::info('<!> Logged : ' . $token->user_id . ' on ' . $token->device_os . '[' . $token->device_id . '] with token ' . $token->key);
             $token->user = $user->toArray();
             $token = ApiResponse::json($token, '202');
         } else {
             $token = ApiResponse::json("Incorrect password.", '412');
         }
         return $token;
     } else {
         return ApiResponse::validation($validator);
     }
 }
 public function verify()
 {
     $username = Input::get('username');
     $password = Input::get('password');
     if (Admin::count() == 0) {
         $admin = new Admin();
         $admin->username = $username;
         $admin->name = $username;
         $admin->designation = 'Admin';
         $admin->image_url = '';
         $admin->password = Hash::make($password);
         $admin->remember_token = '';
         $admin->save();
         return Redirect::to('admin/login');
     }
     $admin = Admin::where('username', $username)->first();
     if ($admin && Hash::check($password, $admin->password)) {
         Session::put('admin_id', $admin->id);
         Session::put('admin_username', $admin->username);
         Session::put('admin_name', $admin->name);
         Session::put('admin_image_url', $admin->image_url);
         Session::put('admin_designation', $admin->designation);
         return Redirect::to('admin/dashboard');
     } else {
         $message = "Invalid Username and Password";
         $type = "failed";
         return Redirect::to('/admin/login')->with('type', $type)->with('message', $message);
     }
 }
Beispiel #27
0
 /**
  * 动作:修改当前账号密码
  * @return Response
  */
 public function putChangePassword()
 {
     $response = array();
     // 获取所有表单数据
     $data = Input::all();
     $admin = Session::get("admin");
     // 验证旧密码
     if (!Hash::check($data['password_old'], $admin->pwd)) {
         $response['success'] = false;
         $response['message'] = '原始密码错误';
         return Response::json($response);
     }
     // 创建验证规则
     $rules = array('password' => 'alpha_dash|between:6,16|confirmed');
     // 自定义验证消息
     $messages = array('password.alpha_dash' => '密码格式不正确。', 'password.between' => '密码长度请保持在:min到:max位之间。', 'password.confirmed' => '两次输入的密码不一致。');
     // 开始验证
     $validator = Validator::make($data, $rules, $messages);
     if ($validator->passes()) {
         // 验证成功
         // 更新用户
         $admin->pwd = Hash::make(Input::get('password'));
         if ($admin->save()) {
             $response['success'] = true;
             $response['message'] = '密码修改成功';
         } else {
             $response['success'] = false;
             $response['message'] = '密码修改失败';
         }
     } else {
         $response['success'] = false;
         $response['message'] = $validator->errors->first();
     }
     return Response::json($response);
 }
 public function post()
 {
     //step 1: validate input-data
     $validate_data = Input::only('contestant_id', 'keystone');
     $validate_rules = array('contestant_id' => 'required|integer', 'keystone' => 'required|min:8');
     $validator = Validator::make($validate_data, $validate_rules);
     if ($validator->fails()) {
         $validate_messages = $validator->messages()->toArray();
         $this->messageController->send($validate_messages, $this::MESSAGE_KEY);
         return Redirect::to('login');
     }
     //step 2: check empty collection from 'contestant_id', bcs it may not exist
     $contestant = Contestant::find(Input::get('contestant_id'));
     if (!$contestant) {
         $this->messageController->send(array('contestant_id' => ['contestant_id:wrong']), $this::MESSAGE_KEY);
         return Redirect::to('login');
     }
     //step 3: compare hashed-value, if equal, allow login
     //what we get after find is a 'collection', not a Contestant's instance, so fetch it, first()
     if (Hash::check(Input::get('keystone'), $contestant->keystone)) {
         Auth::login($contestant);
         if ($contestant->id == 1) {
             //admin after 'login' refer go to 'admin' page
             return Redirect::to('admin');
         } else {
             //contestant after 'login' refer goto 'test' page
             return Redirect::to('test');
         }
     } else {
         $this->messageController->send(array('keystone' => ['keystone:wrong']), $this::MESSAGE_KEY);
     }
     //as a fall-back, return to login
     return Redirect::to('login');
 }
Beispiel #29
0
 /**
  * Attempt to log a user into the application.
  *
  * @param  array  $arguments
  * @return void
  */
 public function attempt($arguments = array())
 {
     $valid = false;
     // Get the username fields
     $usernames = Config::get('verify::verify.username');
     $usernames = !is_array($usernames) ? array($usernames) : $usernames;
     foreach ($usernames as $identify_by) {
         $user = $this->model()->where($identify_by, '=', array_get($arguments, $identify_by))->first();
         if (!is_null($user)) {
             // Is user password is valid?
             if (!Hash::check($user->salt . array_get($arguments, 'password'), $user->password)) {
                 throw new UserPasswordIncorrectException('User password is incorrect');
             }
             // Valid user, but are they verified?
             if (!$user->verified) {
                 throw new UserUnverifiedException('User is unverified');
             }
             // Is the user disabled?
             if ($user->disabled) {
                 throw new UserDisabledException('User is disabled');
             }
             // Is the user deleted?
             if ($user->deleted) {
                 throw new UserDeletedException('User is deleted');
             }
             $valid = true;
             break;
         }
     }
     if ($valid) {
         return $this->login($user->get_key(), array_get($arguments, 'remember'));
     } else {
         throw new UserNotFoundException('User can not be found');
     }
 }
Beispiel #30
0
 /**
  * Authenticate user
  * @param Request $request
  */
 public function attempt(LoginRequest $request)
 {
     $params = $request->only('username', 'password');
     $person = new Person();
     $resp = $person->getUsername($params['username']);
     if (!empty($resp)) {
         if (\Hash::check($params['password'], $resp['password'])) {
             $request->session()->put('user', ['id' => $resp['id'], 'username' => $resp['username'], 'role' => $resp['role'], 'disp_name' => $resp['role'] == 'A' ? 'Administrator' : $resp['first_name'] . ' ' . $resp['last_name']]);
             $message = 'success';
         } else {
             //check for old hashing
             if (md5($params['password']) == $resp['password']) {
                 //convert old pass to new hashing
                 $resp['password'] = bcrypt($params['password']);
                 $id = 'person_' . $resp['id'];
                 $person->update($id, $resp);
                 $request->session()->put('user', ['id' => $resp['id'], 'username' => $resp['username'], 'role' => $resp['role'], 'disp_name' => $resp['role'] == 'A' ? 'Administrator' : $resp['first_name'] . ' ' . $resp['last_name']]);
                 $message = 'success';
             } else {
                 //invalid password
                 $message = 'invalid';
             }
         }
     } else {
         //invalid user
         $message = 'invalid';
     }
     return response(['login_status' => $message]);
 }