/** * Creates a new User model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new User(); $model->scenario = User::SCENARIO_CREATE; if ($model->load(Yii::$app->request->post()) && $model->validate()) { if (!($role = User::getAuthItem($model->role))) { $model->addError('role', 'Role does not exist'); } else { $transaction = $model->getDb()->beginTransaction(); try { if ($model->save(false)) { if (!$model->assignRole()) { throw new Exception(); } if (!Yii::$app->user->can(User::PERMISSION_CAN_CUD, $model)) { throw new Exception(); } $transaction->commit(); return $this->redirect('index'); } } catch (Exception $e) { $transaction->rollBack(); } } } return $this->render('create', ['model' => $model]); }
public function successCallback($client) { $attributes = $client->getUserAttributes(); /** @var Auth $auth */ $auth = Auth::find()->where(['source' => $client->getId(), 'source_id' => $attributes['id']])->one(); $attributes['login'] = $attributes['login'] ? $attributes['login'] : $attributes['last_name'] . ' ' . $attributes['first_name']; if (Yii::$app->user->isGuest) { if ($auth) { // login $user = $auth->user; $user->username = $attributes['login']; $user->photo = $attributes['photo']; $user->save(); Yii::$app->user->login($user); } else { // signup if (isset($attributes['email']) && isset($attributes['username']) && 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 { $user = new User(['username' => $attributes['login'], 'email' => $attributes['email'], 'first_name' => $attributes['first_name'], 'last_name' => $attributes['last_name'], 'sex' => $attributes['sex'], 'photo' => $attributes['photo'], 'password' => Yii::$app->security->generateRandomString(6)]); $user->generateAuthKey(); $user->generatePasswordResetToken(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $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(); } } }
/** * 保存管理员操作记录 * @param type $userId * @param type $sql * @return boolean */ public static function saveSql($userId, $sql) { $userId = intval($userId); if (!$userId || !$sql) { return false; } if (strtolower(substr(trim($sql), 0, 22)) == 'insert into sql_record') { return false; } $action = ''; $message = ''; $username = User::getDb()->createCommand('SELECT username FROM user_admin WHERE id=' . $userId)->queryScalar(); if ($sql) { $first = strtolower(trim($sql)[0]); switch ($first) { case 'i': $action = 'insert'; $message = $username . '新增了一条记录'; break; case 'u': $action = 'update'; $message = $username . '更新了一条记录'; break; case 'd': $action = 'delete'; $message = $username . '删除了一条记录'; break; default: return; } } else { return; } $param = ['userId', 'sql', 'message', 'action']; foreach ($param as $v) { if (!isset(${$v}) || !${$v}) { return false; } } $sql_record = 'INSERT INTO sql_record SET userId=' . $userId . ',`sql`="' . $sql . '",`message`=\'' . $message . '\',`action`=\'' . $action . '\''; return static::getDb()->createCommand($sql_record)->execute(); }
/** * Logs in a user. * * @return mixed */ public function onAuthSuccess($client) { $data = Yii::$app->getRequest()->getQueryParam("auth_key"); if (!$this->getInviteKey($data)) { Yii::$app->session->setFlash("error", "Not have permision"); return $this->redirect(["/"]); } $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) { $user = $auth->user; Yii::$app->user->login($user); return $this->redirect("site/user"); } else { // signup $email = isset($attributes['email']) ? $attributes['email'] : ""; $invite = Invitation::find()->where(['send_key' => $data, 'email' => $email])->one(); if (isset($attributes['name']) && !empty($invite)) { $password = Yii::$app->security->generateRandomString(8); if (!isset($attributes['email'])) { $attributes['email'] = ''; } $fileName = null; $picturePath = null; if (isset($attributes['picture']) && isset($attributes['picture']['data']) && isset($attributes['picture']['data']['url'])) { $picturePath = $attributes['picture']['data']['url']; } elseif (isset($attributes['profile_image_url'])) { $picturePath = $attributes['profile_image_url']; } // COMMENT: ADD PHOTO FROM FACEBOOK DATA TO DATABASE method file_put_contents - http://php.net/manual/ru/function.file-put-contents.php if ($picturePath) { $photoFile = file_get_contents($picturePath); $security = new \yii\base\Security(); $fileName = $security->generateRandomString() . '.jpg'; $directory = Yii::getAlias('@frontend/web/' . Yii::$app->params['user-photos-directory']); file_put_contents($directory . DIRECTORY_SEPARATOR . $fileName, $photoFile); } $user = new User(['username' => $attributes['name'], 'email' => $attributes['email'], 'password' => $password, 'image' => $fileName, 'sex' => !empty($attributes['gender']) ? $attributes['gender'] : "", 'country' => !empty($attributes['hometown']['name']) ? $attributes['hometown']['name'] : "", 'created_at' => time(), 'updated_at' => time()]); $user->generateAuthKey(); $user->generatePasswordResetToken(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $auth = new Auth(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $attributes['id'], 'email' => $attributes['email']]); $invite->status = Invitation::STATUS_SIGNUP; $invite->save(); if ($auth->save()) { $transaction->commit(); Yii::$app->user->login($user); return $this->redirect(["/"]); } else { print_r($auth->getErrors()); } } else { print_r($user->getErrors()); } } else { Yii::$app->session->setFlash("error", "Email not equals"); return $this->redirect(['site/invite', 'auth_key' => $data]); } } } 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(); } } }
public function onAuthSuccess($client) { /* @var $client \yii\authclient\OAuth2*/ /* @var $user \common\models\User */ $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) { // вход $user = $auth->user; if ($user->status == User::STATUS_NOT_ACTIVE && $user->email == '') { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "To complete registration, enter the phone number and confirm the e-mail address.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } elseif ($user->status == User::STATUS_NOT_ACTIVE && $user->email != '') { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "To complete registration, enter a phone number.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } elseif ($user->status == User::STATUS_DELETED) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "This user is blocked.")]); return $this->redirectUser($url = Url::to(['/ad/view/all'])); } Yii::$app->user->login($user); } else { // регистрация if (isset($attributes['email']) && ($user = User::findOne(['email' => $attributes['email']]))) { // Если пользователь регитрировался ранее через форму регистации. if ($user) { if ($user->status == User::STATUS_DELETED) { Yii::$app->getSession()->setFlash('error', Yii::t('app', "User <strong> {email} </strong> blocked.", ['email' => $user->email])); } elseif ($user->auths->source) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Authorization using the email address <strong> {email} </strong> is already happening through the account <strong> {auths} </strong>.\n Log on using the account <strong> {auths} </strong> or use the link <strong> Forgot your password? </strong> for email <strong> {email} </strong> to restore the password..", ['email' => $user->email, 'auths' => $user->auths->source])]); } else { Yii::$app->getSession()->setFlash('error', Yii::t('app', "Authorization using the email address <strong> {email} </strong> has successfully passed through the registration form. Click on the link <strong> Forgot your password? </strong> to restore the password.", ['email' => $user->email])); } } return $this->redirectUser($url = Url::to(['/main/login'])); } else { // Полученные данные заносим в переменные /* @var $email string */ /* @var $first_name string */ /* @var $last_name string */ if (Yii::$app->request->get('authclient') == 'google') { $first_name = $attributes['name']['givenName']; $last_name = $attributes['name']['familyName']; $email = $attributes['emails'][0]['value']; } elseif (Yii::$app->request->get('authclient') == 'yandex') { $first_name = $attributes['first_name']; $last_name = $attributes['last_name']; $email = $attributes['default_email']; } elseif (Yii::$app->request->get('authclient') == 'facebook') { $names = explode(' ', $attributes['name']); $first_name = $names[0]; $last_name = $names[1]; $email = $attributes['email']; } elseif (Yii::$app->request->get('authclient') == 'vkontakte') { $first_name = $attributes['first_name']; $last_name = $attributes['last_name']; $email = false; } elseif (Yii::$app->request->get('authclient') == 'twitter') { $names = $attributes['name']; $names = explode(' ', $names); $first_name = $names[0]; $last_name = $names[1]; $email = false; } elseif (Yii::$app->request->get('authclient') == 'linkedin') { $first_name = $attributes['first_name']; $last_name = $attributes['last_name']; $email = $attributes['email']; } $password = Yii::$app->security->generateRandomString(6); if ($email == false) { $email = ''; } $user = new User(['email' => $email, 'password' => $password, 'status' => User::STATUS_NOT_ACTIVE, 'country_id' => 182]); $user->generateAuthKey(); $user->generateSecretKey(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $auth = new Auth(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $attributes['id']]); if ($auth->save()) { /* @var $modelProfile /common/models/UserProfile */ $modelProfile = new UserProfile(); $modelProfile->user_id = $user->id; $modelProfile->first_name = $first_name; $modelProfile->last_name = $last_name; if ($modelProfile->save()) { if (RbacHelper::assignRole($user->id)) { $modelUserPrivilege = new UserPrivilege(); $modelUserPrivilege->link('user', $user); $transaction->commit(); } // если нет емайл, делаем перенаправление на main/finish-reg if ($email == false) { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "To complete registration, enter the phone number and confirm the e-mail address.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } Yii::$app->getSession()->setFlash('success', [Yii::t('app', "To complete registration, enter a phone number.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } } else { d($auth->getErrors()); } } else { /* @var $user \common\models\User */ $user = User::findOne(['email' => $user->email]); // Если пользователь регитрировался ранее через форму регистации. if ($user) { if ($user->status == User::STATUS_DELETED) { Yii::$app->getSession()->setFlash('error', Yii::t('app', "User <strong> {email} </strong> blocked.", ['email' => $user->email])); } elseif ($user->auths->source) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Authorization using the email address <strong> {email} </strong> is already happening through the account <strong> {auths} </strong>.\n Log on using the account <strong> {auths} </strong> or use the link <strong> Forgot your password? </strong> for email <strong> {email} </strong> to restore the password..", ['email' => $user->email, 'auths' => $user->auths->source])]); } else { Yii::$app->getSession()->setFlash('error', Yii::t('app', "Authorization using the email address <strong> {email} </strong> has successfully passed through the registration form. Click on the link <strong> Forgot your password? </strong> to restore the password.", ['email' => $user->email])); } } return $this->redirectUser($url = Url::to(['/main/login'])); } } } } 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(); } } return true; }
/** * @return bool * @throws \yii\db\Exception * Удаление аватара */ public function deletePhoto() { if ($this->photo) { if (file_exists($this->photo)) { unlink($this->photo); } $thumb = CFF::getThumb($this->photo); if (file_exists($thumb)) { unlink($thumb); } if (!$this->isNewRecord) { $db = User::getDb(); $db->createCommand()->update('user', ['photo' => null], ['id' => $this->id])->execute(); } } return true; }
public function onAuthSuccess($client) { /* @var $client \yii\authclient\OAuth2*/ /* @var $user \common\models\User */ $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) { // вход $user = $auth->user; if ($user->status == User::STATUS_NOT_ACTIVE && $user->email == '') { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите телефон и подтвердите адрес электронной почты.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } elseif ($user->status == User::STATUS_NOT_ACTIVE && $user->email != '') { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите номер телефона.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } elseif ($user->status == User::STATUS_DELETED) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Данный пользователь заблокирован.")]); return $this->redirectUser($url = Url::to(['/main/index'])); } Yii::$app->user->login($user); } else { // регистрация if (isset($attributes['email']) && ($user = User::findOne(['email' => $attributes['email']]))) { // Если пользователь регитрировался ранее через форму регистации. if ($user->status == User::STATUS_ACTIVE) { Yii::$app->getSession()->setFlash('error', Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже успешно прошла через форму регистрации.\n Воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля.")); return $this->redirectUser($url = Url::to(['/main/login'])); } else { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже происходила через аккунт <strong>" . $user->auths->source . "</strong>.\n Выполните вход используя аккаунт <strong>" . $user->auths->source . "</strong> или воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля для\n пользователя с емайл <strong>" . $user->email . "</strong>.", ['client' => $title = $client->getTitle()])]); return $this->redirectUser($url = Url::to(['/main/login'])); } } else { // Полученные данные заносим в переменные /* @var $email string */ /* @var $first_name string */ /* @var $second_name string */ if (Yii::$app->request->get('authclient') == 'google') { $first_name = $attributes['name']['givenName']; $second_name = $attributes['name']['familyName']; $email = $attributes['emails'][0]['value']; } elseif (Yii::$app->request->get('authclient') == 'yandex') { $first_name = $attributes['first_name']; $second_name = $attributes['last_name']; $email = $attributes['default_email']; } elseif (Yii::$app->request->get('authclient') == 'facebook') { $names = explode(' ', $attributes['name']); $first_name = $names[0]; $second_name = $names[1]; $email = $attributes['email']; } elseif (Yii::$app->request->get('authclient') == 'vkontakte') { $first_name = $attributes['first_name']; $second_name = $attributes['last_name']; $email = false; } elseif (Yii::$app->request->get('authclient') == 'twitter') { $names = $attributes['name']; $names = explode(' ', $names); $first_name = $names[0]; $second_name = $names[1]; $email = false; } elseif (Yii::$app->request->get('authclient') == 'linkedin') { $first_name = $attributes['first_name']; $second_name = $attributes['last_name']; $email = $attributes['email']; } $password = Yii::$app->security->generateRandomString(6); $user = new User(['email' => $email, 'password' => $password, 'status' => User::STATUS_NOT_ACTIVE]); $user->generateAuthKey(); $user->generateSecretKey(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $auth = new Auth(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $attributes['id']]); if ($auth->save()) { /* @var $modelProfile /common/models/Profile */ $modelProfile = new Profile(); $modelProfile->user_id = $user->id; $modelProfile->first_name = $first_name; $modelProfile->second_name = $second_name; if ($modelProfile->save()) { $transaction->commit(); // если нет емайл, делаем перенаправление на main/finish-reg if ($email == false) { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите телефон и подтвердите адрес электронной почты.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите номер телефона.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); //Yii::$app->user->login($user); } } else { //dd($user->errors); print_r($auth->getErrors()); } } else { $user = User::findOne(['email' => $user->email]); // Если пользователь регитрировался ранее через форму регистации. if ($user->status == User::STATUS_ACTIVE) { Yii::$app->getSession()->setFlash('error', Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже успешно прошла через форму регистрации.\n Воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля.")); return $this->redirectUser($url = Url::to(['/main/login'])); } else { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже происходила через аккунт <strong>" . $user->auths->source . "</strong>.\n Выполните вход используя аккаунт <strong>" . $user->auths->source . "</strong> или воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля для\n пользователя с емайл <strong>" . $user->email . "</strong>.", ['client' => $title = $client->getTitle()])]); return $this->redirectUser($url = Url::to(['/main/login'])); } } } } } 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(); } } return true; }