PHP code example of draidel / laravel-supabase-auth

1. Go to this page and download the library: Download draidel/laravel-supabase-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

draidel / laravel-supabase-auth example snippets


'defaults' => [
    'guard' => 'supabase',
    'passwords' => 'users',
],

'guards' => [
    'supabase' => [
        'driver' => 'supabase',
        'provider' => 'supabase',
    ],
],

'providers' => [
    'supabase' => [
        'driver' => 'supabase',
        'model' => Supabase\\LaravelAuth\\Models\\SupabaseUser::class,
    ],
],

return [
    // Core Supabase settings
    'url' => env('SUPABASE_URL'),
    'anon_key' => env('SUPABASE_ANON_KEY'),
    'service_key' => env('SUPABASE_SERVICE_KEY'),
    'jwt' => [
        'secret' => env('SUPABASE_JWT_SECRET'),
        'algorithm' => env('SUPABASE_JWT_ALGORITHM', 'HS256'),
        'ttl' => env('SUPABASE_JWT_TTL', 3600),
    ],
    
    // Enterprise features
    'rate_limiting' => [
        'enabled' => env('SUPABASE_RATE_LIMITING_ENABLED', true),
        'login' => [
            'max_attempts' => env('SUPABASE_LOGIN_MAX_ATTEMPTS', 5),
            'decay_minutes' => env('SUPABASE_LOGIN_DECAY_MINUTES', 15),
        ],
    ],
    
    'circuit_breaker' => [
        'enabled' => env('SUPABASE_CIRCUIT_BREAKER_ENABLED', true),
        'failure_threshold' => env('SUPABASE_CB_FAILURE_THRESHOLD', 5),
        'recovery_timeout' => env('SUPABASE_CB_RECOVERY_TIMEOUT', 60),
    ],
    
    'cache' => [
        'enabled' => env('SUPABASE_CACHE_ENABLED', true),
        'store' => env('SUPABASE_CACHE_STORE', 'redis'),
        'ttl' => [
            'user_data' => env('SUPABASE_CACHE_USER_TTL', 300),
            'jwt_validation' => env('SUPABASE_CACHE_JWT_TTL', 60),
        ],
    ],
];

use Supabase\LaravelAuth\Facades\SupabaseAuth;

// Using the facade
$response = SupabaseAuth::signUp('[email protected]', 'password123', [
    'name' => 'John Doe',
    'timezone' => 'America/New_York',
]);

// Using API endpoint
POST /auth/supabase/register
{
    "email": "[email protected]",
    "password": "password123",
    "name": "John Doe"
}

use Illuminate\Support\Facades\Auth;

// Using Laravel's Auth facade (recommended)
if (Auth::attempt(['email' => $email, 'password' => $password])) {
    $user = Auth::user();
    // User is authenticated
}

// Using API endpoint
POST /auth/supabase/login
{
    "email": "[email protected]",
    "password": "password123",
    "remember": true
}

$user = Auth::user();

// Access Supabase-specific data
$supabaseData = $user->getSupabaseData();
$userId = $user->getSupabaseUserId();
$metadata = $user->getSupabaseUserMetadata();

// User attributes and methods
$user->hasVerifiedEmail();
$user->isAdmin();
$user->hasRole('premium');
$user->getTimezone();
$user->getPreferences();

// Update user profile
$user->updateSupabaseProfile(['name' => 'New Name']);

// Change password
$user->changeSupabasePassword('new-password');

// Generate OAuth URL
$oauthUrl = SupabaseAuth::signInWithOAuth('google', [
    'redirectTo' => config('app.url') . '/auth/callback',
    'scopes' => 'email profile',
]);

return redirect($oauthUrl);

// Request password reset
SupabaseAuth::resetPasswordForEmail('[email protected]', $redirectUrl);

// Update password (with access token)
SupabaseAuth::updatePassword($accessToken, 'new-password');

// Verify OTP
$response = SupabaseAuth::verifyOtp('[email protected]', '123456', 'email');

// Resend verification email
SupabaseAuth::resendOtp('[email protected]', 'signup');

use Supabase\LaravelAuth\Http\Middleware\AuthenticateSupabase;

Route::middleware('auth:supabase')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/profile', [ProfileController::class, 'show']);
});

use Supabase\LaravelAuth\Http\Middleware\EnsureTokenIsValid;

// Ensure token is valid and auto-refresh if needed
Route::middleware(EnsureTokenIsValid::class)->group(function () {
    Route::get('/api/user', [ApiController::class, 'user']);
});

use Supabase\LaravelAuth\Http\Middleware\RedirectIfAuthenticated;

Route::middleware(RedirectIfAuthenticated::class)->group(function () {
    Route::get('/login', [AuthController::class, 'showLoginForm']);
    Route::get('/register', [AuthController::class, 'showRegistrationForm']);
});

$health = app(SupabaseClient::class)->healthCheck();

// Returns:
// [
//     'status' => 'healthy',
//     'response_time_ms' => 45.2,
//     'timestamp' => '2024-01-01T12:00:00Z'
// ]

$circuitBreaker = app(CircuitBreakerInterface::class);

if ($circuitBreaker->isOpen('supabase')) {
    // Service is temporarily unavailable
}

$rateLimiter = app(RateLimiterInterface::class);
$status = $rateLimiter->getStatus($key, $maxAttempts);

// Returns attempt count, retries left, etc.

use Supabase\LaravelAuth\Traits\HasSupabaseAuth;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasSupabaseAuth;
    
    // Your custom implementation
    protected $fillable = [
        'id', 'email', 'name', 'company_id', 'role',
    ];
    
    public function company()
    {
        return $this->belongsTo(Company::class);
    }
}

'providers' => [
    'supabase' => [
        'driver' => 'supabase',
        'model' => App\\Models\\User::class,
    ],
],

use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;

Event::listen(Login::class, function (Login $event) {
    // User logged in
    $user = $event->user;
    $guard = $event->guard; // 'supabase'
});

Event::listen(Logout::class, function (Logout $event) {
    // User logged out
});

$this->app->bind(SupabaseAuthInterface::class, CustomSupabaseAuth::class);
$this->app->bind(CircuitBreakerInterface::class, CustomCircuitBreaker::class);

use Supabase\LaravelAuth\Services\SupabaseClient;

public function test_user_registration()
{
    $mockClient = Mockery::mock(SupabaseClient::class);
    $mockClient->shouldReceive('request')
        ->andReturn(['user' => ['id' => 'test-id']]);
    
    $this->app->instance(SupabaseClient::class, $mockClient);
    
    $response = $this->postJson('/auth/supabase/register', [
        'email' => '[email protected]',
        'password' => 'password123',
    ]);
    
    $response->assertSuccessful();
}

interface SupabaseAuthInterface
{
    public function signUp(string $email, string $password, array $data = []): array;
    public function signIn(string $email, string $password): array;
    public function signOut(string $accessToken): array;
    public function refreshToken(string $refreshToken): array;
    public function getUser(string $accessToken): array;
    public function updateUser(string $accessToken, array $data): array;
    public function resetPasswordForEmail(string $email, ?string $redirectTo = null): array;
    public function updatePassword(string $accessToken, string $newPassword): array;
    public function verifyOtp(string $email, string $token, string $type = 'email'): array;
    public function resendOtp(string $email, string $type = 'signup'): array;
    public function signInWithOAuth(string $provider, array $options = []): string;
    public function verifyToken(string $token): array;
    public function getUserById(string $userId): array;
    public function deleteUser(string $userId): array;
}

use Supabase\LaravelAuth\Exceptions\AuthenticationException;
use Supabase\LaravelAuth\Exceptions\ConfigurationException;
use Supabase\LaravelAuth\Exceptions\CircuitBreakerException;

try {
    SupabaseAuth::signIn($email, $password);
} catch (AuthenticationException $e) {
    // Handle authentication errors
    if ($e->getCode() === 401) {
        return response()->json(['error' => 'Invalid credentials'], 401);
    }
} catch (CircuitBreakerException $e) {
    // Handle service unavailable
    return response()->json(['error' => 'Service temporarily unavailable'], 503);
}
bash
php artisan vendor:publish --tag=supabase-auth-config
php artisan vendor:publish --tag=supabase-auth-migrations
bash
php artisan migrate
bash
# Test Supabase connection
php artisan supabase:test-connection

# With detailed diagnostics
php artisan supabase:test-connection --detailed --reset-circuit-breaker
bash
   php artisan supabase:test-connection --detailed
   
bash
   php artisan supabase:clear-cache --stats