Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A basic API implementation #71

Open
baj84 opened this issue Jul 29, 2021 · 0 comments
Open

A basic API implementation #71

baj84 opened this issue Jul 29, 2021 · 0 comments

Comments

@baj84
Copy link

baj84 commented Jul 29, 2021

Hi, great library! I use laravel as a restful api with a react frontend, so for me I didn't need a lot of what your library offers. So I made a very basic watered down version that will hopefully be of use to others.

MagicLinkController.php

class MagicLinkController extends Controller
{
    public function generate(Request $request)
    {
        $user = User::find(101);

        $magicLink = new MagicLinkService($user);

        $magicLink->setRedirectUrl('/somewhere/else');
        
        $url = $magicLink->generate();

        return response()->json(['url' => $url], 200);
    }

    public function check(Request $request, UrlGenerator $urlGenerator)
    {
        if (!$request->hasValidSignature() || !$urlGenerator->hasCorrectSignature($request) || !$urlGenerator->signatureHasNotExpired($request)) {
            throw new AuthorizationException;
        }

        $user = User::findOrFail($request->id);

        return response()->json([
            'token' => $user->createToken('web')->plainTextToken,
            'user' => $user,
            'redirect_to' => $request->redirect_to
        ], 200);
    }
}

MagicLinkService.php

class MagicLinkService
{
    public $user;
    protected $routeName = 'magic-link';
    protected $routeExpires = 30;
    protected $redirectUrl = null;

    public function __construct(User $user) {
        $this->user = $user;
    }

    public function generate()
    {
        return URL::temporarySignedRoute(
            $this->routeName,
            now()->addMinutes($this->routeExpires),
            [
                'id' => $this->user->getAuthIdentifier(),
                'redirect_to' => $this->redirectUrl
            ]
        );
    }

    public function setRedirectUrl(string $redirectUrl)
    {
        $this->redirectUrl = $redirectUrl;
    }
}

routes/api.php

Route::post('magic-link', 'MagicLinkController@generate');
Route::get('magic-link/{id}', 'MagicLinkController@check')->name('magic-link');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant