Skip to content

Commit

Permalink
feat: add default middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
mychidarko committed Dec 15, 2024
1 parent 5b9458d commit 86ee8f7
Showing 1 changed file with 39 additions and 6 deletions.
45 changes: 39 additions & 6 deletions src/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,33 @@ class Auth
*/
protected $errorsArray = [];

public function __construct()
{
$this->middleware('auth.required', function () {
response()->redirect('/auth/login', 401);
});

$this->middleware('auth.guest', function () {
response()->json('/dashboard', 401);
});

$this->middleware('is', function ($role) {
\Leaf\Exception\General::default404();
});

$this->middleware('isNot', function () {
\Leaf\Exception\General::default404();
});

$this->middleware('can', function () {
\Leaf\Exception\General::default404();
});

$this->middleware('cannot', function () {
\Leaf\Exception\General::default404();
});
}

/**
* Connect leaf auth to the database
* @param array $dbConfig Configuration for leaf db connection
Expand Down Expand Up @@ -594,6 +621,7 @@ public function middleware(string $middleware, callable $callback)
return app()->registerMiddleware('auth.required', function () use ($callback) {
if (!$this->user()) {
$callback();
exit;
}
});
}
Expand All @@ -602,6 +630,7 @@ public function middleware(string $middleware, callable $callback)
return app()->registerMiddleware('auth.guest', function () use ($callback) {
if ($this->user()) {
$callback();
exit;
}

auth()->clearErrors();
Expand All @@ -611,31 +640,35 @@ public function middleware(string $middleware, callable $callback)
if ($middleware === 'is') {
return app()->registerMiddleware('is', function ($role) use ($callback) {
if ($this->user()?->isNot($role)) {
$callback();
$callback($role);
exit;
}
});
}

if ($middleware === 'isNot') {
return app()->registerMiddleware('isNot', function ($role) use ($callback) {
if ($this->user()?->is($role)) {
$callback();
$callback($role);
exit;
}
});
}

if ($middleware === 'can') {
return app()->registerMiddleware('can', function ($role) use ($callback) {
if ($this->user()?->can($role)) {
$callback();
if ($this->user()?->cannot($role)) {
$callback($role);
exit;
}
});
}

if ($middleware === 'cannot') {
return app()->registerMiddleware('cannot', function ($role) use ($callback) {
if ($this->user()?->cannot($role)) {
$callback();
if ($this->user()?->can($role)) {
$callback($role);
exit;
}
});
}
Expand Down

0 comments on commit 86ee8f7

Please sign in to comment.