summaryrefslogtreecommitdiff
path: root/src/AuthSubscriber.php
blob: 1827ae5142e4772bd16b29be910e02573e56dfc9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php

namespace Lightscale\LaralightAuthLog;

use Lightscale\LaralightAuthLog\Models\AuthLog;
use Lightscale\LaralightAuthLog\Enums\Status;

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

class AuthSubscriber
{

    private function handleEvent(Status $status, mixed $event, iterable $props): void
    {
        $log = new AuthLog([
            'status' => $status,
            'properties' => $props,
        ]);
        $log->user()->associate($event->user);
        $log->save();
    }

    public function handleLogin(Login $event): void
    {
        $this->handleEvent(Status::LoginSuccess, $event);
    }

    public function handleFailed(Failed $event): void
    {
        $creds = collect($event->credentials)->except('password');
        $this->handleEvent(Status::LoginFailure, $event, $creds);
    }

    public function handleLogout(Logout $event): void
    {
        $this->handleEvent(Status::Logout, $event);
    }

    public function subscribe(Dispatcher $events): array
    {
        return [
            Login::class => 'handleLogin',
            Failed::class => 'handleFailed',
            Logout::class => 'handleLogout',
        ];
    }
}