Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Nopass Laravel Package

lakm/nopass

Passwordless authentication helpers for Laravel 10/11. Send secure verification links or one-time passcodes (OTP) to log users in without passwords. Includes configuration, usage examples, testing, and security guidance.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup Steps

  1. Installation

    composer require lakm/nopass
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="LakM\NoPass\NoPassServiceProvider"
    
  2. Configure Email/SMS Provider Ensure your Laravel app is configured to send emails (e.g., Mailgun, SES) or SMS (e.g., Twilio) for OTP delivery. The package does not bundle these services—you must integrate them separately.

  3. First Use Case: Magic Link Login

    • Generate a signed login link for a user:
      use LakM\NoPass\Facades\NoPass;
      
      $user = User::find(1);
      $link = NoPass::for($user)
          ->email()
          ->routeName('login') // Must match a named route
          ->generate(['custom' => 'data']); // Optional query params
      
    • Send the link via email (use Laravel’s Mail facade or a queue job).
  4. First Use Case: OTP Login

    • Generate and send an OTP:
      $otp = NoPass::for($user)
          ->otp()
          ->generate();
      
    • Send the OTP via SMS (e.g., Twilio) or email.
    • Validate the OTP in a controller:
      if (NoPass::for($user)->isValid($request->input('otp'))) {
          auth()->login($user);
          return redirect()->intended('/dashboard');
      }
      
  5. Route Setup Create a route to handle the magic link (e.g., login-link):

    Route::get('/login/{token}', [AuthController::class, 'handleMagicLink'])
        ->name('login-link');
    

    Implement handleMagicLink to validate the token and log the user in:

    public function handleMagicLink($token) {
        $user = NoPass::validateToken($token);
        if ($user) {
            auth()->login($user);
            return redirect()->intended('/dashboard');
        }
        abort(404);
    }
    

Implementation Patterns

Core Workflows

1. Magic Link Authentication

  • Generation: Use the facade to create a signed URL with an expiration timestamp.
    $link = NoPass::for($user)
        ->email()
        ->routeName('login')
        ->expires(60) // 60 minutes
        ->generate(['redirect' => 'dashboard']);
    
  • Sending: Attach the link to an email template (e.g., using Laravel Notifications).
    Mail::to($user->email)->send(new MagicLinkNotification($link));
    
  • Validation: Extract the token from the URL and validate it in a route handler.
    public function validateMagicLink($token) {
        $user = NoPass::validateToken($token);
        if ($user) {
            auth()->login($user);
            return redirect()->intended('/dashboard');
        }
        return back()->withError('Invalid or expired link.');
    }
    

2. OTP Authentication

  • Generation: Generate a 6-digit OTP and store it temporarily (e.g., in the database or cache).
    $otp = NoPass::for($user)
        ->otp()
        ->length(6)
        ->expires(5) // 5 minutes
        ->generate();
    
  • Delivery: Send the OTP via SMS or email (e.g., using Twilio or Laravel Notifications).
    // Example with Twilio
    $client->messages->create(
        $user->phone,
        ['body' => "Your OTP is: {$otp}"]
    );
    
  • Validation: Check the OTP in a form submission.
    if (NoPass::for($user)->isValid($request->input('otp'))) {
        auth()->login($user);
        return redirect()->intended('/dashboard');
    }
    

3. Hybrid Authentication

Combine magic links and OTPs for flexibility:

// In a registration/login controller
if ($request->input('method') === 'email') {
    $link = NoPass::for($user)->email()->generate();
    // Send email with link
} elseif ($request->input('method') === 'sms') {
    $otp = NoPass::for($user)->otp()->generate();
    // Send SMS with OTP
}

Integration Tips

1. Leverage Existing Auth Systems

  • Breeze/Jetstream: Replace the default login form with a "Send Magic Link" or "Send OTP" button. Use the package’s methods to generate and validate tokens.
  • Custom Auth: Extend the AuthenticatesUsers trait to include passwordless login options. Example:
    public function sendLoginLink(Request $request) {
        $user = User::where('email', $request->email)->first();
        if ($user) {
            $link = NoPass::for($user)->email()->generate();
            Mail::to($user->email)->send(new MagicLinkNotification($link));
        }
        return back()->with('status', 'Login link sent!');
    }
    

2. Rate Limiting

Implement rate limiting to prevent abuse (e.g., brute-force OTP guessing):

use Illuminate\Http\Request;
use Illuminate\Cache\RateLimiter;

protected function attemptLogin(Request $request) {
    $limiter = app(RateLimiter::class);
    $key = $request->ip().'|'.$request->input('email');

    if ($limiter->tooManyAttempts($key, 5)) {
        abort(429, 'Too many attempts. Try again later.');
    }

    // Proceed with OTP/magic link logic
}

3. Queue Jobs for Scalability

Offload email/OTP sending to queues to avoid blocking requests:

// Generate link/OTP
$link = NoPass::for($user)->email()->generate();

// Dispatch a job to send the email
SendMagicLinkEmail::dispatch($user, $link);

Define the job:

class SendMagicLinkEmail implements ShouldQueue {
    public function handle() {
        Mail::to($this->user->email)->send(new MagicLinkNotification($this->link));
    }
}

4. Customize Expiration and Length

Override defaults in the config or dynamically:

// Config (config/nopass.php)
'email' => [
    'expires' => 30, // minutes
],
'otp' => [
    'length' => 6,
    'expires' => 3, // minutes
],

Or set per-user:

$link = NoPass::for($user)
    ->email()
    ->expires(15) // 15 minutes
    ->generate();

5. Invalidate Tokens

Invalidate tokens after use or on request:

// After successful login
NoPass::for($user)->invalidate();

// Or invalidate all tokens for a user
NoPass::for($user)->invalidateAll();

6. Logging and Analytics

Track passwordless authentication events:

event(new PasswordlessLoginAttempt($user, $method));

Create an event listener to log to a database or external service.


Gotchas and Tips

Pitfalls

1. Token Validation Failures

  • Issue: NoPass::validateToken($token) may fail silently or return null if the token is invalid/expired.
  • Fix: Always check the return value and handle errors gracefully:
    $user = NoPass::validateToken($token);
    if (!$user) {
        abort(404, 'Invalid or expired link.');
    }
    

2. Missing Route Naming

  • Issue: The routeName method requires a named route that exists in your routes/web.php. Using an undefined route will throw an exception.
  • Fix: Ensure the route is defined and named:
    Route::get('/login/{token}', [AuthController::class, 'handleMagicLink'])
        ->name('login-link');
    

3. OTP Delivery Dependencies

  • Issue: The package does not include SMS/email providers. You must integrate third-party services (e.g., Twilio, Mailgun) manually.
  • Fix: Use Laravel’s Mail facade or a queue job to send emails/OTPs. Example for Twilio:
    $client = new Client($accountSid, $authToken);
    $client->messages->create(
        $user->phone,
        ['body' => "Your OTP is: {$otp}"]
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity