├── .gitignore ├── LICENSE ├── composer.json ├── config └── magic-auth.php ├── readme.md ├── resources └── lang │ ├── en │ └── messages.php │ └── nl │ └── messages.php ├── routes └── web.php └── src ├── AuthServiceProvider.php ├── AuthenticatesUsers.php ├── Contracts ├── CanMagicallyLogin.php └── LinkBroker.php ├── Http ├── Controllers │ ├── LinkController.php │ └── LoginController.php └── Middleware │ └── AuthenticateWithMagicLink.php ├── Links └── LinkBroker.php ├── Notifications └── MagicLink.php ├── SendsMagicLinkEmails.php └── Traits └── CanMagicallyLogin.php /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor 2 | composer.lock 3 | .DS_Store 4 | Thumbs.db 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Sander de Vos 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "soved/laravel-magic-auth", 3 | "description": "Authenticate users using a magic link", 4 | "keywords": ["laravel", "magic-authentication", "soved", "authentication", "encryption"], 5 | "type": "library", 6 | "require": { 7 | "php": "^7.1.3", 8 | "illuminate/support": "~5.6|~6.0|~7.0|~8.0" 9 | }, 10 | "autoload": { 11 | "psr-4": { 12 | "Soved\\Laravel\\Magic\\Auth\\": "src/" 13 | } 14 | }, 15 | "license": "MIT", 16 | "authors": [ 17 | { 18 | "name": "Sander de Vos", 19 | "email": "sander@tutanota.de" 20 | } 21 | ], 22 | "minimum-stability": "stable", 23 | "extra": { 24 | "laravel": { 25 | "providers": [ 26 | "Soved\\Laravel\\Magic\\Auth\\AuthServiceProvider" 27 | ] 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /config/magic-auth.php: -------------------------------------------------------------------------------- 1 | 'magic', 16 | 17 | /* 18 | |-------------------------------------------------------------------------- 19 | | Expiration Time 20 | |-------------------------------------------------------------------------- 21 | | 22 | | The expiration time is the number of minutes that the magic link should 23 | | be considered valid. 24 | | 25 | */ 26 | 27 | 'expiration' => 5, 28 | 29 | /* 30 | |-------------------------------------------------------------------------- 31 | | Remembering Users 32 | |-------------------------------------------------------------------------- 33 | | 34 | | If you would like to provide "remember me" functionality in your 35 | | application, you may set this value to true. 36 | | 37 | */ 38 | 39 | 'remember' => false, 40 | 41 | ]; 42 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Authenticate users using a magic link 2 | 3 | Fast and secure passwordless authentication for the masses. 4 | 5 | [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/sander3/laravel-magic-auth/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/sander3/laravel-magic-auth/?branch=master) 6 | [![Latest Stable Version](https://poser.pugx.org/soved/laravel-magic-auth/v/stable)](https://packagist.org/packages/soved/laravel-magic-auth) 7 | [![Monthly Downloads](https://poser.pugx.org/soved/laravel-magic-auth/d/monthly)](https://packagist.org/packages/soved/laravel-magic-auth) 8 | [![License](https://poser.pugx.org/soved/laravel-magic-auth/license)](https://packagist.org/packages/soved/laravel-magic-auth) 9 | 10 | [Buy me a coffee ☕️](https://www.buymeacoffee.com/sander3) 11 | 12 | ## Requirements 13 | 14 | - PHP >= 7.1.3 15 | - Laravel >= 5.6, 6.0 or 7.0 16 | 17 | ## Installation 18 | 19 | First, install the package via the Composer package manager: 20 | 21 | ```bash 22 | $ composer require soved/laravel-magic-auth 23 | ``` 24 | 25 | After installing the package, you should publish the configuration file: 26 | 27 | ```bash 28 | $ php artisan vendor:publish --tag=magic-auth-config 29 | ``` 30 | 31 | Add the `Soved\Laravel\Magic\Auth\Contracts\CanMagicallyLogin` interface to the `App\User` model: 32 | 33 | ```php 34 | 'We have e-mailed your magic link!', 6 | 'authenticated' => 'You have logged in successfully.', 7 | 'user' => "We can't find a user with that e-mail address.", 8 | 'signature' => 'This magic link is invalid.', 9 | 10 | ]; 11 | -------------------------------------------------------------------------------- /resources/lang/nl/messages.php: -------------------------------------------------------------------------------- 1 | 'We hebben je een magische link gemaild!', 6 | 'authenticated' => 'Je bent succesvol ingelogd.', 7 | 'user' => 'We kunnen geen gebruiker met dat e-mailadres vinden.', 8 | 'signature' => 'Deze magische link is ongeldig.', 9 | 10 | ]; 11 | -------------------------------------------------------------------------------- /routes/web.php: -------------------------------------------------------------------------------- 1 | name('magic.email')->middleware('throttle:5,5'); 7 | 8 | Route::get('login', 'LoginController@login') 9 | ->name('magic.login')->middleware('throttle:12,60'); 10 | -------------------------------------------------------------------------------- /src/AuthServiceProvider.php: -------------------------------------------------------------------------------- 1 | registerRoutes(); 18 | $this->registerTranslations(); 19 | } 20 | 21 | /** 22 | * Register the magic authentication routes. 23 | * 24 | * @return void 25 | */ 26 | protected function registerRoutes() 27 | { 28 | Route::group([ 29 | 'prefix' => config('magic-auth.uri'), 30 | 'namespace' => 'Soved\Laravel\Magic\Auth\Http\Controllers', 31 | 'middleware' => 'web', 32 | ], function () { 33 | $this->loadRoutesFrom(__DIR__ . '/../routes/web.php'); 34 | }); 35 | } 36 | 37 | /** 38 | * Register the magic authentication translations. 39 | * 40 | * @return void 41 | */ 42 | protected function registerTranslations() 43 | { 44 | $this->loadTranslationsFrom( 45 | __DIR__ . '/../resources/lang', 'magic-auth' 46 | ); 47 | } 48 | 49 | /** 50 | * Register the application services. 51 | * 52 | * @return void 53 | */ 54 | public function register() 55 | { 56 | $this->configure(); 57 | $this->offerPublishing(); 58 | } 59 | 60 | /** 61 | * Setup the configuration for magic authentication. 62 | * 63 | * @return void 64 | */ 65 | protected function configure() 66 | { 67 | $this->mergeConfigFrom( 68 | __DIR__ . '/../config/magic-auth.php', 'magic-auth' 69 | ); 70 | } 71 | 72 | /** 73 | * Setup the resource publishing groups for magic authentication. 74 | * 75 | * @return void 76 | */ 77 | protected function offerPublishing() 78 | { 79 | if ($this->app->runningInConsole()) { 80 | $this->publishes([ 81 | __DIR__ . '/../config/magic-auth.php' => config_path('magic-auth.php'), 82 | ], 'magic-auth-config'); 83 | 84 | $this->publishes([ 85 | __DIR__ . '/../resources/lang' => resource_path('lang/vendor/magic-auth'), 86 | ], 'magic-auth-lang'); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/AuthenticatesUsers.php: -------------------------------------------------------------------------------- 1 | validateLogin($request); 23 | 24 | $response = $this->broker()->login( 25 | $request, function ($user) { 26 | $this->authenticateUser($user); 27 | } 28 | ); 29 | 30 | return $response == LinkBroker::USER_AUTHENTICATED 31 | ? $this->sendLoginResponse($request) 32 | : $this->sendFailedLoginResponse($response); 33 | } 34 | 35 | /** 36 | * Validate the user login request. 37 | * 38 | * @param \Illuminate\Http\Request $request 39 | * @return void 40 | */ 41 | protected function validateLogin(Request $request) 42 | { 43 | $this->validate($request, ['email' => 'required|email']); 44 | } 45 | 46 | /** 47 | * Authenticate the given user. 48 | * 49 | * @param \Soved\Laravel\Magic\Auth\Traits\CanMagicallyLogin $user 50 | * @return void 51 | */ 52 | protected function authenticateUser($user) 53 | { 54 | $this->guard()->login($user, config('magic-auth.remember')); 55 | } 56 | 57 | /** 58 | * Send the response after the user was authenticated. 59 | * 60 | * @param \Illuminate\Http\Request $request 61 | * @return \Illuminate\Http\Response 62 | */ 63 | protected function sendLoginResponse(Request $request) 64 | { 65 | $request->session()->regenerate(); 66 | 67 | return $this->authenticated($request, $this->guard()->user()) 68 | ?: redirect()->intended($this->redirectPath()); 69 | } 70 | 71 | /** 72 | * The user has been authenticated. 73 | * 74 | * @param \Illuminate\Http\Request $request 75 | * @param mixed $user 76 | * @return mixed 77 | */ 78 | protected function authenticated( 79 | Request $request, 80 | $user 81 | ) { 82 | $request->session()->put('viaMagicLink', true); 83 | 84 | // Invalidating all unexpired magic links 85 | $user->touch(); 86 | } 87 | 88 | /** 89 | * Get the failed login response instance. 90 | * 91 | * @param string $response 92 | * @return \Illuminate\Http\RedirectResponse 93 | */ 94 | protected function sendFailedLoginResponse(string $response) 95 | { 96 | return redirect($this->redirectPath()) 97 | ->withErrors(['email' => __($response)]); 98 | } 99 | 100 | /** 101 | * Get the broker to be used during magic authentication. 102 | * 103 | * @return \Soved\Laravel\Magic\Auth\Links\LinkBroker 104 | */ 105 | public function broker() 106 | { 107 | $userProvider = Auth::getProvider(); 108 | 109 | return new LinkBroker($userProvider); 110 | } 111 | 112 | /** 113 | * Get the guard to be used during magic authentication. 114 | * 115 | * @return \Illuminate\Contracts\Auth\StatefulGuard 116 | */ 117 | protected function guard() 118 | { 119 | return Auth::guard(); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/Contracts/CanMagicallyLogin.php: -------------------------------------------------------------------------------- 1 | check()) { 27 | throw new AuthenticationException; 28 | } 29 | 30 | if (!Auth::guard($guard)->user()->viaMagicLink()) { 31 | $response = $this->sendMagicLinkEmail($request); 32 | 33 | Auth::guard($guard)->logout(); 34 | 35 | return redirect() 36 | ->guest(route('login')) 37 | ->with('status', __($response)); 38 | } 39 | 40 | return $next($request); 41 | } 42 | 43 | /** 44 | * Send a magic link to the given user. 45 | * 46 | * @param \Illuminate\Http\Request $request 47 | * @return string 48 | */ 49 | private function sendMagicLinkEmail(Request $request) 50 | { 51 | return $this->broker()->sendMagicLink( 52 | [ 53 | 'email' => $request->user()->email, 54 | ] 55 | ); 56 | } 57 | 58 | /** 59 | * Get the broker to be used during magic authentication. 60 | * 61 | * @return \Soved\Laravel\Magic\Auth\Links\LinkBroker 62 | */ 63 | private function broker() 64 | { 65 | $userProvider = Auth::getProvider(); 66 | 67 | return new LinkBroker($userProvider); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/Links/LinkBroker.php: -------------------------------------------------------------------------------- 1 | users = $users; 31 | } 32 | 33 | /** 34 | * Send a magic link to a user. 35 | * 36 | * @param array $credentials 37 | * @return string 38 | */ 39 | public function sendMagicLink(array $credentials) 40 | { 41 | $user = $this->getUser($credentials); 42 | 43 | if (is_null($user)) { 44 | return static::INVALID_USER; 45 | } 46 | 47 | $user->sendMagicLinkNotification( 48 | $this->createMagicLink($user) 49 | ); 50 | 51 | return static::MAGIC_LINK_SENT; 52 | } 53 | 54 | /** 55 | * Log the user into the application. 56 | * 57 | * @param \Illuminate\Http\Request $request 58 | * @param \Closure $callback 59 | * @return string 60 | */ 61 | public function login( 62 | Request $request, 63 | Closure $callback 64 | ) { 65 | $user = $this->validateLogin($request); 66 | 67 | if (!$user instanceof CanMagicallyLoginContract) { 68 | return $user; 69 | } 70 | 71 | $callback($user); 72 | 73 | return static::USER_AUTHENTICATED; 74 | } 75 | 76 | /** 77 | * Validate a magic authentication request for the given user. 78 | * 79 | * @param \Illuminate\Http\Request $request 80 | * @return \Soved\Laravel\Magic\Auth\Traits\CanMagicallyLogin|string 81 | */ 82 | protected function validateLogin(Request $request) 83 | { 84 | $credentials = $request->only([ 85 | 'id', 86 | 'email', 87 | 'updated_at', 88 | ]); 89 | 90 | if (is_null($user = $this->getUser($credentials))) { 91 | return static::INVALID_USER; 92 | } 93 | 94 | if (!$request->hasValidSignature()) { 95 | return static::INVALID_SIGNATURE; 96 | } 97 | 98 | return $user; 99 | } 100 | 101 | /** 102 | * Get the user for the given credentials. 103 | * 104 | * @param array $credentials 105 | * @return \Soved\Laravel\Magic\Auth\Traits\CanMagicallyLogin|null 106 | * 107 | * @throws \UnexpectedValueException 108 | */ 109 | public function getUser(array $credentials) 110 | { 111 | $user = $this->users->retrieveByCredentials($credentials); 112 | 113 | if ($user && !$user instanceof CanMagicallyLoginContract) { 114 | throw new UnexpectedValueException('User must implement CanMagicallyLogin interface.'); 115 | } 116 | 117 | return $user; 118 | } 119 | 120 | /** 121 | * Create a new magic link. 122 | * 123 | * @param \Soved\Laravel\Magic\Auth\Traits\CanMagicallyLogin $user 124 | * @return string 125 | */ 126 | public function createMagicLink(CanMagicallyLoginContract $user) 127 | { 128 | $email = $user->getEmailForMagicLink(); 129 | 130 | return URL::temporarySignedRoute( 131 | 'magic.login', 132 | now()->addMinutes(config('magic-auth.expiration')), 133 | [ 134 | 'id' => $user->id, 135 | 'email' => $email, 136 | 'updated_at' => $user->updated_at, 137 | ] 138 | ); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/Notifications/MagicLink.php: -------------------------------------------------------------------------------- 1 | link = $link; 25 | } 26 | 27 | /** 28 | * Get the notification's channels. 29 | * 30 | * @param mixed $notifiable 31 | * 32 | * @return string 33 | */ 34 | public function via($notifiable) 35 | { 36 | return 'mail'; 37 | } 38 | 39 | /** 40 | * Build the mail representation of the notification. 41 | * 42 | * @param mixed $notifiable 43 | * 44 | * @return \Illuminate\Notifications\Messages\MailMessage 45 | */ 46 | public function toMail($notifiable) 47 | { 48 | return (new MailMessage()) 49 | ->subject(__('Magic Authentication Notification')) 50 | ->line(__('You are receiving this email because we received a magic authentication request for your account.')) 51 | ->action(__('Login'), $this->link) 52 | ->line(__('If you did not request a magic link, no further action is required.')); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/SendsMagicLinkEmails.php: -------------------------------------------------------------------------------- 1 | validateEmail($request); 20 | 21 | $response = $this->broker()->sendMagicLink( 22 | $request->only('email') 23 | ); 24 | 25 | return $response == LinkBroker::MAGIC_LINK_SENT 26 | ? $this->sendMagicLinkResponse($response) 27 | : $this->sendMagicLinkFailedResponse($request); 28 | } 29 | 30 | /** 31 | * Validate the email for the given request. 32 | * 33 | * @param \Illuminate\Http\Request $request 34 | * @return void 35 | */ 36 | protected function validateEmail(Request $request) 37 | { 38 | $this->validate($request, ['email' => 'required|email']); 39 | } 40 | 41 | /** 42 | * Get the response for a successfully sent magic link. 43 | * 44 | * @param string $response 45 | * @return \Illuminate\Http\RedirectResponse 46 | */ 47 | protected function sendMagicLinkResponse(string $response) 48 | { 49 | return back()->with('status', __($response)); 50 | } 51 | 52 | /** 53 | * Get the response for a failed magic link. 54 | * 55 | * @param \Illuminate\Http\Request $request 56 | * @return \Illuminate\Http\RedirectResponse 57 | */ 58 | protected function sendMagicLinkFailedResponse(Request $request) 59 | { 60 | // We will send the success response to prevent user enumeration 61 | return $this->sendMagicLinkResponse(LinkBroker::MAGIC_LINK_SENT); 62 | } 63 | 64 | /** 65 | * Get the broker to be used during magic authentication. 66 | * 67 | * @return \Soved\Laravel\Magic\Auth\Links\LinkBroker 68 | */ 69 | public function broker() 70 | { 71 | $userProvider = Auth::getProvider(); 72 | 73 | return new LinkBroker($userProvider); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Traits/CanMagicallyLogin.php: -------------------------------------------------------------------------------- 1 | email; 17 | } 18 | 19 | /** 20 | * Send the magic link notification. 21 | * 22 | * @param string $link 23 | * @return void 24 | */ 25 | public function sendMagicLinkNotification(string $link) 26 | { 27 | $this->notify(new MagicLinkNotification($link)); 28 | } 29 | 30 | /** 31 | * Determine if the user was authenticated via a magic link. 32 | * 33 | * @return bool 34 | */ 35 | public function viaMagicLink() 36 | { 37 | return session('viaMagicLink', false); 38 | } 39 | } 40 | --------------------------------------------------------------------------------