2019-03-26 05:46:08 +01:00
|
|
|
<?php
|
2019-05-11 05:32:07 +02:00
|
|
|
/**
|
|
|
|
* Invoice Ninja (https://invoiceninja.com)
|
|
|
|
*
|
|
|
|
* @link https://github.com/invoiceninja/invoiceninja source repository
|
|
|
|
*
|
|
|
|
* @copyright Copyright (c) 2019. Invoice Ninja LLC (https://invoiceninja.com)
|
|
|
|
*
|
|
|
|
* @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;
|
|
|
|
use Closure;
|
|
|
|
|
|
|
|
class TokenAuth
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Handle an incoming request.
|
|
|
|
*
|
|
|
|
* @param \Illuminate\Http\Request $request
|
|
|
|
* @param \Closure $next
|
|
|
|
* @return mixed
|
|
|
|
*/
|
|
|
|
public function handle($request, Closure $next)
|
|
|
|
{
|
|
|
|
|
2019-06-12 01:15:17 +02:00
|
|
|
if( $request->header('X-API-TOKEN') && ($company_token = CompanyToken::with(['user','company'])->whereRaw("BINARY `token`= ?",[$request->header('X-API-TOKEN')])->first() ) )
|
2019-03-27 05:50:13 +01:00
|
|
|
{
|
2019-06-12 01:15:17 +02:00
|
|
|
$user = $company_token->user;
|
2019-03-27 10:38:28 +01:00
|
|
|
|
2019-06-12 01:15:17 +02:00
|
|
|
/*
|
|
|
|
|
|
|
|
|
| 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);
|
|
|
|
|
|
|
|
//stateless, don't remember the user.
|
|
|
|
auth()->login($user, false);
|
|
|
|
|
2019-06-05 07:33:48 +02:00
|
|
|
event(new UserLoggedIn($user));
|
2019-03-26 05:46:08 +01:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
|
2019-04-18 08:11:37 +02:00
|
|
|
return response()->json(json_encode(['message' => 'Invalid token'], JSON_PRETTY_PRINT) ,403);
|
2019-03-26 05:46:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return $next($request);
|
|
|
|
}
|
|
|
|
}
|