示例#1
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->last_name = $this->last_name;
         $user->first_name = $this->first_name;
         $user->patronymic = $this->patronymic;
         $user->email_work = $this->email_work;
         $user->post_id = $this->post_id;
         $user->department_id = $this->department_id;
         $user->status_id = User::STATUS_WAIT;
         $user->setPassword($this->password);
         $user->generateAuthKey();
         $user->generateEmailConfirmToken();
         if ($user->save()) {
             // Присваиваем роль по умолчанию
             //$auth = Yii::$app->authManager;
             //$authorRole = $auth->getRole('user');
             //$auth->assign($authorRole, $user->getId());
             //Отправляем письмо с подтверждением
             /*Yii::$app->mailer->compose('confirmEmail', ['user' => $user])
                               ->setFrom([Yii::$app->params['app']['supportEmail'] => Yii::$app->params['app']['title']])
                               ->setTo($this->email_work)
                               ->setSubject('Email confirmation for ' . Yii::$app->name)
                               ->send();
             */
             Yii::$app->mailer->compose('confirmEmail', ['user' => $user])->setFrom([Yii::$app->params['app']['email'] => Yii::$app->params['app']['title']])->setTo($this->email_work)->setSubject('Email confirmation for ')->send();
         }
         return $user;
     }
     return null;
 }
示例#2
0
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->status = User::STATUS_WAIT;
         $user->generateAuthKey();
         $user->generateEmailConfirmToken();
         if ($user->save()) {
             $auth = Yii::$app->authManager;
             $userRoleDefault = $auth->getRole('user');
             $auth->assign($userRoleDefault, $user->getId());
             $userProfile = new Profile();
             $userProfile->user_id = $user->getId();
             $userProfile->user_agent = Yii::$app->request->getUserAgent();
             $userProfile->user_ip = Yii::$app->request->getUserIP();
             $userProfile->name = $user->username;
             $userProfile->avatar_id = 1;
             //default.png (id = 1)
             $userProfile->save(false);
             Yii::$app->mailer->compose(['text' => '@app/modules/user/mails/emailConfirm'], ['user' => $user])->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])->setTo($this->email)->setSubject(Module::t('app', 'EMAIL_SIGNUP_SUBJECT') . Yii::$app->name)->send();
         }
         return $user;
     }
     return null;
 }
示例#3
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     $auth = Yii::$app->authManager;
     $role = $auth->getRole($this->jabatan);
     if ($this->validate() && !empty($role)) {
         $user = new User();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->generateAuthKey();
         if ($user->validate() && $user->save()) {
             $person = new Person();
             $person->first_name = $this->first_name;
             $person->last_name = $this->last_name;
             $person->gender = $this->gender;
             $person->birth_date = $this->birth_date;
             $person->user_id = $user->id;
             if ($person->validate() && $person->save()) {
                 $auth->assign($role, $user->id);
                 return true;
             }
         }
     }
     return false;
 }
示例#4
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $profile = new Profile();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->generateAuthKey();
         $user->role = 'user';
         $user->status = 1;
         $profile->firstname = $this->firstname;
         $profile->lastname = $this->lastname;
         $profile->avatar = $this->avatar;
         // $profile->gender = 0;
         $transaction = Yii::$app->db->beginTransaction();
         if ($user->save()) {
             $profile->user_id = $user->getId();
             if ($profile->save()) {
                 $transaction->commit();
                 return $user;
             }
         } else {
             $transaction->rollback();
             print_r($user->getErrors());
             return false;
         }
     }
     return null;
 }
示例#5
0
 /**
  * Creates a new Person model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Person();
     $modelUser = new User();
     $modelAuthRule = new AuthRule();
     $modelAuthItem = new AuthItem();
     $authRule = AuthRule::find()->all();
     $authItem = AuthItem::find()->all();
     if (Yii::$app->request->isPost) {
         // do transaction if fails it will not saved
         $transaction = Yii::$app->db->beginTransaction();
         try {
             if ($modelUser->load(Yii::$app->request->post()) && $modelUser->validate()) {
                 $modelUser->generateAuthKey();
                 // first attempt save user record
                 if ($modelUser->save()) {
                     if ($model->load(Yii::$app->request->post())) {
                         $model->user_id = $modelUser->id;
                         // second attemp save person record
                         if ($model->validate() && $model->save()) {
                             if ($modelAuthItem->load(Yii::$app->request->post()) && $modelAuthItem->validate()) {
                                 $auth = Yii::$app->authManager;
                                 $role = $auth->getRole($modelAuthItem->name);
                                 if (!empty($role)) {
                                     // thrid attemp assign role to user
                                     $auth->assign($role, $modelUser->id);
                                     $transaction->commit();
                                     Yii::$app->getSession()->setFlash('success', Yii::t('app', 'Data Karyawan Berhasil Disimpan'));
                                     return $this->redirect(['index']);
                                 } else {
                                     throw new \Exception("AuthRole search data checkpoint fail to save");
                                 }
                             } else {
                                 throw new \Exception("AuthItem (Role) validation checkpoint fail to save");
                             }
                         } else {
                             throw new \Exception("Person save checkpoint fail to save");
                         }
                     } else {
                         throw new \Exception("Person loaded checkpoint fail to save");
                     }
                 } else {
                     throw new \Exception("User save checkpoint fail to save");
                 }
             } else {
                 throw new \Exception("User validation checkpoint fail to save");
             }
         } catch (\Exception $e) {
             $transaction->rollback();
             Yii::$app->getSession()->setFlash('error', Yii::t('app', 'Data Karyawan Gagal Disimpan'));
         }
     }
     return $this->render('create', ['model' => $model, 'modelUser' => $modelUser, 'modelAuthRule' => $modelAuthRule, 'authRule' => $authRule, 'modelAuthItem' => $modelAuthItem, 'authItem' => $authItem]);
 }
 /**
  * Updates or create an User model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id = null)
 {
     /** @var User $model */
     if (is_null($id)) {
         $model = new User(['scenario' => 'adminSignup']);
         $model->generateAuthKey();
     } else {
         $model = $this->findModel($id);
         $model->scenario = 'admin';
         $model->updatePropertyGroupsInformation(true);
     }
     $assignments = Yii::$app->authManager->getAssignments($id);
     if (Yii::$app->request->isPost) {
         $model->load(Yii::$app->request->post());
         $model->auth_key = '';
         if ($model->validate()) {
             if ($id !== null && !empty($model->password)) {
                 $model->setPassword($model->password);
             }
             $model->save();
             $postAssignments = Yii::$app->request->post('AuthAssignment', []);
             $errors = [];
             foreach ($assignments as $assignment) {
                 $key = array_search($assignment->roleName, $postAssignments);
                 if ($key === false) {
                     Yii::$app->authManager->revoke(new Item(['name' => $assignment->roleName]), $model->id);
                 } else {
                     unset($postAssignments[$key]);
                 }
             }
             foreach ($postAssignments as $assignment) {
                 try {
                     Yii::$app->authManager->assign(new Item(['name' => $assignment]), $model->id);
                 } catch (\Exception $e) {
                     $errors[] = 'Cannot assign "' . $assignment . '" to user';
                 }
             }
             if (count($errors) > 0) {
                 Yii::$app->getSession()->setFlash('error', implode('<br />', $errors));
             }
             Yii::$app->session->setFlash('success', Yii::t('app', 'Record has been saved'));
             $returnUrl = Yii::$app->request->get('returnUrl', ['index']);
             switch (Yii::$app->request->post('action', 'save')) {
                 case 'next':
                     return $this->redirect(['update', 'returnUrl' => $returnUrl]);
                 case 'back':
                     return $this->redirect($returnUrl);
                 default:
                     return $this->redirect(Url::toRoute(['update', 'id' => $model->id, 'returnUrl' => $returnUrl]));
             }
         }
     }
     return $this->render('update', ['model' => $model, 'assignments' => ArrayHelper::map($assignments, 'roleName', 'roleName')]);
 }
示例#7
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->status = User::STATUS_WAIT;
         $user->generateAuthKey();
         $user->generateEmailConfirmToken();
         //
         if ($user->save()) {
             $auth = Yii::$app->authManager;
             $role = $auth->getRole('client');
             $auth->assign($role, $user->getId());
             $confirmLink = Yii::$app->urlManager->createAbsoluteUrl(['user/default/confirm-email', 'token' => $user->email_confirm_token]);
             $message = "Здравствуйте, " . Html::encode($user->username) . "!";
             $message .= "Для подтверждения адреса пройдите по ссылке:";
             //$message .= Html::a(Html::encode($confirmLink), $confirmLink) ;
             $message .= $confirmLink;
             $message .= " Если Вы не регистрировались у на нашем сайте, то просто удалите это письмо.";
             // Отправляем
             mail($user->email, 'Регистрация на сайте', $message);
             //                $mailer =Yii::$app->get('mailsmtp');
             //
             //                $message =$mailer->compose('confirmEmail', ['user' => $user])
             //
             //                    ->setTo($this->email)
             //                    ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])
             //                    ->setSubject('Email confirmation for ' . Yii::$app->name);
             //
             //                $message->getSwiftMessage()->getHeaders()->addTextHeader('name', 'value');
             //                $failures =null;
             //                try {
             //
             //                    if(!$mailer->send($message, $failures)) $errorCode=$failures; //отправляем
             //
             //                }catch (\Swift_TransportException $e) { //проверяем на ошибки
             //                    $pattern = '|got code "(.+?)", with|is';
             //                    preg_match($pattern, $e->getMessage(), $out);
             //                    $errorCode=$out[1];
             //                }
             /*Yii::$app->mailer->compose('confirmEmail', ['user' => $user])
               ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])
               ->setTo($this->email)
               ->setSubject('Email confirmation for ' . Yii::$app->name)
               ->send();*/
         }
         return $user;
     }
     return null;
 }
示例#8
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->generateAuthKey();
         if ($user->save()) {
             return $user;
         }
     }
     return null;
 }
示例#9
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate() === true) {
         $user = new User();
         $user->setScenario('signup');
         $user->username = $this->username;
         $user->password = $this->password;
         $user->email = $this->email;
         $user->generateAuthKey();
         if ($user->save() === false) {
             return null;
         }
         return $user;
     }
     return null;
 }
示例#10
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->status = User::STATUS_WAIT;
         $user->generateAuthKey();
         $user->generateEmailConfirmToken();
         if ($user->save()) {
             Yii::$app->mailer->compose('confirmEmail', ['user' => $user])->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])->setTo($this->email)->setSubject('Email confirmation for ' . Yii::$app->name)->send();
         }
         return $user;
     }
     return null;
 }
示例#11
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->status = User::STATUS_WAIT;
         $user->generateAuthKey();
         $user->generateEmailConfirmToken();
         if ($user->save()) {
             Yii::$app->mailer->compose(['text' => '@app/modules/user/mails/emailConfirm'], ['user' => $user])->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])->setTo($this->email)->setSubject(Module::t('module', 'EMAIL_CONFIRMATION_FOR {appName}', ['appName' => Yii::$app->name]))->send();
         }
         return $user;
     }
     return null;
 }
示例#12
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->status = User::STATUS_ACTIVE;
         // заглушка (должно быть STATUS_WAIT): из-за неполадок с отправкой e-mail на сервере
         $user->generateAuthKey();
         $user->generateEmailConfirmToken();
         if ($user->save()) {
             Yii::$app->mailer->compose('confirmEmail', ['user' => $user])->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])->setTo($this->email)->setSubject('Email confirmation for ' . Yii::$app->name)->send();
         }
         return $user;
     }
     return null;
 }
示例#13
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->status = User::STATUS_NOT_CONFIRMED;
         $user->generateAuthKey();
         $user->generateEmailConfirmToken();
         if ($user->save()) {
             $profile = new Profile();
             $profile->link('user', $user);
             Yii::$app->mailer->compose(['text' => '@app/modules/user/mails/emailConfirm'], ['user' => $user])->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])->setTo($this->email)->setSubject('Email confirmation for ' . Yii::$app->name)->send();
         }
         return $user;
     }
     return null;
 }
示例#14
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->status = User::STATUS_WAIT;
         $user->generateAuthKey();
         $user->generateEmailConfirmToken();
         if ($user->save()) {
             $auth = Yii::$app->authManager;
             $authorRole = $auth->getRole('author');
             $auth->assign($authorRole, $user->getId());
             Yii::$app->mailer->compose(['text' => '@app/modules/user/mails/emailConfirm'], ['user' => $user])->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])->setTo($this->email)->setSubject('Email confirmation for ' . Yii::$app->name)->send();
         }
         return $user;
     }
     return null;
 }
示例#15
0
 public function onAuthSuccess($client)
 {
     $attributes = $client->getUserAttributes();
     /* @var $auth Auth */
     $auth = Auth::find()->where(['source' => $client->getId(), 'source_id' => $attributes['id']])->one();
     if (Yii::$app->user->isGuest) {
         if ($auth) {
             // login
             $user = $auth->user;
             Yii::$app->user->login($user);
         } else {
             // signup
             if (isset($attributes['email']) && User::find()->where(['email' => $attributes['email']])->exists()) {
                 Yii::$app->getSession()->setFlash('error', [Yii::t('app', "User with the same email as in {client} account already exists but isn't linked to it. Login using email first to link it.", ['client' => $client->getTitle()])]);
             } else {
                 $password = Yii::$app->security->generateRandomString(6);
                 $user = new User(['username' => $attributes['screen_name'], 'password' => $password, 'role' => 'user', 'email' => $attributes['email']]);
                 if (!empty($attributes['photo'])) {
                     $file = file_get_contents($attributes['photo']);
                     $avatarPath = \app\modules\user\Module::$avatarPath;
                     file_put_contents($avatarPath . '/1.jpg', $file);
                 }
                 $profile = new Profile(['firstname' => $attributes['first_name'], 'lastname' => $attributes['last_name'], 'country' => $attributes['country']]);
                 $user->generateAuthKey();
                 $user->generatePasswordResetToken();
                 $transaction = $user->getDb()->beginTransaction();
                 if ($user->save()) {
                     // Сохраняем профиль
                     $profile->user_id = $user->id;
                     if (!$profile->save()) {
                         print_r($profile->getErrors());
                         die;
                     }
                     $auth = new Auth(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $attributes['id']]);
                     if ($auth->save()) {
                         $transaction->commit();
                         Yii::$app->user->login($user);
                     } else {
                         print_r($auth->getErrors());
                     }
                 } else {
                     print_r($user->getErrors());
                 }
             }
         }
     } else {
         // user already logged in
         if (!$auth) {
             // add auth provider
             $auth = new Auth(['user_id' => Yii::$app->user->id, 'source' => $client->getId(), 'source_id' => $attributes['id']]);
             $auth->save();
         }
     }
 }
示例#16
0
 /**
  * Success callback for social networks authentication
  * @param $client
  * @throws ErrorException
  * @throws \yii\base\ExitException
  */
 public function successCallback($client)
 {
     $model = AuthClientHelper::findUserByService($client);
     if (is_object($model) === false) {
         // user not found, retrieve additional data
         $client = AuthClientHelper::retrieveAdditionalData($client);
         $attributes = AuthClientHelper::mapUserAttributesWithService($client);
         // check if it is anonymous user
         if (Yii::$app->user->isGuest === true) {
             $model = new User(['scenario' => 'registerService']);
             $security = Yii::$app->security;
             $model->setAttributes($attributes['user']);
             $model->status = User::STATUS_ACTIVE;
             if (empty($model->username) === true) {
                 // if we doesn't have username - generate unique random temporary username
                 // it will be needed for saving purposes
                 $model->username = $security->generateRandomString(18);
                 $model->username_is_temporary = 1;
             }
             $model->setPassword($security->generateRandomString(16));
             $model->generateAuthKey();
             if ($model->save() === false) {
                 if (isset($model->errors['username'])) {
                     // regenerate username
                     $model->username = $security->generateRandomString(18);
                     $model->username_is_temporary = 1;
                     $model->save();
                 }
                 if (isset($model->errors['email'])) {
                     // empty email
                     $model->email = null;
                     $model->save();
                 }
                 if (count($model->errors) > 0) {
                     throw new ErrorException(Yii::t('app', "Temporary error signing up user"));
                 }
             }
         } else {
             // non anonymous - link to existing account
             /** @var \app\modules\user\models\User $model */
             $model = Yii::$app->user->identity;
         }
         $service = new UserService();
         $service->service_type = $client->className();
         $service->service_id = '' . $attributes['service']['service_id'];
         $service->user_id = $model->id;
         if ($service->save() === false) {
             throw new ErrorException(Yii::t('app', "Temporary error saving social service"));
         }
     } elseif (Yii::$app->user->isGuest === false) {
         // service exists and user logged in
         // check if this service is binded to current user
         if ($model->id != Yii::$app->user->id) {
             throw new ErrorException(Yii::t('app', "This service is already binded to another user"));
         } else {
             throw new ErrorException(Yii::t('app', 'This service is already binded.'));
         }
     }
     TagDependency::invalidate(Yii::$app->cache, ['Session:' . Yii::$app->session->id]);
     Yii::$app->user->login($model, 86400);
     if ($model->username_is_temporary == 1 || empty($model->email)) {
         // show post-registration form
         $this->layout = $this->module->postRegistrationLayout;
         $model->setScenario('completeRegistration');
         echo $this->render('post-registration', ['model' => $model]);
         Yii::$app->end();
         return;
     }
 }
示例#17
0
 public function beforeSave($insert)
 {
     if ($this->scenario == 'registerUser') {
         $password = Yii::$app->security->generateRandomString(10);
         $user = new User();
         $user->setScenario('signup');
         $user->username = $this->email;
         $user->email = $this->email;
         $user->first_name = $this->first_name;
         $user->last_name = $this->last_name;
         $user->password = $password;
         $user->generateAuthKey();
         if ($user->save()) {
             Yii::$app->mail->compose('new-user-in-order', ['user' => $user, 'password' => $password])->setFrom(Yii::$app->getModule('core')->emailConfig['mailFrom'])->setTo($this->email)->setSubject(Yii::t('app', 'Welcome to {appName}', ['appName' => Yii::$app->getModule('DefaultTheme')->siteName]))->send();
             Yii::$app->user->login($user, 86400);
             $this->user_id = $user->id;
         }
     }
     return parent::beforeSave($insert);
 }
示例#18
0
 /**
  * @throws \yii\base\Exception
  * @throws \yii\base\InvalidConfigException
  */
 public function register()
 {
     if (!$this->validate()) {
         return false;
     }
     $user = new User();
     $user->email = $this->email;
     $user->name = $this->name;
     $user->country_id = $this->country_id;
     $user->phone = $this->phone;
     $user->address = $this->address;
     $user->password_hash = User::hashPassword($this->password);
     $user->generateAuthKey();
     $user->status = User::USER_STATUS_ACTIVE;
     $user->save();
     return User::login($this->email, true);
 }