cesargb / laravel-magiclink

Create link for authenticate in Laravel without password or get private content
MIT License
385 stars 44 forks source link

linking a magic link with a user #115

Open uoc-kpf opened 4 months ago

uoc-kpf commented 4 months ago

It would be really useful when managing links to be able to associate them with the users that they are generated for. I looked at the MagicLinkWasVisited event but it is fired before the user is logged in. I also looked at the action classes but they don't accept arbitrary extra parameters to save with the magic link data.

Any ideas on a good solution for this?

boudydegeer commented 4 months ago

Hi, I just came across this repo, so not used it yet. But it seems like you can do it your self already. According to the documentation here for example you could do something like this:

<?php
use MagicLink\Actions\LoginAction;
use MagicLink\MagicLink;

// Sample 1; Login and redirect to dashboard
$user = User::first();
$action = (new LoginAction($user))->response(redirect('/dashboard'));
$magicLink = MagicLink::createFor($action);
$urlToDashBoard = $magicLink->url;

UserLinks::create([
  'user_id' => $user->id,
  'magicklink_id' => $$magicLink->id,
  'visited_at' => null
]);

And then just create a Listener to listen to the MagicLinkWasVisited event to mark that link as visited_at!

<?php
namespace App\Listeners;

use MagicLink\Events\MagicLinkWasVisited;

class WhenMagicLinkWasVisited
{
  /**
  * Handle the event.
  */
  public function handle(MagicLinkWasVisited $event): void
  {
    UserMagicLinks::first(["magiclink_id" => $event->magicLink->id])->update(["visited_at" => now()]);
  }
}

Obviously it would be awesome to have that functionality build in, maybe I will do a PR with that approach.

@cesargb Do you think its a feature you would like to include?

I hope that helped @uoc-kpf !

uoc-kpf commented 4 months ago

@boudydegeer Many thanks for your suggestions.

I came up with a similar workaround. It would be good to have this included as a feature (along with defaults for max number of visits and link lifetime in the config file).