dongzhanlu8890 2015-12-08 17:05 采纳率: 0%
浏览 37

覆盖FOSUserBundle中的登录控制器(Symfony2)

I'm currently migrating from a WordPress to a Symfony2 website.

I imported all my WP user on Symfony2 but now I'm looking for a way to make additional checks when the user tries to log in (typically check if the user was imported from WP and check his old password).

What's the best way to add some checks on the User authentication ? (login_check on fosuserbundle).

I simply try to override the SecurityController, but it doesn't work as the login doesn't seem to be made here.

Thanks for your help.

Edit: I need to add my check during the login process, not after. During the login, if the user comes from WordPress, I want to check if the password he provides is the same as his old WordPress password (that is stored in the DB too).

  • 写回答

1条回答 默认 最新

  • dswqw66280 2015-12-09 07:13
    关注

    I finaly found a solution, but not sure it's the best way to do the stuff.

    I added a listener when the login failed and check if it's a user from WordPress.

    Now I'm looking for a solution to handle the "remember me" checkbox because the user is a authenticate programmatically. Here is the code :

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        $username = $request->request->get('_username');
        $password = $request->request->get('_password');
    
        $user = $this->doctrine->getRepository('AppBundle:User')->findOneByUsername($username);
    
        if ($user instanceof User && $user->getFromWordpress() == true) {
    
            //The class use by WordPress to check / encode passwords
            $hasher = new PasswordHash(8, TRUE);    
    
            //User provide the right password
            if ($hasher->CheckPassword($password, $user->getWordpressPassword())){
    
                //Programmatically authenticate the user
                $token = new UsernamePasswordToken($user, $user->getPassword(), "main", $user->getRoles());
                $this->tokenStorage->setToken($token);
                $event = new InteractiveLoginEvent($request, $token);
                $this->eventDispacher->dispatch("security.interactive_login", $event);
    
                //Set the password with the Symfony2 encoder
                $encoder = $this->encoderFactory->getEncoder($user);
                $password = $encoder->encodePassword($password, $user->getSalt());
                $user->setPassword($password);
                $user->setFromWordpress(false);
                $this->doctrine->getManager()->persist($user);
                $this->doctrine->getManager()->flush();
    
                //Finnaly send login ok response
                return $this->onAuthenticationSuccess($request, $token);
            }
        }   
    
        //Login failed code ...
        //.....
    }
    
    评论

报告相同问题?