Skip to content

Authentication

Mitchell van Wijngaarden edited this page May 10, 2014 · 1 revision

Security is an important thing in most applications and if you're using Laravel's Auth system and Doctrine 2, why not use the Doctrine UserProvider delivered with this package. Like with Timestamps and Soft Deleting this ends up to be very easy and works right out of the box.

Change the driver value in the app/config/auth.php configuration to doctrine.

'driver' => 'doctrine',

Laravel's User objects implement have to implement Illuminate\Auth\UserInterface, this interface demands getters and setters for the password and remember token. To simplify this I've created the Authentication trait that you can easily include in your user class and automagically comply to the UserInterface.

<?php

use Doctrine\ORM\Mapping AS ORM;
use Illuminate\Auth\UserInterface;
use Mitch\LaravelDoctrine\Traits\Authentication;

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User implements UserInterface
{
    use Authentication;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string")
     */
    private $email;

    // Getters and setters for $id and $email here
}

That's it! You're ready to authenticate users with joy!

If you want to implement the password, getAuthIdentifier() and getAuthPassword() from the UserInterface yourself, but don't want to create the remember token methods, this is also possible. Included is a RememberToken trait which does just that.

<?php

use Doctrine\ORM\Mapping AS ORM;
use Illuminate\Auth\UserInterface;
use Mitch\LaravelDoctrine\Traits\RememberToken;

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User implements UserInterface
{
    use RememberToken;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string")
     */
    private $email;

    /**
     * @ORM\Column(type="string")
     */
    private $password;

  	public function getAuthIdentifier()
  	{
  	    return $this->getId();
  	}

  	public function getAuthPassword()
  	{
  	    return $this->getPassword();
  	}

    // Getters and setters for $id, $email and $password here
}