akaunting/app/Http/Middleware/IdentifyCompany.php

84 lines
2.2 KiB
PHP
Raw Normal View History

2021-04-16 00:59:43 +03:00
<?php
namespace App\Http\Middleware;
use App\Traits\Users;
use Closure;
use Illuminate\Auth\AuthenticationException;
class IdentifyCompany
{
use Users;
public $request;
2021-04-16 00:59:43 +03:00
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string[] ...$guards
* @return mixed
*
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
$this->request = $request;
$company_id = $this->request->isApi()
? $this->getCompanyIdFromApi()
: $this->getCompanyIdFromWeb();
2021-04-16 00:59:43 +03:00
if (empty($company_id)) {
abort(500, 'Missing company');
}
// Check if user can access company
if ($this->request->isNotSigned($company_id) && $this->isNotUserCompany($company_id)) {
2021-04-16 00:59:43 +03:00
throw new AuthenticationException('Unauthenticated.', $guards);
}
// Set company as current
company($company_id)->makeCurrent();
2021-04-21 09:18:45 +03:00
// Fix file/folder paths
config(['filesystems.disks.' . config('filesystems.default') . '.url' => url('/' . $company_id) . '/uploads']);
2021-04-16 00:59:43 +03:00
// Fix routes
if ($this->request->isNotApi()) {
app('url')->defaults(['company_id' => $company_id]);
$this->request->route()->forgetParameter('company_id');
}
2021-04-16 00:59:43 +03:00
return $next($this->request);
2021-04-16 00:59:43 +03:00
}
protected function getCompanyIdFromWeb()
2021-04-16 00:59:43 +03:00
{
return $this->getCompanyIdFromRoute() ?: ($this->getCompanyIdFromQuery() ?: $this->getCompanyIdFromHeader());
2021-04-16 00:59:43 +03:00
}
protected function getCompanyIdFromApi()
2021-04-16 00:59:43 +03:00
{
$company_id = $this->getCompanyIdFromQuery() ?: $this->getCompanyIdFromHeader();
2021-04-16 00:59:43 +03:00
return $company_id ?: optional($this->getFirstCompanyOfUser())->id;
}
protected function getCompanyIdFromRoute()
{
return (int) $this->request->route('company_id');
}
protected function getCompanyIdFromQuery()
{
return (int) $this->request->query('company_id');
}
protected function getCompanyIdFromHeader()
{
return (int) $this->request->header('X-Company');
}
2021-04-16 00:59:43 +03:00
}