1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-10 21:22:58 +01:00
invoiceninja/app/Http/Controllers/Auth/LoginController.php

537 lines
19 KiB
PHP
Raw Normal View History

2018-10-04 19:10:43 +02: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
*/
2018-10-04 19:10:43 +02:00
2019-05-22 03:24:05 +02:00
namespace App\Http\Controllers\Auth;
2018-10-04 19:10:43 +02:00
2020-04-30 14:33:57 +02:00
use App\DataMapper\Analytics\LoginFailure;
use App\DataMapper\Analytics\LoginSuccess;
2021-05-12 08:18:32 +02:00
use App\Events\User\UserLoggedIn;
2019-04-19 04:58:40 +02:00
use App\Http\Controllers\BaseController;
2018-10-04 19:10:43 +02:00
use App\Http\Controllers\Controller;
use App\Jobs\Account\CreateAccount;
use App\Jobs\Company\CreateCompanyToken;
2021-05-12 08:31:02 +02:00
use App\Jobs\Util\SystemLogger;
use App\Libraries\MultiDB;
use App\Libraries\OAuth\OAuth;
use App\Libraries\OAuth\Providers\Google;
2021-05-12 08:31:02 +02:00
use App\Models\Client;
use App\Models\Company;
use App\Models\CompanyToken;
2019-09-11 12:15:44 +02:00
use App\Models\CompanyUser;
2021-05-12 08:31:02 +02:00
use App\Models\SystemLog;
use App\Models\User;
2019-09-11 12:15:44 +02:00
use App\Transformers\CompanyUserTransformer;
2021-05-12 08:18:32 +02:00
use App\Utils\Ninja;
use App\Utils\Traits\UserSessionAttributes;
2021-05-23 10:59:09 +02:00
use App\Utils\Traits\User\LoginCache;
2020-10-28 11:10:49 +01:00
use Google_Client;
2018-10-04 19:10:43 +02:00
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
2021-03-16 13:10:15 +01:00
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
2021-06-01 02:24:20 +02:00
use Laravel\Socialite\Facades\Socialite;
2021-03-16 13:10:15 +01:00
use PragmaRX\Google2FA\Google2FA;
use Turbo124\Beacon\Facades\LightLogs;
2018-10-04 19:10:43 +02:00
2019-04-19 04:58:40 +02:00
class LoginController extends BaseController
2018-10-04 19:10:43 +02:00
{
2020-10-10 14:07:52 +02:00
/**
* @OA\Tag(
* name="login",
* description="Authentication",
* @OA\ExternalDocumentation(
* description="Find out more",
* url="http://docs.invoiceninja.com"
* )
* )
*/
2018-10-04 19:10:43 +02:00
use AuthenticatesUsers;
use UserSessionAttributes;
2021-05-23 10:59:09 +02:00
use LoginCache;
2019-09-12 14:02:25 +02:00
protected $entity_type = CompanyUser::class;
2019-04-19 04:58:40 +02:00
2019-09-12 14:02:25 +02:00
protected $entity_transformer = CompanyUserTransformer::class;
2019-04-19 04:58:40 +02:00
2018-10-04 19:10:43 +02:00
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/dashboard';
2018-10-04 19:10:43 +02:00
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
2019-04-19 04:58:40 +02:00
parent::__construct();
2018-10-04 19:10:43 +02:00
}
/**
* Once the user is authenticated, we need to set
* the default company into a session variable.
*
2020-10-28 11:10:49 +01:00
* @param Request $request
* @param User $user
* @return void
2019-05-23 02:25:55 +02:00
* deprecated .1 API ONLY we don't need to set any session variables
*/
public function authenticated(Request $request, User $user) : void
{
2019-03-26 12:31:07 +01:00
//$this->setCurrentCompanyId($user->companies()->first()->account->default_company_id);
}
2019-05-23 02:25:55 +02:00
/**
* Login via API.
2019-05-23 02:25:55 +02:00
*
2020-10-28 11:10:49 +01:00
* @param Request $request The request
2019-05-23 02:25:55 +02:00
*
* @return Response|User Process user login.
2019-10-07 00:00:02 +02:00
*
*
2020-10-28 11:10:49 +01:00
* @throws \Illuminate\Validation\ValidationException
2019-10-06 08:05:46 +02:00
* @OA\Post(
* path="/api/v1/login",
* operationId="postLogin",
* tags={"login"},
* summary="Attempts authentication",
* description="Returns a CompanyUser object on success",
* @OA\Parameter(ref="#/components/parameters/X-Api-Secret"),
* @OA\Parameter(ref="#/components/parameters/X-Api-Token"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\Parameter(ref="#/components/parameters/include"),
* @OA\Parameter(ref="#/components/parameters/include_static"),
* @OA\Parameter(ref="#/components/parameters/clear_cache"),
* @OA\RequestBody(
* description="User credentials",
* required=true,
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="email",
* description="The user email address",
* type="string",
* ),
* @OA\Property(
* property="password",
* example="1234567",
* description="The user password must meet minimum criteria ~ >6 characters",
* type="string"
* )
* )
* )
* ),
* @OA\Response(
* response=200,
* description="The Company User response",
* @OA\Header(header="X-MINIMUM-CLIENT-VERSION", ref="#/components/headers/X-MINIMUM-CLIENT-VERSION"),
2019-10-06 08:05:46 +02:00
* @OA\Header(header="X-RateLimit-Remaining", ref="#/components/headers/X-RateLimit-Remaining"),
* @OA\Header(header="X-RateLimit-Limit", ref="#/components/headers/X-RateLimit-Limit"),
2019-10-06 13:51:33 +02:00
* @OA\JsonContent(ref="#/components/schemas/CompanyUser"),
* ),
* @OA\Response(
* response=422,
* description="Validation error",
* @OA\JsonContent(ref="#/components/schemas/ValidationError"),
2019-10-06 08:05:46 +02:00
* ),
2019-10-06 13:24:54 +02:00
* @OA\Response(
* response="default",
2019-10-06 13:24:54 +02:00
* description="Unexpected Error",
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
2019-10-06 08:05:46 +02:00
* )
*/
2019-04-19 03:59:07 +02:00
public function apiLogin(Request $request)
{
$this->forced_includes = ['company_users'];
2019-04-19 03:59:07 +02:00
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
2019-09-11 07:32:47 +02:00
return response()
->json(['message' => 'Too many login attempts, you are being throttled'], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
}
2019-09-11 02:37:53 +02:00
if ($this->attemptLogin($request)) {
2021-03-16 13:10:15 +01:00
LightLogs::create(new LoginSuccess())
2020-04-30 14:33:57 +02:00
->increment()
->batch();
2020-08-08 01:58:10 +02:00
$user = $this->guard()->user();
2021-05-12 08:18:32 +02:00
event(new UserLoggedIn($user, $user->account->default_company, Ninja::eventVars($user->id)));
2021-05-23 10:43:50 +02:00
//2FA
2021-03-20 01:46:42 +01:00
if($user->google_2fa_secret && $request->has('one_time_password'))
2021-03-16 13:10:15 +01:00
{
$google2fa = new Google2FA();
2021-03-20 01:46:42 +01:00
if(strlen($request->input('one_time_password')) == 0 || !$google2fa->verifyKey(decrypt($user->google_2fa_secret), $request->input('one_time_password')))
2021-03-16 13:10:15 +01:00
{
return response()
->json(['message' => ctrans('texts.invalid_one_time_password')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
}
}
2021-03-18 12:46:58 +01:00
elseif($user->google_2fa_secret && !$request->has('one_time_password')) {
return response()
->json(['message' => ctrans('texts.invalid_one_time_password')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
}
2021-03-16 13:10:15 +01:00
2020-11-13 10:09:20 +01:00
$user->setCompany($user->account->default_company);
2021-05-05 08:44:31 +02:00
2021-05-23 10:43:50 +02:00
$this->setLoginCache($user);
2019-09-11 02:37:53 +02:00
2020-11-13 10:09:20 +01:00
$cu = CompanyUser::query()
->where('user_id', auth()->user()->id);
if(!$cu->exists())
return response()->json(['message' => 'User not linked to any companies'], 403);
2021-06-08 10:30:54 +02:00
/* Ensure the user has a valid token */
2021-06-08 10:42:37 +02:00
$user->company_users->each(function ($company_user) use($request){
2021-06-08 10:30:54 +02:00
if($company_user->tokens->count() == 0){
CreateCompanyToken::dispatchNow($company_user->company, $company_user->user, $request->server('HTTP_USER_AGENT'));
}
});
2021-06-08 10:30:54 +02:00
// $cu->first()->account->companies->each(function ($company) use($cu, $request){
// if($company->tokens()->where('is_system', true)->count() == 0)
// {
// CreateCompanyToken::dispatchNow($company, $cu->first()->user, $request->server('HTTP_USER_AGENT'));
// }
// });
2021-04-29 00:44:40 +02:00
return $this->timeConstrainedResponse($cu);
2021-05-23 10:43:50 +02:00
2021-03-16 13:10:15 +01:00
} else {
2021-03-16 13:10:15 +01:00
LightLogs::create(new LoginFailure())
2020-04-30 14:33:57 +02:00
->increment()
->batch();
2021-05-12 08:31:02 +02:00
SystemLogger::dispatch(
json_encode(['ip' => request()->getClientIp()]),
2021-05-12 08:31:02 +02:00
SystemLog::CATEGORY_SECURITY,
SystemLog::EVENT_USER,
SystemLog::TYPE_LOGIN_FAILURE,
null,
Company::first(),
2021-05-12 08:31:02 +02:00
);
$this->incrementLoginAttempts($request);
2019-09-11 07:32:47 +02:00
return response()
->json(['message' => ctrans('texts.invalid_credentials')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
2021-03-16 13:10:15 +01:00
}
2019-04-19 03:59:07 +02:00
}
2019-10-07 00:00:02 +02:00
/**
* Refreshes the data feed with the current Company User.
*
2020-10-28 11:10:49 +01:00
* @param Request $request
2019-10-07 00:00:02 +02:00
* @return CompanyUser Refresh Feed.
*
*
2019-10-07 00:00:02 +02:00
* @OA\Post(
* path="/api/v1/refresh",
* operationId="refresh",
* tags={"refresh"},
* summary="Refreshes the dataset",
* description="Refreshes the dataset",
* @OA\Parameter(ref="#/components/parameters/X-Api-Secret"),
* @OA\Parameter(ref="#/components/parameters/X-Api-Token"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\Parameter(ref="#/components/parameters/include"),
* @OA\Parameter(ref="#/components/parameters/include_static"),
* @OA\Parameter(ref="#/components/parameters/clear_cache"),
* @OA\Response(
* response=200,
* description="The Company User response",
* @OA\Header(header="X-MINIMUM-CLIENT-VERSION", ref="#/components/headers/X-MINIMUM-CLIENT-VERSION"),
2019-10-07 00:00:02 +02:00
* @OA\Header(header="X-RateLimit-Remaining", ref="#/components/headers/X-RateLimit-Remaining"),
* @OA\Header(header="X-RateLimit-Limit", ref="#/components/headers/X-RateLimit-Limit"),
* @OA\JsonContent(ref="#/components/schemas/CompanyUser"),
* ),
* @OA\Response(
* response=422,
* description="Validation error",
* @OA\JsonContent(ref="#/components/schemas/ValidationError"),
* ),
* @OA\Response(
* response="default",
2019-10-07 00:00:02 +02:00
* description="Unexpected Error",
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
*/
2019-09-25 13:49:43 +02:00
public function refresh(Request $request)
{
$company_token = CompanyToken::whereRaw('BINARY `token`= ?', [$request->header('X-API-TOKEN')])->first();
2020-08-11 12:57:45 +02:00
$cu = CompanyUser::query()
->where('user_id', $company_token->user_id);
$cu->first()->account->companies->each(function ($company) use($cu, $request){
if($company->tokens()->where('is_system', true)->count() == 0)
{
CreateCompanyToken::dispatchNow($company, $cu->first()->user, $request->server('HTTP_USER_AGENT'));
}
});
2021-04-29 13:36:34 +02:00
if($request->has('current_company') && $request->input('current_company') == 'true')
$cu->where("company_id", $company_token->company_id);
2020-08-11 12:57:45 +02:00
return $this->refreshResponse($cu);
2019-09-25 13:49:43 +02:00
}
/**
* A client side authentication has taken place.
* We now digest the token and confirm authentication with
* the authentication server, the correct user object
* is returned to us here and we send back the correct
* user object payload - or error.
*
* This can be extended to a create route also - need to pass a ?create query parameter and
2019-05-23 02:25:55 +02:00
* then process the signup
*
* return User $user
*/
public function oauthApiLogin()
{
if (request()->input('provider') == 'google') {
return $this->handleGoogleOauth();
}
2020-05-13 11:02:38 +02:00
return response()
->json(['message' => 'Provider not supported'], 400)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
}
private function handleGoogleOauth()
{
$user = false;
$google = new Google();
$user = $google->getTokenResponse(request()->input('id_token'));
if (is_array($user)) {
2021-03-16 12:29:16 +01:00
2021-05-22 06:45:09 +02:00
//
$query = [
2020-05-13 07:40:55 +02:00
'oauth_user_id' => $google->harvestSubField($user),
'oauth_provider_id'=> 'google',
];
if ($existing_user = MultiDB::hasUser($query)) {
2021-03-16 12:29:16 +01:00
2020-05-13 08:20:05 +02:00
Auth::login($existing_user, true);
2020-05-13 11:02:38 +02:00
$existing_user->setCompany($existing_user->account->default_company);
2021-05-05 08:44:31 +02:00
2021-05-23 10:43:50 +02:00
$this->setLoginCache($existing_user);
2020-11-13 10:09:20 +01:00
$cu = CompanyUser::query()
->where('user_id', auth()->user()->id);
$cu->first()->account->companies->each(function ($company) use($cu){
if($company->tokens()->where('is_system', true)->count() == 0)
{
CreateCompanyToken::dispatchNow($company, $cu->first()->user, request()->server('HTTP_USER_AGENT'));
}
});
2021-04-29 03:31:04 +02:00
return $this->timeConstrainedResponse($cu);
2021-03-16 12:29:16 +01:00
}
2021-05-22 06:45:09 +02:00
//If this is a result user/email combo - lets add their OAuth details details
if($existing_login_user = MultiDB::hasUser(['email' => $google->harvestEmail($user)]))
{
Auth::login($existing_login_user, true);
$existing_login_user->setCompany($existing_login_user->account->default_company);
2021-05-23 10:43:50 +02:00
$this->setLoginCache($existing_login_user);
2021-05-22 06:45:09 +02:00
auth()->user()->update([
'oauth_user_id' => $google->harvestSubField($user),
'oauth_provider_id'=> 'google',
]);
$cu = CompanyUser::query()
->where('user_id', auth()->user()->id);
$cu->first()->account->companies->each(function ($company) use($cu){
if($company->tokens()->where('is_system', true)->count() == 0)
{
CreateCompanyToken::dispatchNow($company, $cu->first()->user, request()->server('HTTP_USER_AGENT'));
}
});
return $this->timeConstrainedResponse($cu);
2021-05-22 06:45:09 +02:00
}
}
2020-05-13 08:20:05 +02:00
if ($user) {
2021-03-20 01:41:41 +01:00
2021-05-23 23:23:30 +02:00
//check the user doesn't already exist in some form
if($existing_login_user = MultiDB::hasUser(['email' => $google->harvestEmail($user)]))
{
Auth::login($existing_login_user, true);
$existing_login_user->setCompany($existing_login_user->account->default_company);
$this->setLoginCache($existing_login_user);
auth()->user()->update([
'oauth_user_id' => $google->harvestSubField($user),
'oauth_provider_id'=> 'google',
]);
$cu = CompanyUser::query()
->where('user_id', auth()->user()->id);
$cu->first()->account->companies->each(function ($company) use($cu){
if($company->tokens()->where('is_system', true)->count() == 0)
{
CreateCompanyToken::dispatchNow($company, $cu->first()->user, request()->server('HTTP_USER_AGENT'));
}
});
return $this->timeConstrainedResponse($cu);
}
//user not found anywhere - lets sign them up.
2020-05-13 07:40:55 +02:00
$name = OAuth::splitName($google->harvestName($user));
$new_account = [
'first_name' => $name[0],
'last_name' => $name[1],
'password' => '',
2020-05-13 07:40:55 +02:00
'email' => $google->harvestEmail($user),
'oauth_user_id' => $google->harvestSubField($user),
2021-03-21 23:52:39 +01:00
// 'oauth_user_token' => $token,
// 'oauth_user_refresh_token' => $refresh_token,
'oauth_provider_id' => 'google',
];
MultiDB::setDefaultDatabase();
$account = CreateAccount::dispatchNow($new_account, request()->getClientIp());
Auth::login($account->default_company->owner(), true);
2020-05-13 11:02:38 +02:00
auth()->user()->email_verified_at = now();
auth()->user()->save();
2021-05-05 08:44:31 +02:00
2021-05-23 10:43:50 +02:00
$this->setLoginCache(auth()->user());
2021-03-22 12:18:57 +01:00
$cu = CompanyUser::whereUserId(auth()->user()->id);
$cu->first()->account->companies->each(function ($company) use($cu){
if($company->tokens()->where('is_system', true)->count() == 0)
{
CreateCompanyToken::dispatchNow($company, $cu->first()->user, request()->server('HTTP_USER_AGENT'));
}
});
2021-04-29 03:31:04 +02:00
return $this->timeConstrainedResponse($cu);
}
2020-05-13 07:30:17 +02:00
return response()
->json(['message' => ctrans('texts.invalid_credentials')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
}
2021-05-24 11:39:21 +02:00
public function redirectToProvider(string $provider)
{
//'https://www.googleapis.com/auth/gmail.send','email','profile','openid'
$scopes = [];
if($provider == 'google'){
$scopes = ['https://www.googleapis.com/auth/gmail.send','email','profile','openid'];
}
if (request()->has('code')) {
return $this->handleProviderCallback($provider);
} else {
2021-06-01 09:24:51 +02:00
return Socialite::driver($provider)->with(['redirect_uri' => config('ninja.app_url')."/auth/google"])->scopes($scopes)->redirect();
2021-05-24 11:39:21 +02:00
}
}
public function handleProviderCallback(string $provider)
{
$socialite_user = Socialite::driver($provider)
2021-06-10 06:05:49 +02:00
->with(['redirect_uri' => config('ninja.app_url')."/auth/google"])
2021-05-24 11:39:21 +02:00
->user();
2021-06-01 07:24:47 +02:00
if($user = OAuth::handleAuth($socialite_user, $provider))
{
2021-05-24 11:39:21 +02:00
2021-06-01 09:24:51 +02:00
nlog('found user and updating their user record');
2021-05-24 11:39:21 +02:00
2021-06-01 07:24:47 +02:00
$update_user = [
'first_name' => $name[0],
'last_name' => $name[1],
'password' => '',
'email' => $socialite_user->getEmail(),
'oauth_user_id' => $socialite_user->getId(),
2021-06-01 08:06:00 +02:00
'oauth_provider_id' => $provider,
2021-06-01 07:24:47 +02:00
'oauth_user_token' => $socialite_user->refreshToken,
];
2021-05-24 11:39:21 +02:00
2021-06-01 09:24:51 +02:00
$user->update($update_user);
2021-05-24 11:39:21 +02:00
2021-06-01 09:24:51 +02:00
}
else {
nlog("user not found for oauth");
2021-06-01 07:24:47 +02:00
}
2021-05-24 11:39:21 +02:00
2021-06-01 09:24:51 +02:00
return redirect('/#/');
2021-05-24 11:39:21 +02:00
}
2018-10-04 19:10:43 +02:00
}