1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-18 09:04:35 +01:00
invoiceninja/app/Http/Middleware/TokenAuth.php

85 lines
2.4 KiB
PHP
Raw Normal View History

2019-03-26 05:46:08 +01:00
<?php
2019-05-11 05:32:07 +02:00
/**
* Invoice Ninja (https://invoiceninja.com).
2019-05-11 05:32:07 +02:00
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com)
2019-05-11 05:32:07 +02:00
*
* @license https://opensource.org/licenses/AAL
*/
2019-03-26 05:46:08 +01:00
namespace App\Http\Middleware;
2019-06-05 07:33:48 +02:00
use App\Events\User\UserLoggedIn;
2019-03-26 05:46:08 +01:00
use App\Models\CompanyToken;
use App\Models\User;
2020-07-08 14:02:16 +02:00
use App\Utils\Ninja;
2019-03-26 05:46:08 +01:00
use Closure;
2020-10-28 11:10:49 +01:00
use Illuminate\Http\Request;
use stdClass;
2019-03-26 05:46:08 +01:00
class TokenAuth
{
/**
* Handle an incoming request.
*
2020-10-28 11:10:49 +01:00
* @param Request $request
* @param Closure $next
2019-03-26 05:46:08 +01:00
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->header('X-API-TOKEN') && ($company_token = CompanyToken::with(['user', 'company'])->whereRaw('BINARY `token`= ?', [$request->header('X-API-TOKEN')])->first())) {
$user = $company_token->user;
2019-09-24 00:37:38 +02:00
$error = [
'message' => 'User inactive',
2020-10-28 11:10:49 +01:00
'errors' => new stdClass,
2019-09-24 00:37:38 +02:00
];
//user who once existed, but has been soft deleted
if (! $user) {
return response()->json($error, 403);
}
/*
|
| Necessary evil here: As we are authenticating on CompanyToken,
| we need to link the company to the user manually. This allows
| us to decouple a $user and their attached companies completely.
|
*/
$user->setCompany($company_token->company);
app('queue')->createPayloadUsing(function () use ($company_token) {
return ['db' => $company_token->company->db];
});
2019-09-24 00:37:38 +02:00
//user who once existed, but has been soft deleted
if ($company_token->company_user->is_locked) {
2019-09-24 00:37:38 +02:00
$error = [
'message' => 'User access locked',
2020-10-28 11:10:49 +01:00
'errors' => new stdClass,
2019-09-24 00:37:38 +02:00
];
return response()->json($error, 403);
2019-09-24 00:37:38 +02:00
}
//stateless, don't remember the user.
auth()->login($user, false);
2020-07-08 14:02:16 +02:00
event(new UserLoggedIn($user, $company_token->company, Ninja::eventVars()));
2021-03-09 05:43:54 +01:00
} else {
2019-09-24 00:37:38 +02:00
$error = [
'message' => 'Invalid token',
2020-10-28 11:10:49 +01:00
'errors' => new stdClass,
2019-09-24 00:37:38 +02:00
];
return response()->json($error, 403);
2019-03-26 05:46:08 +01:00
}
return $next($request);
}
}