public function createOauthUser(OauthUser $oauthUser, string $oauthIdName, string $oauthId) { /** @var User $user */ $user = $this->createModel(['name' => $oauthUser->getName(), 'email' => $oauthUser->getEmail(), $oauthIdName => $oauthId]); list($saved, $user) = $this->save($user->verify()); if ($saved) { // fire registered via oauth event event(new RegisteredViaOauth($user)); // put avatar upload in queue if ($avatar = $oauthUser->getAvatar()) { dispatch(new UploadOauthAvatar($user, $this->getLargeAvatar($avatar))); } } return $saved ? $user : null; }
/** * @param \Laravel\Socialite\Contracts\User $userData * @return User */ public function findByUsernameOrCreate($userData) { $user = User::firstOrCreate(['username' => $userData->getNickname(), 'email' => $userData->getEmail()]); $user->full_name = $userData->getName(); $user->save(); return $user; }
/** * Logs in or creates a user. * * @param SocialiteUser $userData * @param $provider */ public function loginOrCreateUser(SocialiteUser $userData, $provider) { $user = $this->findUser($provider, $userData->getId()); if (is_null($user)) { $user = $this->createUser($provider, $userData->getId()); } $this->auth->login($user, true); }
public function login(User $socialAcount, $provider) { $userClass = config('auth.model'); $user = $userClass::whereEmail($socialAcount->getEmail())->first(); if (!$user) { $user = $userClass::create(['name' => $socialAcount->getName(), 'email' => $socialAcount->getEmail(), 'password' => Hash::make(Str::random(16)), 'status' => config('laravolt-auth.default.status')]); } $account = SocialAccount::firstOrCreate(['provider' => $provider, 'provider_id' => $socialAcount->getId()]); $user->socialAccounts()->save($account); $account->touch(); $this->auth->login($user, true); }
public static function confirmFacebook(User $localUser, SocialiteUser $facebookUser) { $nickname = $facebookUser->getNickname(); if ($nickname == '') { $nickname = $facebookUser->getId(); } $profile = $localUser->profile; $profile->facebook = 'http://facebook.com/' . $nickname; $profile->confirmed_facebook = true; $profile->save(); return $profile; }
/** * Create new user if it does not exists. * * @param Provider * @param \Laravel\Socialite\Contracts\User * @return User */ public static function findOrCreate(Provider $provider, SocialUser $socialUser) { // If user already exists reuse it $user = self::where(['uuid' => $socialUser->getId(), 'provider_id' => $provider->id])->withTrashed()->first(); if ($user) { return $user; } // Create a new user $user = new static(); $user->uuid = $socialUser->getId(); $user->name = $socialUser->getName(); $user->nickname = $socialUser->getNickname(); $user->email = $socialUser->getEmail(); $user->avatar = $socialUser->getAvatar(); $user->provider_id = $provider->id; $user->language_id = app('language')->id; $user->role_id = Role::whereIsDefault(true)->firstOrFail()->id; $user->save(); return $user; }
/** * Checks the API data returned with what we have in the db. Then logs them in * There's an option to create an account for them * * @param User $api_user * @param bool $createNew * * @return \Illuminate\Http\RedirectResponse */ public function checkUsersAccount(User $api_user, $createNew = false) { // grab the user's email $email = $api_user->getEmail(); // check if the account exists on our server $user = $this->userRepository->getFirstBy('email', '=', $email); if (is_null($user)) { if ($createNew) { // store the user api data in the session, then allow them to fill other fields prior to their account creation $this->session->put('api_user_data', $api_user); return redirect()->route('auth.fill'); } flash()->error('We could not find a matching user account on our server. Try creating an account first'); return redirect()->to(session('url.intended', '/')); } else { // login the user $this->auth->login($user, true); return redirect()->intended(session('url.intended', '/')); } }
public function createOrGetUser(ProviderUser $providerUser) { $account = SocialAccount::whereProvider('facebook')->whereProviderUserId($providerUser->getId())->first(); if ($account) { return $account->user; } else { $account = new SocialAccount(['provider_user_id' => $providerUser->getId(), 'provider' => 'facebook']); $user = User::whereEmail($providerUser->getEmail())->first(); $email = ""; if ($providerUser->getEmail() == "") { $email = $providerUser->getName(); } else { $email = $providerUser->getEmail(); } if (!$user) { $user = User::create(['email' => $email, 'name' => $providerUser->getName()]); } $account->user()->associate($user); $account->save(); return $user; } }
public function createOrGetUser(SocialUser $providerUser, $providerName) { $account = SocialAccount::whereProvider($providerName)->whereProviderUserId($providerUser->getId())->first(); if ($account) { return $account->user; } $account = new SocialAccount(['provider_user_id' => $providerUser->getId(), 'provider' => $providerName]); $user = User::whereEmail($providerUser->getEmail())->first(); if (!$user) { $user = User::create(['email' => $providerUser->getEmail(), 'name' => $providerUser->getName()]); } $account->user()->associate($user); $account->save(); return $user; }
public function createOrGetUser(ProviderUser $providerUser) { // Cari akun di db $account = SocialAccount::whereProvider('facebook')->whereProviderUserId($providerUser->getId())->first(); if ($account) { // Kalo ada > return user return $account->user; } else { // Kalo gaada > register $account = new SocialAccount(['provider_user_id' => $providerUser->getId(), 'provider' => 'facebook']); $user = User::whereEmail($providerUser->getEmail())->first(); if (!$user) { $user = User::create(['email' => $providerUser->getEmail(), 'name' => $providerUser->getName()]); } $account->user()->associate($user); $account->save(); return $user; } }
/** * Validate data from a social provider. * * @param \Laravel\Socialite\Contracts\User * @return \Illuminate\Contracts\Support\MessageProvider */ public function validate(SocialUser $socialUser) { $input = ['uuid' => $socialUser->getId(), 'name' => $socialUser->getName(), 'nickname' => $socialUser->getNickname(), 'email' => $socialUser->getEmail(), 'avatar' => $socialUser->getAvatar()]; $customMessages = ['same' => _('Your account is not verified')]; return Validator::make($input, $this->rules, $customMessages)->setAttributeNames($this->labels)->errors(); }
/** * @param string $socialDriver * @param \Laravel\Socialite\Contracts\User $socialUser * @return SocialAccount */ public function fillSocialAccount($socialDriver, $socialUser) { $this->socialAccount->fill(['driver' => $socialDriver, 'driver_id' => $socialUser->getId(), 'avatar' => $socialUser->getAvatar()]); return $this->socialAccount; }
protected function fillUser(User $user, array $user_data, UserContract $data, string $provider) { $mappings = ['name' => 'name', 'email' => 'email', 'avatar' => ['avatar', 'id'], 'picture' => 'avatar_original', 'bio' => ['bio', 'description'], 'birthday' => ['birthday', 'birth_year'], 'gender' => 'gender', 'rel:location' => 'location.name', 'rel:timezone' => 'timezone', 'rel:locale' => 'locale', 'rel:website' => 'website', "rel:{$provider}" => 'link', 'tagline' => ['work', 'company', 'headline', 'occupation']]; $relations_data = ['links' => []]; $getValue = function ($key) use($user_data, $data) { if (strpos($key, '.') === false) { return $user_data[$key] ?? $data->{$key} ?? null; } else { $value = $user_data; $sub_key = strtok($key, '.'); do { $value = $value[$sub_key]; } while ($sub_key = strtok('.')); return $value; } }; foreach ($mappings as $field => $key) { if (strpos($field, 'rel:') === false && !$user->{$field}) { //not a relation and is still unset if (is_array($key)) { foreach ($key as $key_option) { if ($value = $getValue($key_option)) { break; } } } else { $value = $getValue($key); } if (!isset($value)) { continue; //no data, so we can skip this field } switch ($field) { case 'name': if ($provider == 'google') { $value = trim($value['givenName'] . ' ' . $value['familyName']); if (!$value) { //yeah, hosted accounts may not even have a NAME (!!!) $email = $data->getEmail(); $value = substr($email, 0, strpos($email, '@')); //takes the email username... $value = strtr($value, ['.' => ' ', '_' => ' ', '-' => ' ']); //..replaces common placeholders.. $value = ucwords($value); //...and call it a "name" } } break; case 'birthday': switch ($provider) { case 'live': //TODO: user might have month + day without year. We should split the birthday field to accomodate this if ($user_data['birth_month'] && $user_data['birth_day'] && $user_data['birth_year']) { $value = date('Y-m-d', mktime(0, 0, 0, $user_data['birth_month'], $user_data['birth_day'], $user_data['birth_year'])); } break; default: $value = \DateTime::createFromFormat('m/d/Y', $value)->format('Y-m-d'); } break; case 'tagline': switch ($provider) { case 'github': $value = 'Developer' . ($value ? ' @ ' . $value : ''); break; case 'facebook': $last_job = current($value); $value = $last_job['position']['name'] . ' @ ' . $last_job['employer']['name']; break; case 'live': $value = isset($value[0]['employer']['name']) ? ($value[0]['position']['name'] ?? 'works') . ' @ ' . $value[0]['employer']['name'] : ''; break; } break; case 'avatar': switch ($provider) { case 'live': $value = "https://apis.live.net/v5.0/{$data->getId()}/picture"; break; } break; case 'gender': $value = strtoupper($value[0]); break; } $user->{$field} = $value; } else { $relation = substr($field, 4); switch ($relation) { case 'website': switch ($provider) { case 'twitter': $url = static::unshortenUrl($user_data['url']); break; case 'github': $url = $user_data['blog']; break; //seriously github? blog? hahah //seriously github? blog? hahah default: $url = $user_data['website'] ?? ''; break; } if ($url) { if (!preg_match('|^https?://|', $url)) { $url = 'http://' . $url; } $url = substr($url, 4); //personal website prefix length $relations_data['links']['personal website'] = $url; } break; case $provider: //provider's profile switch ($provider) { case 'twitter': case 'github': case 'bitbucket': $username = $data->getNickname(); break; case 'linkedin': $profile = $user_data['publicProfileUrl']; $username = substr($profile, strpos($profile, '/in/') + 4); break; case 'google': $username = $data->getId(); if ($user_data['isPlusUser']) { $relations_data['links']['google+'] = $data->getId(); } if (isset($user_data['urls']) && is_array($user_data['urls'])) { //TODO: should we use our entries from SocialNetwork instead? how? maybe spliting the URL field into verification_url (regex) and profile_url? $valid_networks = ['facebook', 'linkedin', 'twitter', 'youtube']; foreach ($user_data['urls'] as $entry) { $label = strtolower($entry['label']); $handle = substr($entry['value'], (strrpos($entry['value'], '/') ?: -1) + 1); if (in_array($label, $valid_networks)) { $relations_data['links'][$label] = $handle; } else { foreach ($valid_networks as $network) { if (strpos($entry['value'], $network . '.com')) { $relations_data['links'][$network] = $handle; } } } } } break; default: $username = $data->getId(); } session()->set('signup.main_provider_link', compact('provider', 'username')); break; case 'location': //facebook: location.name //twitter, github, bitbucket (empty?): location //linkedin: location.name (Rio de Janeiro Area, Brazil) + location.country.code (br) //google: placesLived[].primary=true ~ value //live: requires complete address permission :/ //TODO: add a location relationship here; don't forget to test with a testuser with no location! break; case 'locale': //facebook, live: locale //twitter: lang (en) //google: language //github, bitbucket: none? //TODO: add a language relationship here; don't forget to test with a testuser with no locale! break; case 'timezone': //facebook: timezone //TODO DAFUK timezone comes as -2 USELESS HALP //twitter: utc_offset (-10800) / timezone (Brasilia) //github, bitbucket, google, live: none? //TODO: add a timezone relationship here; don't forget to test with a testuser with no timezone! break; } } } // !ddd($user->getAttributes(), $username, $data, $relations_data); session()->set('signup.relations', $relations_data); }
/** * Gets the user model according to the user contract given. * * @param UserContract $user The user object from the oauth event. * * @return \App\User The user model from the database. */ private function getUserModel(UserContract $user) { $faker = Factory::create(); $model = User::whereEmail($user->getEmail())->first(); if (!$model) { $model = new User(); $model->name = $user->getName(); $model->email = $user->getEmail(); $model->password = bcrypt($faker->words(5, true)); $model->admin = false; $model->save(); } return $model; }
private function populateSession(YoutubeUser $youtubeUser) { $session = $this->request->session(); $userSessionValues = ['youtube_id' => $youtubeUser->getId(), 'name' => $youtubeUser->getNickname(), 'avatar' => $youtubeUser->getAvatar(), 'token' => $youtubeUser->token]; $session->put('user', $userSessionValues); }
/** * @param JWTAuth $jwt * @param \Laravel\Socialite\Contracts\User $login * @param string $provider * @return \Illuminate\Http\Response */ private function handleSocialLogin(JWTAuth $jwt, $login, $provider) { $token = UserSocialLogin::firstOrNew(['token' => $login->getId(), 'provider' => $provider]); if (!$token->exists) { $user = $this->createOrFindUser($login); $token->user_id = $user->id; $token->data = json_encode($login); } else { $user = $token->user; } $token->save(); try { if ($token = $jwt->fromUser($user)) { return redirect("/login/handle/{$token}"); } } catch (JWTException $e) { // return error on exception or empty token } return new JsonResponse(['Error creating JWT token'], 401); }
/** * @param SocialiteUser $user * @param $params * @return array */ protected function getUserData(SocialiteUser $user, $params) { $user_data = $user->map($user->user); return ['first_name' => array_get($user_data->name, 'familyName'), 'last_name' => array_get($user_data->name, 'givenName'), 'avatar' => $user_data->avatar, 'email' => $user->getEmail(), 'gender' => $user_data->gender, 'password' => app('hash')->make($params['password'])]; }
/** * @param \Laravel\Socialite\Contracts\User $user * @return array */ private function githubUserToArray(GithubUser $user) { return ['id' => $user->getId(), 'name' => $user->getNickname(), 'email' => $user->getEmail(), 'github_id' => $user->getId(), 'github_url' => 'https://github.com/' . $user->getNickname(), 'image_url' => $user->getAvatar()]; }
/** * If does not exists, creates a shadow OAuth user using user info provided * by the OAuth service provider and assigns default role to this user * for all apps in the system. If user already exists then updates user's * role for all apps and returns it. * * @param OAuthUserContract $OAuthUser * * @return User * @throws \Exception */ public function createShadowOAuthUser(OAuthUserContract $OAuthUser) { $fullName = $OAuthUser->getName(); @(list($firstName, $lastName) = explode(' ', $fullName)); $email = $OAuthUser->getEmail(); $serviceName = $this->getName(); $providerName = $this->getProviderName(); $accessToken = $OAuthUser->token; if (empty($email)) { $email = $OAuthUser->getId() . '+' . $serviceName . '@' . $serviceName . '.com'; } else { list($emailId, $domain) = explode('@', $email); $email = $emailId . '+' . $serviceName . '@' . $domain; } $user = User::whereEmail($email)->first(); if (empty($user)) { $data = ['name' => $fullName, 'first_name' => $firstName, 'last_name' => $lastName, 'email' => $email, 'is_active' => true, 'oauth_provider' => $providerName, 'password' => $accessToken]; $user = User::create($data); } $defaultRole = $this->getDefaultRole(); User::applyDefaultUserAppRole($user, $defaultRole); return $user; }