1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-14 07:02:34 +01:00
invoiceninja/app/Http/Middleware/TokenAuth.php
David Bomba 3d31f810c0
Set Invitations as a default include for invoices (#3362)
* Working on importing company gateways

* Fix for companyuser settings object

* Migrate client_gateway_tokens

* Working on Notificaitons

* Working on notifications

* Failsafe for user-company

* unlink files

* Set DB for jobs

* Always have a fallback for company_id

* Fixes for user model

* Formatting for MultiDB

* Working on Company Ledger Tests

* Fixes for contact request

* Set Invitations as a default include for invoices
2020-02-24 21:15:30 +11:00

84 lines
2.4 KiB
PHP

<?php
/**
* Invoice Ninja (https://invoiceninja.com)
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2020. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://opensource.org/licenses/AAL
*/
namespace App\Http\Middleware;
use App\Events\User\UserLoggedIn;
use App\Models\CompanyToken;
use App\Models\User;
use Closure;
class TokenAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @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;
$error = [
'message' => 'User inactive',
'errors' => []
];
//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);
config(['ninja.company_id' => $company_token->company->id]);
app('queue')->createPayloadUsing(function () use($company_token) {
return ['db' => $company_token->company->db];
});
//user who once existed, but has been soft deleted
if ($user->company_user->is_locked) {
$error = [
'message' => 'User access locked',
'errors' => []
];
return response()->json($error, 403);
}
//stateless, don't remember the user.
auth()->login($user, false);
event(new UserLoggedIn($user));
} else {
$error = [
'message' => 'Invalid token',
'errors' => []
];
return response()->json($error, 403);
}
return $next($request);
}
}