PHPackages                             ikechukwukalu/sanctumauthstarter - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. ikechukwukalu/sanctumauthstarter

AbandonedArchivedLibrary

ikechukwukalu/sanctumauthstarter
================================

Laravel sanctum auth starter

v2.0.2(2y ago)101.7k1[2 PRs](https://github.com/ikechukwukalu/sanctumauthstarter/pulls)MITPHPPHP ^8.0

Since Jan 17Pushed 2y ago1 watchersCompare

[ Source](https://github.com/ikechukwukalu/sanctumauthstarter)[ Packagist](https://packagist.org/packages/ikechukwukalu/sanctumauthstarter)[ RSS](/packages/ikechukwukalu-sanctumauthstarter/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (31)Versions (15)Used By (0)

SANCTUM AUTH STARTER
====================

[](#sanctum-auth-starter)

[![Latest Version on Packagist](https://camo.githubusercontent.com/fd2972dfbcf1824120f7b8111f5d559075ff678c1c9b1478feca6dcd32eaf64d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696b656368756b77756b616c752f73616e6374756d61757468737461727465723f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ikechukwukalu/sanctumauthstarter)[![Quality Score](https://camo.githubusercontent.com/37db3cbbbc5ce6710ecd523950d9c2eec698481bc085390f4362ac696fa3ddec/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f7175616c6974792f672f696b656368756b77756b616c752f73616e6374756d61757468737461727465722f6d61696e3f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/ikechukwukalu/sanctumauthstarter/)[![Code Quality](https://camo.githubusercontent.com/6647a0896e5b68209cef42213425625f57e593c7b2c06ae895452dd58fbe3383/68747470733a2f2f696d672e736869656c64732e696f2f636f6465666163746f722f67726164652f6769746875622f696b656368756b77756b616c752f73616e6374756d61757468737461727465723f7374796c653d666c61742d737175617265)](https://www.codefactor.io/repository/github/ikechukwukalu/sanctumauthstarter)[![Known Vulnerabilities](https://camo.githubusercontent.com/c325b266bf305a27f51cf940a9564bd9ce5b43dd7637ba10288140de3548d9f4/68747470733a2f2f736e796b2e696f2f746573742f6769746875622f696b656368756b77756b616c752f73616e6374756d61757468737461727465722f62616467652e7376673f7374796c653d666c61742d737175617265)](https://security.snyk.io/package/composer/ikechukwukalu%2Fsanctumauthstarter)[![Github Workflow Status](https://camo.githubusercontent.com/f72feef5518106d867ea3b51437912ae130e52dbbe77ccc8c4f2009584961c39/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f696b656368756b77756b616c752f73616e6374756d61757468737461727465722f73616e6374756d61757468737461727465722e796d6c3f6272616e63683d6d61696e267374796c653d666c61742d737175617265)](https://github.com/ikechukwukalu/sanctumauthstarter/actions/workflows/sanctumauthstarter.yml)[![Total Downloads](https://camo.githubusercontent.com/db5b8da7b2b76d683437790fd4f6e149e6dd54887898b75e1b66ec6265a8b94b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f696b656368756b77756b616c752f73616e6374756d61757468737461727465723f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ikechukwukalu/sanctumauthstarter)[![Licence](https://camo.githubusercontent.com/06e24d7eb64b4e4fd4a9860ef3bc8129a7006309c0a8baa410471f3fb144bf5f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f696b656368756b77756b616c752f73616e6374756d61757468737461727465723f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ikechukwukalu/sanctumauthstarter)

This is a very flexible and customisable laravel package (boilerplate) that utilises [laravel/ui](https://github.com/laravel/ui) and [laravel-sanctum](https://laravel.com/docs/9.x/sanctum) to create Basic Authetication classes and other helpful functionalities to give you a quick start when building REST APIs using [Laravel](https://laravel.com/). The following functionalities are made available:

- User registration
- User login
- Auto login after registration
- Login throttling
- Login 2FA
- Social media login
- Forgot password
- Email verification
- Resend email verification
- Reset password
- Change password
- Edit user profile
- Notifications
    - Welcome notification
    - Email verification
    - Login notification
    - Password change notification
- Generate documentation
- Helper CI/CD files for GitHub

REQUIREMENTS
------------

[](#requirements)

- PHP 8+
- Laravel 9+

STEPS TO INSTALL
----------------

[](#steps-to-install)

```
composer require ikechukwukalu/sanctumauthstarter
```

- `php artisan ui bootstrap`
- `npm install --save-dev laravel-echo pusher-js`
- Uncomment `use Illuminate\Contracts\Auth\MustVerifyEmail;` in `User` model class
- Add `two_factor` columns to the `fillable` and `hidden` arrays within the `User` model class. At the end the `User` should look similar to this:

```
use Laravel\Sanctum\HasApiTokens;
use Laragear\TwoFactor\TwoFactorAuthentication;
use Laragear\TwoFactor\Contracts\TwoFactorAuthenticatable;

class User extends Authenticatable implements TwoFactorAuthenticatable, MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable, TwoFactorAuthentication;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'two_factor',
        'socialite_signup',
        'form_signup'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}
```

GENERATE AUTH CONTROLLERS, REQUESTS, SERVICES AND ROUTES
--------------------------------------------------------

[](#generate-auth-controllers-requests-services-and-routes)

You can run `php artisan sas:setup` to generate them at once. You can also call generate them separately:

- `php artisan sas:controllers`
- `php artisan sas:routes`
- `php artisan sas:tests`

PUBLISH MIGRATIONS AND CONFIG
-----------------------------

[](#publish-migrations-and-config)

- `php artisan vendor:publish --tag=sas-migrations`
- `php artisan vendor:publish --tag=sas-config`

WEBSOCKETS AND QUEUES
---------------------

[](#websockets-and-queues)

This package utilizes laravel [beyondcode/laravel-websockets](https://beyondco.de/docs/laravel-websockets/getting-started/introduction) to pass `access_token` to the client after authentication. First, you must setup your laravel app for broadcasts. In order to do that run the following:

- `php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"`
- `php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"`
- Set `REDIS_CLIENT=predis` and `BROADCAST_DRIVER=pusher` within your `.env` file.
- Your `laravel-echo` config should look similar to this:

```
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    wsHost: window.location.hostname,
    wsPort: 6001,
    forceTLS: false,
    encrypted: false,
    enabledTransports: ['ws', 'wss'],
    disableStats: true,
    cluster:import.meta.env.VITE_PUSHER_APP_CLUSTER,
    authorizer: (channel, options) => {
        return {
            authorize: (socketId, callback) => {
                axios.post('/broadcasting/auth', {
                    socket_id: socketId,
                    channel_name: channel.name
                })
                .then(response => {
                    callback(false, response.data);
                })
                .catch(error => {
                    callback(true, error);
                });
            }
        };
    },
});
```

You will need a [queue](https://laravel.com/docs/9.x/queues#introduction) worker for the notifications and other events.

- Set `QUEUE_CONNECTION=redis` within your `.env` file.
- Uncomment `App\Providers\BroadcastServiceProvider::class` in `config\app.php`
- Your `.env` should look similar to this

```
PUSHER_APP_KEY=app-key
PUSHER_APP_ID=app-id
PUSHER_APP_SECRET=app-secret
PUSHER_HOST=127.0.0.1
PUSHER_PORT=6001
PUSHER_SCHEME=http
PUSHER_APP_CLUSTER=mt1
```

- For SSL using apache. The snippet below should be placed within the `virtualhost` SSL config.

```
    ProxyPass "/app/" "ws://127.0.0.1:6001/app/"
    ProxyPass "/app/" "http://127.0.0.1:6001/app/"
```

- Run `php artisan config:clear`, `php artisan migrate`, `php artisan websockets:serve` and `php artisan queue:work`
- `php artisan serve`
- `npm install && npm run dev`

WEBVIEW LOGINS
--------------

[](#webview-logins)

- Social media login
- Two-factor login

### Social Media Login

[](#social-media-login)

Add the following to your `config/services.php` file.

```
'google' => [
    'client_id' => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect' => env('GOOGLE_CLIENT_REDIRECT'),
],
```

- Navigate to `auth/socialite` to view a sample Google sign-up/sign-in page to view the generated `access_token` after sign up. Uncomment the route within the `web.php`. Below is the script that is called within the view `resources/views/vendor/sanctumauthstarter/socialite/auth.blade.php`.

```
window.addEventListener('DOMContentLoaded',  () => {
    const getUserUUID = () => {
        let userUUID = localStorage.getItem('user_uuid');

        if (!userUUID) {
            userUUID = crypto.randomUUID();
            localStorage.setItem('user_uuid', userUUID);
        }

        console.log('user_uuid created', userUUID);
        return userUUID;
    }

    const removeUserUUID = () => {
        if (localStorage.getItem('user_uuid')) {
            localStorage.removeItem('user_uuid');
        }

        console.log('user_uuid removed');
    }

    const USER_UUID = getUserUUID();
    const TIMEOUT = parseInt("{{ $minutes }}") * 60 * 1000;

    window.Echo.channel(`access.token.socialite.${USER_UUID}`)
    .listen('.Ikechukwukalu\\Sanctumauthstarter\\Events\\SocialiteLogin', (e) => {
        console.log(`payload:`, e);
    });

    document.getElementById('googleSignUp').onclick = () => {
        window.open(
            "{{ url('auth/redirect') }}/" + USER_UUID,
            '_blank'
        )
    }

    setTimeout(() => {
        removeUserUUID();
    }, TIMEOUT);
});
```

- After a successful authentication, this view is displayed `resources/views/vendor/sanctumauthstarter/socialite/callback.blade.php` and it contains the following script:

```
window.addEventListener('DOMContentLoaded',  () => {
    if (localStorage.getItem('user_uuid')) {
        localStorage.removeItem('user_uuid');
    }
});
```

### Two-factor Login

[](#two-factor-login)

This package utilizes [Laragear/TwoFactor](https://github.com/Laragear/TwoFactor) to power 2fa login and [beyondcode/laravel-websockets](https://beyondco.de/docs/laravel-websockets/getting-started/introduction) to pass `access_token` to the client after authentication.

2fa authentication has been implemented for both password login and social media login.

- `php artisan vendor:publish --provider="Laragear\TwoFactor\TwoFactorServiceProvider"`
- `php artisan migrate`
- Replace the form in `resources/views/vendor/two-factor/login.blade.php` with the code below:

```

    @php
        foreach ($_GET as $key => $value) {
            $key = htmlspecialchars($key);
            $value = htmlspecialchars($value);
            echo "";
        }
    @endphp
    @csrf

        {{ trans('two-factor::messages.continue') }}

        @if($errors->isNotEmpty() || isset($message))

                    @if (isset($message))
                        {{ $message }}
                    @endif
                    @foreach ($errors->all() as $error)
                        {{ $error }}
                    @endforeach

        @endif

                {{ trans('two-factor::messages.confirm') }}

```

- Call `api/create-two-factor` to create 2fa.

```
{
    "status": "success",
    "status_code": 200,
    "data": {
        "qr_code": "\n
