1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-11 05:32:39 +01:00
invoiceninja/app/Http/Middleware/TokenAuth.php

83 lines
2.3 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
*
2021-06-16 08:58:16 +02:00
* @license https://www.elastic.co/licensing/elastic-license
2019-05-11 05:32:07 +02:00
*/
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.
|
*/
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);
2021-05-24 02:41:23 +02:00
auth()->user()->setCompany($company_token->company);
} 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);
}
}