Skip to content

FEAT(auth): implement magic link authentication #642

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

Merged
merged 9 commits into from
Mar 2, 2025
Merged
79 changes: 79 additions & 0 deletions app/Http/Controllers/Api/V1/Auth/MagicLinkController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

namespace App\Http\Controllers\Api\V1\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\MagicLinkEmail;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;
use Exception;

class MagicLinkController extends Controller
{

public function setUp(): void
{
parent::setUp();
$this->artisan('migrate'); // Run migrations for the test database
}


// Send a magic link to the user's email.
public function sendMagicLink(Request $request)
{
try {

$validator = Validator::make($request->all(), [
'email' => 'required|email',
]);

if ($validator->fails()) {
return response()->json([
'status_code' => 400,
'status' => 'error',
'message' => 'Invalid email address',
'data' => $validator->errors(),
], 400);
}

$user = User::where('email', $request->email)->first();

if (!$user) {
return response()->json([
'status_code' => 404,
'status' => 'error',
'message' => 'User not found',
'data' => [],
], 404);
}

// Generate a unique token
$token = Str::random(60);
$expiresAt = Carbon::now()->addMinutes(30); // expires in 30 minutes

// Save the token to the user in db
$user->magic_link_token = $token;
$user->magic_link_expires_at = $expiresAt;
$user->save();

// Send email
Mail::to($user->email)->send(new MagicLinkEmail($token));

return response()->json([
'status_code' => 200,
'status' => 'success',
'message' => 'Verification token sent to email',
], 200);
} catch (\Exception $e) {
return response()->json([
'status_code' => 500,
'status' => 'error',
'message' => 'Failed to send email',
], 500);
}
}
}
58 changes: 58 additions & 0 deletions app/Mail/MagicLinkEmail.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class MagicLinkEmail extends Mailable
{
use Queueable, SerializesModels;

public $token; // Add a public property to store the token

/**
* Create a new message instance.
*
* @param string $token
*/
public function __construct($token)
{
$this->token = $token; // Store the token
}

/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
return new Envelope(
subject: 'Your Magic Link for Login', // Customize the subject
);
}

/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
view: 'emails.magic_link', // Use the custom email view
with: ['token' => $this->token], // Pass the token to the view
);
}

/**
* Get the attachments for the message.
*
* @return array<int, \Illuminate\Mail\Mailables\Attachment>
*/
public function attachments(): array
{
return [];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddMagicLinkColumnsToUsersTable extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->string('magic_link_token', 100)->nullable()->after('remember_token');
$table->timestamp('magic_link_expires_at')->nullable()->after('magic_link_token');
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('magic_link_token');
$table->dropColumn('magic_link_expires_at');
});
}
}
122 changes: 122 additions & 0 deletions resources/docs/docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,128 @@
}
}
},
"/api/v1/auth/magic-link": {
"post": {
"summary": "Handle magic link authentication request",
"description": "This endpoint allows users to sign in without a password by sending a one-time login token to their email.",
"tags": ["Authentication"],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"email": {
"type": "string",
"format": "email",
"example": "user@example.com"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Verification token sent to email",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"status_code": {
"type": "integer",
"example": 200
},
"message": {
"type": "string",
"example": "Verification token sent to email"
}
}
}
}
}
},
"400": {
"description": "Invalid email format",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "error"
},
"status_code": {
"type": "integer",
"example": 400
},
"message": {
"type": "string",
"example": "Invalid email address"
}
}
}
}
}
},
"404": {
"description": "Email does not exist",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "error"
},
"status_code": {
"type": "integer",
"example": 404
},
"message": {
"type": "string",
"example": "User not found"
}
}
}
}
}
},
"500": {
"description": "Email sending failed",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "error"
},
"status_code": {
"type": "integer",
"example": 500
},
"message": {
"type": "string",
"example": "Failed to send email"
}
}
}
}
}
}
}
}
},
"/api/v1/users/stats": {
"get": {
"summary": "Get user statistics",
Expand Down
12 changes: 12 additions & 0 deletions resources/views/emails/magic_link.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<title>Magic Link Login</title>
</head>
<body>
<h1>Magic Link Login</h1>
<p>Click the link below to log in:</p>
<a href="{{ url('/api/v1/auth/magic-link/verify/' . $token) }}">Login with Magic Link</a>
<p>This link will expire in 30 minutes.</p>
</body>
</html>
3 changes: 3 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
use App\Http\Controllers\Api\V1\Auth\ForgetPasswordRequestController;
use App\Http\Controllers\Api\V1\SuperAdmin\SuperAdminProductController;
use App\Http\Controllers\Api\V1\Organisation\OrganisationMemberController;
use App\Http\Controllers\Api\V1\Auth\MagicLinkController;

/*
|--------------------------------------------------------------------------
Expand All @@ -76,6 +77,7 @@
Route::get('/api-status', [ApiStatusCheckerController::class, 'index']);
Route::post('/api-status', [ApiStatusCheckerController::class, 'store']);

// Auths
Route::post('/auth/register', [AuthController::class, 'store']);
Route::post('/auth/login', [LoginController::class, 'login']);
Route::post('/auth/logout', [LoginController::class, 'logout'])->middleware('auth:api');
Expand All @@ -86,6 +88,7 @@
Route::get('/auth/google/callback', [SocialAuthController::class, 'handleGoogleCallback']);
Route::post('/auth/google/callback', [SocialAuthController::class, 'saveGoogleRequest']);
Route::post('/auth/google', [SocialAuthController::class, 'saveGoogleRequestPost']);
Route::post('/auth/magic-link', [MagicLinkController::class, 'sendMagicLink']);
/* Forget and Reset Password using OTP */
Route::post('/auth/forgot-password', [ForgotResetPasswordController::class, 'forgetPassword']);
Route::post('/auth/reset-forgot-password', [ForgotResetPasswordController::class, 'resetPassword']);
Expand Down
Loading
Loading