Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

php - yii2-usuario custom fields in social connect page

Im using the Yii-usuario plugin for my registration and social registration

After a user registers with their social account. they are redirected to user/registration/connect

i've removed username from the form and added firstname and lastname. when i click "continue" the user is logged in but firstname and lastname is not saved in the users table.

i extended the actionConnect() in the registration controller (below)

 public function actionConnect($code)
    {
        /** @var SocialNetworkAccount $account */
        $account = $this->socialNetworkAccountQuery->whereCode($code)->one();

        $this->on(
            SecurityController::class, SocialNetworkAuthEvent::EVENT_BEFORE_AUTHENTICATE, function (SocialNetworkAuthEvent $event) {
                $client = $event->getClient();
                $account = $event->getAccount();

                if ($account->user === null || !$account->user instanceof User) {
                    
                    /** @var User $user */
                    $user = $event->sender->make(
                        User::class,
                        [],
                        [
                            'scenario' => 'connect',
                            'username' => null,
                            //'username' => $account->username,
                           // 'firstname' => $account,
                            'email' => $account->email,
                        ]
                    );
        
                    if (!$user->validate(['email'])) {
                        $user->email = null;
                    }
        
                    $mailService = MailFactory::makeWelcomeMailerService($user);
        
                    if ($event->sender->make(UserCreateService::class, [$user, $mailService])->run()) {
                        $account->user_id = $user->id;
                        $account->save(false);
                    }
                }
        });


        //added 
        $user = Json::decode($account->data);
        $firstname = $user['given_name'];
        $lastname = $user['family_name'];
        $picture = $user['picture'];


        /** @var User $user */
        $user = $this->make(
            User::class,
            [],
            ['scenario' => 'connect', 'email' => $account->email, 'firstname' => $firstname, 'lastname' => $lastname]
        );
        
        $event = $this->make(SocialNetworkConnectEvent::class, [$user, $account]);

        $this->make(AjaxRequestModelValidator::class, [$user])->validate();

        if ($user->load(Yii::$app->request->post()) && $user->validate()) {
       
            $this->trigger(SocialNetworkConnectEvent::EVENT_BEFORE_CONNECT, $event);
            
            $mailService = MailFactory::makeWelcomeMailerService($user);

       
            if ($this->make(UserCreateService::class, [$user, $mailService])->run()) {

                /*
                * added
                */

                $firstname =$_POST['User']['firstname'];
                $lastname = $_POST['User']['lastname'];

                $_user = User::find()->where('email=:email', [':email' => $account->email])->one();
                $_user->firstname = $firstname;
                $_user->lastname = $lastname;
                $_user->save(false);


                $account->connect($user);
     
                Yii::$app->user->login($user, $this->module->rememberLoginLifespan);

                return $this->goBack();
            }
        }
    
        return $this->render(
            'connect',
            [
                'model' => $user,
                'account' => $account,
                'firstname' => $firstname,
                'lastname' => $lastname,
                'picture' => $picture
            ]
        );
    }

the user is logged in, information is stored. except for the firstname and lastname

how do i get this to work? Thanks

the form in the connect.php view looks like this

 <?php $form = ActiveForm::begin(
                            [
                                'id' => $model->formName(),
                            ]
                            ); ?>

                            <?= $form->field($model, 'email')->textInput(['class' => 'form-control form-control-lg', 'disabled' => true]) ?>

                            <?= $form->field($model, 'firstname')->textInput(['class' => 'form-control form-control-lg', 'value' => $firstname]) ?>

                            <?= $form->field($model, 'lastname')->textInput(['class' => 'form-control form-control-lg', 'value' => $lastname]) ?>

                            <?php //echo $form->field($model, 'username') ?>

                            <?= Html::submitButton(Yii::t('usuario', 'Continue'), ['class' => 'btn btn-success btn-lg btn-block shadow-sm']) ?>

                            <?php ActiveForm::end(); ?>

UPDATE:

Here are my rules and scenarios in my extended user.php file

  /**
     * {@inheritdoc}
     */
    public function scenarios()
    {
        return ArrayHelper::merge(
            parent::scenarios(),
            [
                'register' => ['email', 'password', 'firstname', 'lastname'],
                'connect' => ['email', 'firstname', 'lastname'], //social connect
                'create' => ['email', 'password', 'firstname', 'lastname'],
                'update' => ['email', 'password', 'firstname', 'lastname'],
                'settings' => ['email', 'password', 'firstname', 'lastname'],
            ]
        );
    }

        /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            // email rules
            'emailRequired' => ['email', 'required', 'on' => ['register', 'connect', 'create', 'update']],
            'emailPattern' => ['email', 'email'],
            'emailLength' => ['email', 'string', 'max' => 255],
            'emailUnique' => [
                'email',
                'unique',
                'message' => Yii::t('usuario', 'This email address has already been taken'),
            ],
            'emailTrim' => ['email', 'trim'],

            // password rules
            'passwordTrim' => ['password', 'trim'],
            'passwordRequired' => ['password', 'required', 'on' => ['register']],
            'passwordLength' => ['password', 'string', 'min' => 6, 'max' => 72, 'on' => ['register', 'create']],

            //firstname
            'firstnameLength' => ['firstname', 'string', 'min' => 3, 'max' => 255],
            'firstnameTrim' => ['firstname', 'filter', 'filter' => 'trim'],
            'firstnamePattern' => ['firstname', 'match', 'pattern' => '/^p{L}+$/u'],
            'firstnameRequired' => ['firstname', 'required', 'on' => ['register', 'connect', 'create', 'update']],

            //lastname
            'lastnameLength' => ['lastname', 'string', 'min' => 3, 'max' => 255],
            'lastnameTrim' => ['lastname', 'filter', 'filter' => 'trim'],
            'lastnamePattern' => ['lastname', 'match', 'pattern' => '/^p{L}+$/u'],
            'lastnameRequired' => ['lastname', 'required', 'on' => ['register', 'connect', 'create', 'update']],

            'safeRules'  => [['email', 'firstname', 'lastname'], 'safe'],

            // two factor auth rules
            'twoFactorSecretTrim' => ['auth_tf_key', 'trim'],
            'twoFactorSecretLength' => ['auth_tf_key', 'string', 'max' => 16],
            'twoFactorEnabledNumber' => ['auth_tf_enabled', 'boolean']
        ];
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...