TanGio
TanGio

Reputation: 766

Verify if user is authenticated in symfony2

I tried to create a simple login application in symfony2 and I don't understand a thing. My routing file :

shop_show_login_page:
path: /login
defaults: { _controller: ShopDesktopBundle:User:loginPage }

shop_login_user:
path: /loginUser
defaults: { _controller: ShopDesktopBundle:User:loginCheck }

My controller with this 2 methods :

public function loginPageAction(){
    return $this->render('ShopDesktopBundle:User:loginPage.html.twig');
}
public function loginCheckAction(Request $request){
    $request = $this->get('request');
    $password = $request->request->get('password');
    $login    = $request->request->get('username');
    $em = $this->getDoctrine()->getEntityManager();
    $repository = $em->getRepository('ShopDesktopBundle:Customer');
    $user = $repository->findOneBy(array('customer_login'=> $login, 'customer_password'=> $password));
    if($user){
        return $this->redirect($this->generateUrl('shop_desktop_homepage'));
    }else{
        return $this->render('ShopDesktopBundle:User:loginPage.html.twig',array('message_failed' => 'Error'));
    }
}

My form in view :

 <form action="{{ path('shop_login_user') }}" method="post">
                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="fa fa-user"></i></span>
                        <input type="text" class="form-control" placeholder="Username" name="username">
                    </div>
                </div>
                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="fa fa-lock"></i></span>
                        <input type="text" class="form-control" placeholder="Password" name="password">
                    </div>
                </div>
                <div class="form-group">
                    <button type="submit" class="button">Autentificare</button>
                </div>
            </form>

This system on login work fine but the problem is in the layout.html.twig:

{% if app.user %}
     <p>Test</p>
{% elseif not app.user %}
     <span><a href="{{ path('shop_show_login_page') }}" style="color: #ffffff;">Login / Register</a></span>
{% endif %}

My security.yml:

security:
# http://symfony.com/doc/current/book/security.html#encoding-the-user-s-password
encoders:
    Symfony\Component\Security\Core\User\User: plaintext

# http://symfony.com/doc/current/book/security.html#hierarchical-roles
role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
    in_memory:
        memory:
            users:
                user:  { password: userpass, roles: [ 'ROLE_USER' ] }
                admin: { password: adminpass, roles: [ 'ROLE_ADMIN' ] }

# the main part of the security, where you can set up firewalls
# for specific sections of your app
firewalls:
    # disables authentication for assets and the profiler, adapt it according to your needs
    secured_area:
        pattern:    ^/
        form_login:
            check_path: shop_login_user
            login_path: shop_show_login_page
        logout:
            path:   _demo_logout
            target: _demo
        #anonymous: ~
        #http_basic:
        #    realm: "Secured Demo Area"

# with these settings you can restrict or allow access for different parts
# of your application based on roles, ip, host or methods
# http://symfony.com/doc/current/cookbook/security/access_control.html
access_control:
    #- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }

So I want to see in the page "Test" if user is authentificated with succes and Login/Register if authentification failed. I tried with "if app.user" but I don't understand the principle.

Upvotes: 3

Views: 1406

Answers (1)

Artamiel
Artamiel

Reputation: 3762

There are several ways to check if user is authenticated.

One would be with app.user as you tried, like this:

{% if app.user is not empty %}

That will check if your user object is populated with data.

You can also use is_granted().

{% if is_granted('IS_AUTHENTICATED_FULLY') %}

- Update -

The error you provided in comments could be caused by the fact that you try to use the is_granted function when you're not behind a firewall. If that's the case you can first check if there is a security token before calling for is_granted with if app.security.token is not empty. Would you include your security.yml file?

- Update -

Your security file is required to be set up properly in order for your authentication to work. The default behaviour is set to give you a starting point, but you have to configure your firewall. Take a look and read carefully the chapter about Security in Symfony.

Upvotes: 1

Related Questions