|
| 1 | +# Laravel Eloquent |
| 2 | + |
| 3 | +By default, the SDK does not include any Eloquent models or database support. You can adapt the SDK to your application's needs by adding your own Eloquent models and database support. |
| 4 | + |
| 5 | +## Creating a User Model |
| 6 | + |
| 7 | +Begin by creating a new Eloquent model class. You can use the `make:model` Artisan command to do this. Laravel ships with default user model named `User`, so we'll use the `--force` flag to overwrite it with our custom one. |
| 8 | + |
| 9 | +Please ensure you have a backup of your existing `User` model before running this command, as it will overwrite your existing model. |
| 10 | + |
| 11 | +```bash |
| 12 | +php artisan make:model User --force |
| 13 | +``` |
| 14 | + |
| 15 | +Next, open your `app/Models/User.php` file and modify it match the following example. Notably, we'll add a support for a new `auth0` attribute. This attribute will be used to store the user's Auth0 ID, which is used to uniquely identify the user in Auth0. |
| 16 | + |
| 17 | +```php |
| 18 | +<?php |
| 19 | + |
| 20 | +declare(strict_types=1); |
| 21 | + |
| 22 | +namespace App\Models; |
| 23 | + |
| 24 | +use Illuminate\Auth\Authenticatable; |
| 25 | +use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; |
| 26 | +use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; |
| 27 | +use Illuminate\Database\Eloquent\Factories\HasFactory; |
| 28 | +use Illuminate\Database\Eloquent\Model; |
| 29 | +use Illuminate\Foundation\Auth\Access\Authorizable; |
| 30 | + |
| 31 | +class User extends Model implements |
| 32 | + AuthenticatableContract, |
| 33 | + AuthorizableContract |
| 34 | +{ |
| 35 | + use Authenticatable, |
| 36 | + Authorizable, |
| 37 | + HasFactory; |
| 38 | + |
| 39 | + protected $fillable = [ |
| 40 | + 'auth0', |
| 41 | + 'name', |
| 42 | + 'email', |
| 43 | + 'email_verified', |
| 44 | + 'password', |
| 45 | + ]; |
| 46 | + |
| 47 | + protected $hidden = [ |
| 48 | + 'password', |
| 49 | + 'remember_token', |
| 50 | + ]; |
| 51 | + |
| 52 | + protected $casts = [ |
| 53 | + 'email_verified_at' => 'datetime', |
| 54 | + ]; |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +Next, create a migration to update your application's `users` table schema to support these changes. Create a new migration file: |
| 59 | + |
| 60 | +```bash |
| 61 | +php artisan make:migration update_users_table --table=users |
| 62 | +``` |
| 63 | + |
| 64 | +Openly the newly created migration file (found under `database/migrations` and ending in `update_users_table.php`) and update to match the following example: |
| 65 | + |
| 66 | +```php |
| 67 | +<?php |
| 68 | + |
| 69 | +declare(strict_types=1); |
| 70 | + |
| 71 | +use Illuminate\Database\Migrations\Migration; |
| 72 | +use Illuminate\Database\Schema\Blueprint; |
| 73 | +use Illuminate\Support\Facades\Schema; |
| 74 | + |
| 75 | +return new class extends Migration |
| 76 | +{ |
| 77 | + public function up() |
| 78 | + { |
| 79 | + Schema::table('users', function (Blueprint $table) { |
| 80 | + $table->string('auth0')->nullable(); |
| 81 | + $table->boolean('email_verified')->default(false); |
| 82 | + |
| 83 | + $table->unique('auth0', 'users_auth0_unique'); |
| 84 | + }); |
| 85 | + } |
| 86 | + |
| 87 | + public function down() |
| 88 | + { |
| 89 | + Schema::table('users', function (Blueprint $table) { |
| 90 | + $table->dropUnique('users_auth0_unique'); |
| 91 | + |
| 92 | + $table->dropColumn('auth0'); |
| 93 | + $table->dropColumn('email_verified'); |
| 94 | + }); |
| 95 | + } |
| 96 | +}; |
| 97 | + |
| 98 | +``` |
| 99 | + |
| 100 | +Now run the migration: |
| 101 | + |
| 102 | +```bash |
| 103 | +php artisan migrate |
| 104 | +``` |
| 105 | + |
| 106 | +## Creating a User Repository |
| 107 | + |
| 108 | +You'll need to create a new user repository class to handle the creation and retrieval of your Eloquent user models from your database table. |
| 109 | + |
| 110 | +Create a new repository class in your application at `app/Repositories/UserRepository.php`, and update it to match the following example: |
| 111 | + |
| 112 | +```php |
| 113 | +<?php |
| 114 | + |
| 115 | +declare(strict_types=1); |
| 116 | + |
| 117 | +namespace App\Repositories; |
| 118 | + |
| 119 | +use App\Models\User; |
| 120 | +use Auth0\Laravel\{UserRepositoryAbstract, UserRepositoryContract}; |
| 121 | +use Illuminate\Contracts\Auth\Authenticatable; |
| 122 | +use Illuminate\Support\Facades\Cache; |
| 123 | +use Illuminate\Support\Facades\Hash; |
| 124 | +use Illuminate\Support\Str; |
| 125 | + |
| 126 | +final class UserRepository extends UserRepositoryAbstract implements UserRepositoryContract |
| 127 | +{ |
| 128 | + public function fromAccessToken(array $user): ?Authenticatable |
| 129 | + { |
| 130 | + /* |
| 131 | + $user = [ // Example of a decoded access token |
| 132 | + "iss" => "https://example.auth0.com/", |
| 133 | + "aud" => "https://api.example.com/calendar/v1/", |
| 134 | + "sub" => "auth0|123456", |
| 135 | + "exp" => 1458872196, |
| 136 | + "iat" => 1458785796, |
| 137 | + "scope" => "read write", |
| 138 | + ]; |
| 139 | + */ |
| 140 | + |
| 141 | + $identifier = $user['sub'] ?? $user['auth0'] ?? null; |
| 142 | + |
| 143 | + if (null === $identifier) { |
| 144 | + return null; |
| 145 | + } |
| 146 | + |
| 147 | + return User::where('auth0', $identifier)->first(); |
| 148 | + } |
| 149 | + |
| 150 | + public function fromSession(array $user): ?Authenticatable |
| 151 | + { |
| 152 | + /* |
| 153 | + $user = [ // Example of a decoded ID token |
| 154 | + "iss" => "http://example.auth0.com", |
| 155 | + "aud" => "client_id", |
| 156 | + "sub" => "auth0|123456", |
| 157 | + "exp" => 1458872196, |
| 158 | + "iat" => 1458785796, |
| 159 | + "name" => "Jane Doe", |
| 160 | + |
| 161 | + ]; |
| 162 | + */ |
| 163 | + |
| 164 | + // Determine the Auth0 identifier for the user from the $user array. |
| 165 | + $identifier = $user['sub'] ?? $user['auth0'] ?? null; |
| 166 | + |
| 167 | + // Collect relevant user profile information from the $user array for use later. |
| 168 | + $profile = [ |
| 169 | + 'auth0' => $identifier, |
| 170 | + 'name' => $user['name'] ?? '', |
| 171 | + 'email' => $user['email'] ?? '', |
| 172 | + 'email_verified' => in_array($user['email_verified'], [1, true], true), |
| 173 | + ]; |
| 174 | + |
| 175 | + // Check if a cache of the user exists in memory to avoid unnecessary database queries. |
| 176 | + $cached = $this->withoutRecording(fn () => Cache::get('auth0_user_' . $identifier)); |
| 177 | + |
| 178 | + if ($cached) { |
| 179 | + // Immediately return a cached user if one exists. |
| 180 | + return $cached; |
| 181 | + } |
| 182 | + |
| 183 | + $user = null; |
| 184 | + |
| 185 | + // Check if the user exists in the database by Auth0 identifier. |
| 186 | + if (null !== $identifier) { |
| 187 | + $user = User::where('auth0', $identifier)->first(); |
| 188 | + } |
| 189 | + |
| 190 | + // Optional: if the user does not exist in the database by Auth0 identifier, you could fallback to matching by email. |
| 191 | + if (null === $user && isset($user['email'])) { |
| 192 | + $user = User::where('email', $user['email'])->first(); |
| 193 | + } |
| 194 | + |
| 195 | + // If a user was found, check if any updates to the local record are required. |
| 196 | + if (null !== $user) { |
| 197 | + $updates = []; |
| 198 | + |
| 199 | + if ($user->auth0 !== $profile['auth0']) { |
| 200 | + $updates['auth0'] = $profile['auth0']; |
| 201 | + } |
| 202 | + |
| 203 | + if ($user->name !== $profile['name']) { |
| 204 | + $updates['name'] = $profile['name']; |
| 205 | + } |
| 206 | + |
| 207 | + if ($user->email !== $profile['email']) { |
| 208 | + $updates['email'] = $profile['email']; |
| 209 | + } |
| 210 | + |
| 211 | + $emailVerified = in_array($user->email_verified, [1, true], true); |
| 212 | + |
| 213 | + if ($emailVerified !== $profile['email_verified']) { |
| 214 | + $updates['email_verified'] = $profile['email_verified']; |
| 215 | + } |
| 216 | + |
| 217 | + if ([] !== $updates) { |
| 218 | + $user->update($updates); |
| 219 | + $user->save(); |
| 220 | + } |
| 221 | + |
| 222 | + if ([] === $updates && null !== $cached) { |
| 223 | + return $user; |
| 224 | + } |
| 225 | + } |
| 226 | + |
| 227 | + if (null === $user) { |
| 228 | + // Local password column is not necessary or used by Auth0 authentication, but may be expected by some applications/packages. |
| 229 | + $profile['password'] = Hash::make(Str::random(32)); |
| 230 | + |
| 231 | + // Create the user. |
| 232 | + $user = User::create($profile); |
| 233 | + } |
| 234 | + |
| 235 | + // Cache the user for 30 seconds. |
| 236 | + $this->withoutRecording(fn () => Cache::put('auth0_user_' . $identifier, $user, 30)); |
| 237 | + |
| 238 | + return $user; |
| 239 | + } |
| 240 | + |
| 241 | + /** |
| 242 | + * Workaround for Laravel Telescope potentially causing an infinite loop. |
| 243 | + * @link https://github.com/auth0/laravel-auth0/tree/main/docs/Telescope.md |
| 244 | + * |
| 245 | + * @param callable $callback |
| 246 | + */ |
| 247 | + private function withoutRecording($callback): mixed |
| 248 | + { |
| 249 | + $telescope = '\Laravel\Telescope\Telescope'; |
| 250 | + |
| 251 | + if (class_exists($telescope)) { |
| 252 | + return "$telescope"::withoutRecording($callback); |
| 253 | + } |
| 254 | + |
| 255 | + return call_user_func($callback); |
| 256 | + } |
| 257 | +} |
| 258 | +``` |
| 259 | + |
| 260 | +Finally, update your application's `config/auth.php` file to configure the SDK to query your new user provider during authentication requests. |
| 261 | + |
| 262 | +```php |
| 263 | +'providers' => [ |
| 264 | + 'auth0-provider' => [ |
| 265 | + 'driver' => 'auth0.provider', |
| 266 | + 'repository' => \App\Repositories\UserRepository::class, |
| 267 | + ], |
| 268 | +], |
| 269 | +``` |
0 commit comments