Git Product home page Git Product logo

scoped-auth's Introduction

Scoped Auth

Build Status Coverage Status Scrutinizer Code Quality

Apply specific scope for user authentication.

Requirements

  • PHP: ^8.0
  • Laravel: ^9.0 || ^10.0

Installing

Via Composer

$ composer require mpyw/scoped-auth

For Fortify users

Warning

Default Fortify's RedirectIfTwoFactorAuthenticatable implementation directly uses internal Model under UserProvider, however, the Laravel author won't be willing to fix it for whatever reason. So we need to configure Fortify like this:

CustomFortifyAuthenticator.php
<?php

namespace App\Auth;

use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Contracts\Auth\UserProvider;
use Laravel\Fortify\Fortify;

class CustomFortifyAuthenticator
{
    private const PASSWORD_NAME = 'password';

    private readonly UserProvider $provider;

    public function __construct(StatefulGuard $guard)
    {
        // Assert `StatefulGuard` has `getProvider()` which is not declared in the contract
        assert(method_exists($guard, 'getProvider'));
        $provider = $guard->getProvider();

        assert($provider instanceof UserProvider);
        $this->provider = $provider;
    }

    public function __invoke(Request $request): ?Authenticatable
    {
        $user = $this->provider->retrieveByCredentials([
            Fortify::username() => $request->input(Fortify::username()),
        ]);

        return $user && $this->provider->validateCredentials($user, [
            self::PASSWORD_NAME => $request->input(self::PASSWORD_NAME),
        ]) ? $user : null;
    }
}
AuthServiceProvider.php
<?php

namespace App\Providers;

use App\Auth\CustomFortifyAuthenticator;
use Illuminate\Support\ServiceProvider;
use Laravel\Fortify\Fortify;

class AuthServiceProvider extends ServiceProvider
{
    public function boot(CustomFortifyAuthenticator $authenticator): void
    {
        Fortify::authenticateUsing($authenticator);
    }
}

Testing

Via PHPUnit

$ composer test

Usage

Implement AuthScopable contract on your Authenticatable Eloquent Model.

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Mpyw\ScopedAuth\AuthScopable;

class User extends Model implements UserContract, AuthScopable
{
    use Authenticatable;

    public function scopeForAuthentication(Builder $query): Builder
    {
        return $query->where('active', 1);
    }
}
<?php

use Illuminate\Support\Facades\Auth;

$user = Auth::user(); // Only include users where "active" is 1

Note that you can reuse another existing scope.

public function scopeActive(Builder $query): Builder
{
    return $query->where('active', 1);
}

public function scopeForAuthentication(Builder $query): Builder
{
    return $this->scopeActive($query);
}

As a by-product, you can also run scope queries based on the standard Eloquent way.

$user = User::where('email', '[email protected]')->forAuthentication()->firstOrFail();
$user = User::where('email', '[email protected]')->scopes(['forAuthentication'])->firstOrFail();

Standards

Credits

License

Licensed under the MIT License. See License File for more information.

scoped-auth's People

Contributors

hexium310 avatar mpyw avatar wand2016 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

scoped-auth's Issues

Support for Fortify

It seems this extension doesn't support Laravel 9.

When debugging I notice that even though it hits ScopedAuthServiceProvider::register(), ScopedEloquentUserProvider::newModelQuery() is not called when logging in.

Why this not working for only login attempts?

For Soft Deleted, param deleted_at; Laravel login attempt for a deleted user; attempt login will return false if user is deleted or user will be logout if in a deleted user.

How make invalidate user session if deactivated_at column is not null, like deleted_at?

Only using query when login attempts?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.