A simple, safe magic login link generator for Laravel

Overview

Laravel Passwordless Login

A simple, safe magic login link generator for Laravel

Latest Version on Packagist StyleCI Build Status

This package provides a temporary signed route that logs in a user. What it does not provide is a way of actually sending the link to the route to the user. This is because I don't want to make any assumptions about how you communicate with your users.

Installation

composer require grosv/laravel-passwordless-login

Simple Usage

use App\User;
use Grosv\LaravelPasswordlessLogin\LoginUrl;

function sendLoginLink()
{
    $user = User::find(1);

    $generator = new LoginUrl($user);
    $generator->setRedirectUrl('/somewhere/else'); // Override the default url to redirect to after login
    $url = $generator->generate();

    //OR Use a Facade
    $url = PasswordlessLogin::forUser($user)->generate();

    // Send $url in an email or text message to your user
}

Using A Trait

Because some sites have more than one user-type model (users, admins, etc.), you can use a trait to set up the default configurations for each user type. The methods below are provided by the trait, so you only need to include the ones for which you want to use a different value.

use Grosv\LaravelPasswordlessLogin\Traits\PasswordlessLogin;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use PasswordlessLogin;

    public function getGuardNameAttribute(): string 
    {
        return config('laravel-passwordless-login.user_guard');
    }
    
    public function getShouldRememberLoginAttribute(): bool
    {
        return config('laravel-passwordless-login.remember_login');
    }

    public function getLoginRouteExpiresInAttribute(): int
    {
        return config('laravel-passwordless-login.login_route_expires');
    }

    public function getRedirectUrlAttribute(): string
    {
        return config('laravel-passwordless-login.redirect_on_success');
    }
}

If you are using the PasswordlessLogin Trait, you can generate a link using the defaults defined in the trait by simply calling createPasswordlessLoginLink() on the user you want to log in.

The biggest mistake I could see someone making with this package is creating a login link for one user and sending it to another. Please be careful and test your code. I don't want anyone getting mad at me for someone else's silliness.

Configuration

You can publish the config file or just set the values you want to use in your .env file:

LPL_USER_MODEL=App\User
LPL_REMEMBER_LOGIN=false
LPL_LOGIN_ROUTE=/magic-login
LPL_LOGIN_ROUTE_NAME=magic-login
LPL_LOGIN_ROUTE_EXPIRES=30
LPL_REDIRECT_ON_LOGIN=/
LPL_USER_GUARD=web
LPL_USE_ONCE=false
LPL_INVALID_SIGNATURE_MESSAGE="Expired or Invalid Link"

LPL_USER_MODEL is the the authenticatable model you are logging in (usually App\User)

LPL_REMEMBER_LOGIN is whether you want to remember the login (like the user checking Remember Me)

LPL_LOGIN_ROUTE is the route that points to the login function this package provides. Make sure you don't collide with one of your other routes.

LPL_LOGIN_ROUTE_NAME is the name of the LPL_LOGIN_ROUTE. Again, make sure it doesn't collide with any of your existing route names.

LPL_LOGIN_ROUTE_EXPIRES is the number of minutes you want the link to be good for. I recommend you set the shortest value that makes sense for your use case.

LPL_REDIRECT_ON_LOGIN is where you want to send the user after they've logged in by clicking their magic link.

LPL_USE_ONCE is whether you want a link to expire after first use (uses cache to store used links)

LPL_INVALID_SIGNATURE_MESSAGE is a custom message sent when we abort with a 401 status on an invalid or expired link. You can also add some custom logic on how to deal with invalid or expired links by handling InvalidSignatureException and ExpiredSignatureException in your Handler.php file.

Reporting Issues

For security issues, please email me directly at [email protected]. For any other problems, use the issue tracker here.

Contributing

I welcome the community's help with improving and maintaining all my packages. Just be nice to each other. Remember we're all just trying to do our best.

Comments
  • Argument 1 passed to Grosv\LaravelPasswordlessLogin\LoginUrl::__construct() must be an instance of Grosv\LaravelPasswordlessLogin\Models\User, instance of App\User given

    Argument 1 passed to Grosv\LaravelPasswordlessLogin\LoginUrl::__construct() must be an instance of Grosv\LaravelPasswordlessLogin\Models\User, instance of App\User given

    It is possible that I am not doing it right since I am new to laravel. But I have been doing almost the same thing for other packages and it has been fine.

    As for this package, it kept on reading the Models/User in the LoginUrl class. I will get the error like the title mentioned above.

    But when I changed the LoginUrl to use App\User(which is my user model with a different table name), it works. Url generated nicely.

    So I am not sure if this is a bug or an issue or it is meant to be this way.

    Thanks!

    bug 
    opened by mnazmi23 19
  • Use trait for auth

    Use trait for auth

    I seriously need some help guys.

    Generating the link is done but now I do not have the logic to pull a model type from the already generated link.

     public function login(Request $request)
        {
            abort_if(!$request->hasValidSignature(), 401);
    
            $user_model = config('laravel-passwordless-login.user_model');
    
            Auth::guard(config('laravel-passwordless-login.user_guard'))
    
            //more code there
        }
    

    We used to fetch the user from the config file but now that we are migrating to a trait it means we opened room for more than one class (model).

    The big question now is How can we retrieve the current modal from the current request? given the route is coming in with just the route life span and the model id

    opened by innoflash 16
  • Missing required parameters for [Route: magic-login] [URI: magic-login/{expires}/{uid}].

    Missing required parameters for [Route: magic-login] [URI: magic-login/{expires}/{uid}].

    Hi, i don“t know if i am doing something wrong, but this is my controller:

        function sendLoginLink()
        {
            $user = User::find(8);
    
            $generator = new LoginUrl($user);
            $generator->setRedirectUrl('/home');
            $url = $generator->generate();
    
            return $url;
        }
    

    and when i test the url a got this:

    Illuminate\Routing\Exceptions\UrlGenerationException Missing required parameters for [Route: magic-login] [URI: magic-login/{expires}/{uid}].

    I am in laravel 7.0.8 with default user model, but with a custom table name and password field.

    What could be the problem?

    Thanks.

    opened by killemalljustice 11
  • Redirect Issue with new Guest Middleware

    Redirect Issue with new Guest Middleware

    Hi there,

    Big Fan of your package, thanks for your nice work in advance!!

    Unfortunately the newly added guest middleware causes a new problem. I have an app that highly relies on the redirect feature of the passwordless login package. Due to the new guest middleware the redirect will not be executed when a user is already logged in because the login method of LaravelPasswordlessLoginController will never be called and as far as i understand it correct after a dive into your package the redirect logic is executed within the login method of this Controller.

    The redirect only happens when being logged out and clicking on the generated link.

    opened by dajoeberlei 7
  • Unable to publish config, small tweak.

    Unable to publish config, small tweak.

    Whilst setting this up with Laravel 6, I wasn't able to publish the config.

    When I published with this php artisan vendor:publish --tag=passwordless-login-config: Kept getting the error:

    Can't locate path: <0>
    Can't locate path: <1>
    

    Had to change from this:

    $this->publishes([
       __DIR__.'../config/config.php', config_path('laravel-passwordless-login.php'),
    ], 'passwordless-login-config');
    

    to

    $this->publishes([
        __DIR__.'/../config/config.php' => config_path('laravel-passwordless-login.php'),
    ], 'passwordless-login-config');
    

    Works fine now. If you want this as a PR lemme know šŸ‘šŸ¼ Love your work.

    opened by meredevelopment 5
  • Fixed and optimized login method

    Fixed and optimized login method

    • Fixed missing config() for remember parameter.
    • optimized authentication

    Reference: https://github.com/laravel/framework/blob/5.8/src/Illuminate/Contracts/Auth/StatefulGuard.php#L40

    opened by musapinar 5
  • Refactoring and adding GitHub Actions CI

    Refactoring and adding GitHub Actions CI

    Overview

    This PR also resolves #12 and resolves #13.

    (CC @innoflash @ashleighsims)

    Refactoring

    Followed best practices when developing third-party Laravel libraries.

    • Don't use facades
      • Use dependency injection instead
    • Don't use macros
    • Don't use global helper functions
    • Don't call unsafe magic methods as a shorthand
    • Don't use closure routing
      • Closure routes cannot be cached, ./artisan route:cache will always fail
    • Don't write logic directly in helper classes
      • The core logic should be written in a manager class
    • Don't pollute src directory with the testing stubs

    Adding GitHub Actions CI

    LGTM: https://github.com/mpyw-forks/laravel-passwordless-login/runs/492935564

    opened by mpyw 5
  • Dynamic redirect URL

    Dynamic redirect URL

    Hi, is possible to implement a dynamic redirect url ?? something like this

    $user = User::find(1);
    $generator = new LoginUrl($user);
    $redirect_url = "/home";
    $url = $generator->generate($redirect_url);
    

    Thanks.

    enhancement 
    opened by killemalljustice 5
  • Use login once

    Use login once

    This PR aims to fix this issue https://github.com/grosv/laravel-passwordless-login/issues/28

    Usage:

    // on config.php
    'login_use_once'  => true,
    

    Or on a AuthenticatableUser that uses the trait:

    public function getLoginUseOnceAttribute()
    {
        return true;
    }
    

    I used caching the route for the minutes given.

    opened by innoflash 4
  • Login route expires after first use

    Login route expires after first use

    Hi, i was thinking that maybe should be a variable that determine if the login route should expire after the first use, something like this:

    LPL_LOGIN_ROUTE_EXPIRES_AFTER_FIRST_USE=true

    Then you will have two expirations settings, whatever happends first (the minutes have passed or after first use)

    Thanks.

    opened by killemalljustice 4
  • API implementation

    API implementation

    So from the current setting i see this works only for a web interface but how about we extend it to API logins as well.

    For an API a user might wanna generate a token or do something on success. I am thinking of making a callback in the trait to do extra staff. That might as well fix the issue the last issue was having. Will try implement it later today and you guys evaluate

    opened by innoflash 4
  • How to use new

    How to use new

    I'm having difficulty using the newish LPL_MIDDLEWARE env var.

    I need to inject some middleware called firetest before every request this package deals with. I can add it via the config like this and it works fine:

    <?php
    
    use Grosv\LaravelPasswordlessLogin\HandleAuthenticatedUsers;
    
    return [
        'user_model' => env('LPL_USER_MODEL', 'App\User'),
        // etc etc 
        'middleware' => env('LPL_MIDDLEWARE', ['firetest', 'web', HandleAuthenticatedUsers::class]),
    ];
    

    How would I add it in .env?

    I've tried:

    LPL_MIDDLEWARE="['firetest', 'web', HandleAuthenticatedUsers::class]" #result: Target class [['firetest', 'web', HandleAuthenticatedUsers] does not exist
    LPL_MIDDLEWARE="['firetest', 'web', Grosv\LaravelPasswordlessLogin\HandleAuthenticatedUsers\HandleAuthenticatedUsers::class]" #result: White screen no visible errors.
    LPL_MIDDLEWARE="['firetest', 'web', Grosv\LaravelPasswordlessLogin\HandleAuthenticatedUsers\HandleAuthenticatedUsers]" #result: White screen no visible errors.
    LPL_MIDDLEWARE="['firetest', 'web']" #result: Target class [['firetest', 'web']] does not exist.
    LPL_MIDDLEWARE="\['firetest', 'web'\]" #result: Target class [['firetest', 'web']] does not exist.
    

    I'm thinking there's no way to define an array in .env without having it exploded or something to turn it into an array when it's retrieved, so is the LPL_MIDDLEWARE actually usable? I suppose if one only want's to define a single middleware it is. Any thoughts please?

    opened by meredevelopment 0
  • Magic Passwordless link handle POST calls

    Magic Passwordless link handle POST calls

    So I have a use case my side. I am adding a payment Gateway and they are posting data to the URL specified.

    Do you think we can make the package handle POST calls as well?

    There is useful data incoming from the other server.

    opened by innoflash 0
  • 401 Unauthorized

    401 Unauthorized

    I did a setup as mentioned in the readme, it works fine on local, but when i deploy on production, it gives a 401 Unauthorised error on

    /magic-url/1?expires=1661899121&redirect_to=portal&user_type=app-models-user&signature=xxx

    opened by daniyals 1
  • Benefit from automatic injection in Laravel

    Benefit from automatic injection in Laravel

    I think using automatic injection in the constructor instead of global helper functions improves this package. https://laravel.com/docs/9.x/container#automatic-injection

    @grosv What do you think?

    opened by szepeviktor 0
Releases(1.8.0)
  • 1.8.0(Apr 28, 2022)

    • Fixed a bug in which the the redirect after login url was ignored in favor of the default Laravel redirect on authenticated url
    • Middleware now defined in the configuration file
    Source code(tar.gz)
    Source code(zip)
  • 1.7.1(Feb 14, 2022)

  • 1.7.0(Jan 16, 2022)

  • 1.6.0(Feb 11, 2021)

  • 1.5.1(Jan 13, 2021)

  • 1.5.0(Jan 12, 2021)

  • 1.4.1(Jan 3, 2021)

  • 1.4.0(Dec 6, 2020)

  • 1.3.0(Sep 7, 2020)

  • 1.2.0(Apr 23, 2020)

    This minor release adds the ability to make login links single use. If in your .env you set LPL_USE_ONCE=true used links will be remembered in the cache and, if found, will throw a 401 instead of logging the user in. You can also add a custom message to the 401. See README for more info.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.4(Apr 22, 2020)

  • 1.1.3(Mar 13, 2020)

    My kid pooped himself as I was trying to get the last release together so I had created the pull request that fixed the problem but hadn't merged it. Now it really should be working. I hope.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.2(Mar 12, 2020)

    Fixed a really stupid bug where because I forgot to add the web middleware to the login route, users were momentarily logged in but then immediately logged out on redirect.

    This bug seems to indicate, though, that there is a bug in the Laravel test suite because the tests demonstrated that the user session persisted beyond the redirect which it obviously did not in the real world. I will recreate for the purposes of demonstrating the problem and see if I can get the Larapeeps to fix the tests suite so that nobody else suffers like I have today.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.1(Mar 12, 2020)

  • 1.1.0(Mar 12, 2020)

    Added createPasswordlessLoginLink() to the trait to provide a one-line option for generating the link once you have a user model that you want to log in.

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Mar 11, 2020)

    With a great deal of help from @ashleighsims and @innoflash we worked through a couple of bugs, added the ability to set the redirect url on the fly, and created a trait to make per-user-type defaults easy. I feel good deploying this package in my own projects at work now and look forward to keeping it great with your help!

    Source code(tar.gz)
    Source code(zip)
  • 0.2.0(Mar 5, 2020)

  • 0.1.1(Feb 29, 2020)

    I had added a phone column to the default users table when I intended to handle the actual delivery of the link to the user in this package. But since I decided that was out of scope for this package, I'm removing that migration.

    Source code(tar.gz)
    Source code(zip)
  • 0.1.0(Feb 28, 2020)

Owner
gro.sv
Open source projects maintained by Ed Grosvenor
gro.sv
It's authorization form, login button handler and login to your personal account, logout button

Authorization-form It's authorization form, login button handler and login to your personal account, logout button Each file is: header.php - html-fil

Galina 2 Nov 2, 2021
Braindead simple social login with Laravel and Eloquent.

Important: This package is not actively maintained. For bug fixes and new features, please fork. Eloquent OAuth Use the Laravel 4 wrapper for easy int

Adam Wathan 374 Dec 21, 2022
How to create a simple auth system with login and signup functionalities in Code-igniter 4.

Codeigniter 4 Authentication Login and Registration Example Checkout the step-by-step tutorial on: Codeigniter 4 Authentication Login and Registration

Digamber Rawat 7 Jan 9, 2023
A Laravel 5 package for OAuth Social Login/Register implementation using Laravel socialite and (optionally) AdminLTE Laravel package

laravel-social A Laravel 5 package for OAuth Social Login/Register implementation using Laravel socialite and (optionally) AdminLTE Laravel package. I

Sergi Tur Badenas 42 Nov 29, 2022
Laravel package to easily login as other users during development.

A Laravel 5.4 utility package to enable developers to log in as other users during development. Installation To install the package, simply follow the

VIA Creative 555 Jan 8, 2023
Login Using Laravel UI

Projeto Laravel utilizando a biblioteca Laravel UI para autenticação de usuÔrios com Username e Senha.

AlexLeonel 2 Oct 27, 2021
Login & Register using laravel 8

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Georgy Octavianus Fernando 1 Nov 16, 2021
Login SV Authentication for Laravel.

Autenticación LoginSV para Laravel. Instalación Instalar el paquete usando el siguiente comando, composer require leolopez/loginsv Registrar el prove

null 2 Apr 16, 2022
Instantly login as user via a single button tap on dev environments.

Getting tired of always entering login details in local dev environments? This package adds a button to instantly login a user! Installation You can i

Quinten Buis 3 Feb 18, 2022
A whitelabeled and modernized wp-login.php

Modern Login Here lives a simple mu-plugin to whitelabel and modernize wp-login.php. No admin panels, no bloat – just a simple filter to optionally cu

Brandon 65 Dec 22, 2022
Un proyecto que crea una API de usuarios para registro, login y luego acceder a su información mediante autenticación con JSON Web Token

JSON WEB TOKEN CON LARAVEL 8 Prueba de autenticación de usuarios con una API creada en Laravel 8 Simple, fast routing engine. License The Laravel fram

Yesser Miranda 2 Oct 10, 2021
User registration and login form with validations and escapes for total security made with PHP.

Login and Sign Up with PHP User registration and login form with validations and escapes for total security made with PHP. Validations Required fields

Alexander PƩrez 2 Jan 26, 2022
Register ,Login , Logout , having access control

Helo what's up dude read by the name of creator lov3yp :D This script is inspired by Lov3yp#2018 And Burak karahan Installation steps: !- Import the s

Lov3yp 2 Nov 1, 2021
A complete Login and Register page using a Mysql Database and php

Login With Mysql A complete Login and Register page using a Mysql Database ?? Built with āš™ļø ?? Description A login with Frontend, Backend and Database

Marc Medrano 1 Nov 5, 2021
PHP Login and Registration Script

dj_login PHP Login and Registration Script To function this script requires you put your MySQL info into both login.php and register.php, and have the

djsland.com 1 Nov 16, 2021
This extension expands WSOAuth extension and provide a EveOnline SSO login method

This extension expands WSOAuth extension and provide a EveOnline SSO login method

Raze Soldier 1 Nov 15, 2021
Login Social and product store

Run Stores Fake Marvel store This is a fake Marvel Store, here you can find a list of all the Marvel characters and simulate a shopping of its product

Ricardo Rito Anguiano 1 Jan 22, 2022
Login Menggunakan Google, Github, & Facebook

Login Oauth 2 Karena agak rumit untuk menjelaskan, ikuti tutorial berikut untuk mengatur CLIENTID dan CLIENTSECRET mu terlebih dahulu klik. Server Req

Fadhlurrahman 1 Nov 24, 2021
Helps you securely setup a master password and login into user accounts with it.

?? Make your Login form smart in a minute! Built with ā¤ļø for every smart laravel developer Helps you set a master password in .env file and login into

Iman 341 Jan 1, 2023