Laravel Passwordless
Passwordless authentication for Laravel 5, (*1)
, (*2)
Installation
Add the package to your project using Composer:, (*3)
composer require whyounes/laravel-passwordless-auth
Publish package assets:, (*4)
php artisan vandor:publish
Run the migration to create the tokens table:, (*5)
php artisan migrate
Add it to you providers list:, (*6)
// config/app.php
// ...
'providers' => [
// ...
Whyounes\Passwordless\Providers\PasswordlessProvider::class,
};
Add the Passwordless trait to your user model:, (*7)
// app/User.php
class User extends Authenticatable
{
use Whyounes\Passwordless\Traits\Passwordless;
// ...
}
Configurations
If you don't want to use the user email along with the token, you can change it by overriding the following method:, (*8)
// app/User.php
class User extends Authenticatable
{
use Whyounes\Passwordless\Traits\Passwordless;
// ...
protected function getIdentifierKey()
{
return 'email';
}
}
You can change the expiration time inside the config/passwordless.php file:, (*9)
// config/passwordless.php
return [
'expire_in' => 15, // Minutes
'empty_tokens_after_login' => true // Empty user tokens after login
];
You can set the empty_tokens_after_login config to false if you don't want to delete unused tokens from DB., (*10)
Example
Display the login form for user to type the email:, (*11)
// routes/web.php
Route::post('/login/direct', function() {
return view('login.direct');
});
Catch the form submission:, (*12)
// routes/web.php
Route::post('/login/direct', function(Request $request) {
// send link to user mail
$user = App\User::where('email', $request->get('email'))->first();
if (!$user) {
return redirect()->back(404)->with('error', 'User not found');
}
// generate token and save it
$token = $user->generateToken(true);
// send email to user
\Mail::send("mails.login", ['token' => $token], function($message) use($token) {
$message->to($token->user->email);
});
});
Catch the login link request:, (*13)
// routes/web.php
Route::get('/login/{token}', function(Request $request, $token) {
$user = App\User::where('email', $request->get('email'))->first();
if (!$user) {
dd('User not found');
}
if($user->isValidToken($token))
{
// Login user
Auth::login($user);
} else {
dd("Invalid token");
}
});
Or, if you like working with exceptions:, (*14)
// routes/web.php
Route::get('/login/{token}', function(Request $request, $token) {
try {
$user = App\User::where('email', $request->get('email'))->firstOrFail();
$user->validateToken($token);
Auth::login($user);
} catch(Illuminate\Database\Eloquent\ModelNotFoundException $ex) {
dd('User not found');
} catch(Whyounes\Passwordless\Exceptions\InvalidTokenException $ex) {
dd("Invalid token");
}
});