如何在zf2中使用户名不区分大小写 [英] How to make username case insensitive in zf2

查看:70
本文介绍了如何在zf2中使用户名不区分大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用zf2身份验证对用户进行身份验证.我在用户表中保存了Harib作为用户名,但是如果我使用用户名Harib则接受它,或者如果我使用harib则不接受,我想删除大小写用户名的敏感性,这样Harib或harib都可以访问该怎么解决?

I used zf2 authentication for authenticate user in my project.I saved Harib in my user table as user name but if i use my user name Harib then its accept or if i use harib then its not accept,i want to remove case sensitivity of user name so both Harib or harib access how i fix this?

这是我的代码:

public function loginAction()
{
    $this->layout('layout/login-layout.phtml');
    $login_error = false;
    $loginForm = new LoginForm();
    $form_elements = json_encode($loginForm->form_elements);
    if ($this->request->isPost()) {
        $post = $this->request->getPost();
        $loginForm->setData($post);
        if ($loginForm->isValid()) {
            $hashed_string = '';
            if(
                array_key_exists('hashed_input' , $post) &&
                $post['hashed_input'] != '' &&
                strpos(urldecode($this->params('redirect')) , 'programdetailrequest') !== false
            ) {
                $hashed_string = $post['hashed_input'];
            }
            $data = $loginForm->getData();
            $authService = $this->getServiceLocator()->get('doctrine.authenticationservice.odm_default');
            $adapter = $authService->getAdapter();
            $adapter->setIdentityValue($data['username']);
            $adapter->setCredentialValue(md5($data['password']));
            $authResult = $authService->authenticate();
            if($authResult->isValid()){
                $identity = $authResult->getIdentity();
                if( is_object($identity) && method_exists($identity, 'getData') ){
                    $user_data = $identity->getData();
                    $authService->getStorage()->write($identity);
                    // for remeber checkbox
                    if ($post['rememberme']) {
                        $token = new UserToken();
                        $dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
                        //if same user already running from other browser then remove previous token.
                        $check_token = $dm->getRepository('Admin\Document\UserToken')->findOneBy(array( "user_id.id" => $user_data['id'] ));
                        if (is_object($check_token) && !is_null($check_token)) {
                            $remove_token = $dm->createQueryBuilder('Admin\Document\UserToken')
                                ->remove()
                                ->field('id')->equals($check_token->id)
                                ->getQuery()->execute();
                        }
                        //create token
                        $user = $dm->getRepository('Admin\Document\User')->findOneBy(array( "id" => $user_data['id'] ));
                        $token->setProperty('user_id', $user);
                        $token->setProperty('dataentered', new \MongoDate());
                        $dm->persist($token);
                        $dm->flush($token);
                        //create cookie
                        if(is_object($token) && property_exists($token, 'id')){
                            $time = time() + (60 * 60 * 24 * 30); // 1 month
                            setcookie('token', $token->getProperty('id'), $time, '/');
                        }
                    }
                    if ($user_data['user_type'] == 'onlinemarketer') {
                        $this->redirect()->toRoute('admin_program_meta');
                    } elseif ($user_data['user_type'] == 'bucharestofficemanager') {
                        $this->redirect()->toRoute('admin_program_detail_request');
                    } else {
                        if ($this->params('redirect') && urldecode($this->params('redirect')) !== '/logout/') {
                            $server_url = $this->getRequest()->getUri()->getScheme() . '://' . $this->getRequest()->getUri()->getHost().urldecode($this->params('redirect') . $hashed_string);
                            return $this->redirect()->toUrl($server_url);
                        }
                        return $this->redirect()->toRoute('admin_index');
                    }
                }
            } else {
                $identity = false;
                $login_error = true;
            }
        }
    }
    return new ViewModel(array(
            'loginForm' => $loginForm,
            'form_elements' =>$form_elements,
            'login_error' => $login_error,
    ));
}

这是我的登录表单代码:

and here is my login form code:

<?php
namespace Admin\Form;

use Zend\Form\Form;
use Zend\Form\Element;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;

class LoginForm extends Form implements InputFilterAwareInterface
{
protected $inputFilter;
public $form_elements = array(
    array(
        'name' => 'username',
        'attributes' => array(
            'id' => 'username',
            'type'  => 'text',
            'error_msg' => 'Enter Valid Username',
            'data-parsley-required' => 'true',
            'data-parsley-pattern' => '^[a-zA-Z0-9_\.\-]{1,50}$',
            'data-parsley-trigger' => 'change'
        ),
        'options' => array(
            'label' => 'User Name'
        ), 
        'validation' => array(
            'required'=>true,
            'filters'=> array(
                array('name'=>'StripTags'),
                array('name'=>'StringTrim')
            ),
            'validators'=>array(
                array('name'=>'Regex',
                    'options'=> array(
                        'pattern' => '/^[a-z0-9_.-]{1,50}+$/', // contain only a to z 0 to 9 underscore, hypen and space, min 1 max 50
                        'pattern_js' => '^[a-zA-Z0-9_\.\-]{1,50}$' 
                    )
                )
            )
        )
    ),
    array(
        'name' => 'password',
        'attributes' => array(
            'id' => 'password',
            'type'  => 'password',
            'error_msg' => 'Enter Valid Password',
            'data-parsley-required' => 'true',
            'data-parsley-pattern' => '^[a-zA-Z0-9_\.\-]{6,25}$',
            'data-parsley-trigger' => 'change'
        ),
        'options' => array(
            'label' => 'Password'
        ), 
        'validation' => array(
            'required' => true,
            'filters'=> array(
                array('name'=>'StripTags'),
                array('name'=>'StringTrim')
            ),
            'validators'=>array(
                array('name'=>'Regex',
                    'options'=> array(
                        'pattern' => '/^[a-z0-9_.-]{6,25}+$/', // contain only a to z 0 to 9 underscore, hypen and space, min 1 max 50
                        'pattern_js' => '^[a-zA-Z0-9_\.\-]{6,25}$' 
                    )
                )
            )
        )
    ),
    array(
        'name' => 'hashed_input',
        'attributes' => array(
            'type'  => 'hidden',
            'id' => 'hashed_input',
            'value' => ''
        )
    ),
    array(
        'name' => 'rememberme',
        'attributes' => array(
            'value' => 1,
            'id' => 'rememberme',
            'type' => 'Checkbox'
        ),
        'options' => array(
            'label' => 'Remember Me',
            'use_hidden_element' => false,
        )
    ),
    array(
        'name' => 'submit',
        'attributes' => array(
            'type'  => 'submit',
            'value' => 'Log in',
            'id' => 'submitbutton'
        )
    )
);
public function __construct()
{
    parent::__construct('user');
    $this->setAttribute('method', 'post');
    $this->setAttribute('data-parsley-validate', '');
    $this->setAttribute('data-elements', json_encode($this->form_elements));
    $this->setAttribute('autocomplete', 'off');
    for($i=0;$i<count($this->form_elements);$i++){
        $elements=$this->form_elements[$i];
        $this->add($elements);
    }
}
public function getInputFilter($action=false)
{
    if(!$this->inputFilter){
        $inputFilter = new InputFilter();
        $factory = new InputFactory();
        for($i=0;$i<count($this->form_elements);$i++){
            if(array_key_exists('validation',$this->form_elements[$i])){    
                $this->form_elements[$i]['validation']['name']=$this->form_elements[$i]['name'];
                $inputFilter->add($factory->createInput( $this->form_elements[$i]['validation'] ));
            }
        }
        $this->inputFilter = $inputFilter;
    }
    return $this->inputFilter;
}
}

我们如何删除用户名的区分大小写,以便同时接受Harib或harib?

how we remove case sensitivity of user name so both Harib or harib accepted?

推荐答案

由于您使用的是MongoDB,因此可以使用正则表达式从数据库中获取用户名.

Since you're using MongoDB, you could use a regex to get the user name from the database.

建议1:

在您的示例中,将是:

db.stuff.find( { foo: /^bar$/i } );

建议2:

您可以使用$ options => i进行不区分大小写的搜索.给出一些字符串匹配所需的示例.

You can Use $options => i for case insensitive search. Giving some possible examples required for string match.

不区分大小写的字符串

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})

包含字符串

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

以字符串开头

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})

以字符串结尾

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})

不包含字符串

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})

有关MongoDb中正则表达式的更多信息,请访问: https://docs.mongodb.com/manual/reference/operator/query/regex/index.html

More about regex in MongoDb here: https://docs.mongodb.com/manual/reference/operator/query/regex/index.html

这篇关于如何在zf2中使用户名不区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆