Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public function successOAuthCallback($client)
- {
- // use BaseClient::normalizeUserAttributeMap to provide consistency for user attribute`s names
- $attributes = $client->getUserAttributes();
- $user = User::find()->where([
- 'oauth_client'=>$client->getName(),
- 'oauth_client_user_id'=>ArrayHelper::getValue($attributes, 'id')
- ])
- ->one();
- if (!$user) {
- $user = new User();
- $user->scenario = 'oauth_create';
- $user->username = ArrayHelper::getValue($attributes, 'first_name');
- $user->email = ArrayHelper::getValue($attributes, 'email');
- $user->oauth_client = $client->getName();
- $user->oauth_client_user_id = ArrayHelper::getValue($attributes, 'id');
- $password = Yii::$app->security->generateRandomString(8);
- $user->setPassword($password);
- if ($user->save()) {
- $profileData = [];
- if ($client->getName() === 'facebook') {
- $profileData['firstname'] = ArrayHelper::getValue($attributes, 'first_name');
- $profileData['lastname'] = ArrayHelper::getValue($attributes, 'last_name');
- }
- $user->afterSignup($profileData);
- $token = UserToken::create(
- $user->id,
- UserToken::TYPE_ACTIVATION,
- Time::SECONDS_IN_A_DAY
- );
- $sentSuccess = Yii::$app->commandBus->handle(new SendEmailCommand([
- 'view' => 'activation',
- 'params' => [
- 'user'=>$user,
- 'password'=>$password,
- 'url' => Url::to(['/user/sign-in/activation', 'token' => $token->token], true)
- ],
- 'subject' => Yii::t('frontend', '{app-name} | Activation link', ['app-name'=>Yii::$app->name]),
- 'to' => $user->email
- ]));
- $sentSuccess1 = Yii::$app->commandBus->handle(new SendEmailCommand([
- 'view' => 'oauth_welcome',
- 'params' => [
- 'user'=>$user,
- 'password'=>$password,
- ],
- 'subject' => Yii::t('frontend', '{app-name} | Login information', ['app-name'=>Yii::$app->name]),
- 'to' => $user->email
- ]));
- if ($sentSuccess && $sentSuccess1) {
- Yii::$app->session->setFlash(
- 'alert',
- [
- 'options'=>['class'=>'alert-success'],
- 'body'=>Yii::t('frontend', 'Welcome to {app-name}. Email with activation link and login information was sent to your email.', [
- 'app-name'=>Yii::$app->name
- ])
- ]
- );
- }
- } else {
- // We already have a user with this email. Do what you want in such case
- if ($user->email && User::find()->where(['email'=>$user->email])->count()) {
- Yii::$app->session->setFlash(
- 'alert',
- [
- 'options'=>['class'=>'alert-danger'],
- 'body'=>Yii::t('frontend', 'We already have a user with email {email}', [
- 'email'=>$user->email
- ])
- ]
- );
- } else {
- Yii::$app->session->setFlash(
- 'alert',
- [
- 'options'=>['class'=>'alert-danger'],
- 'body'=>Yii::t('frontend', 'Error while oauth process.')
- ]
- );
- }
- };
- }
- if (Yii::$app->user->login($user, 3600 * 24 * 30)) {
- return true;
- } else {
- throw new Exception('OAuth error');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement