/** * Lists all ApiLogs models. * @return mixed */ public function actionIndex() { $user = User::findIdentity(Yii::$app->user->id); $user->level == 1 ? $searchModel = new ApiLogsSearch() : ($searchModel = new UserApiLogsSearch()); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider]); }
/** * Signs user up. * * @return true|null the saved model or null if saving fails */ public function signup() { if ($this->validate()) { $user = new User(); $user->phone = $this->phone; $user->email = $this->email; $randLength = mt_rand(6, 9); $this->password = Yii::$app->security->generateRandomString($randLength); $user->setPassword($this->password); $user->generateAuthKey(); if ($user->save()) { $profile = new Profile(); $profile->user_id = $user->id; $profile->name = $this->name; //если в куках есть id аффилиата, сохраняем его $affiliateId = (int) Yii::$app->request->cookies['affiliate']; if ($affiliateId > 0 && User::findIdentity($affiliateId)) { $profile->user_affiliate_id = $affiliateId; } $profile->save(); return $this->sendRegistrationEmail(); } } return null; }
public function findPasswords($attribute, $params) { $user = User::findIdentity(Yii::$app->user->id); if (!$user->validatePassword($this->currentPassword)) { $this->addError($attribute, 'Old password is incorrect'); } }
public function rules() { return [[['password', 'email', 'title'], 'required', 'on' => self::SCENARIO_NEW], [['email', 'title'], 'required', 'on' => self::SCENARIO_EDIT], ['password', 'string', 'min' => Yii::$app->params['passLength']], ['password_repeat', 'compare', 'compareAttribute' => 'password', 'message' => Yii::t('app', "Passwords don't match")], [['ssid'], 'default', 'value' => helper::getSsid()], [['ssid', 'shop_id'], 'integer'], [['title'], 'string', 'max' => 100], [['description'], 'string', 'max' => 250], 'emailPattern' => ['email', 'email'], 'emailLength' => ['email', 'string', 'max' => 255], 'emailUniqueEdit' => ['email', function ($attribute) { if (User::findByEmail($this->email)) { $this->addError($attribute, $this->email . Yii::t('app', 'Email already exist')); } }, 'when' => function () { $user = User::findByEmail($this->email); if (!empty((array) $user)) { return Yii::$app->user->id != $user->id; // do not check for current user (my email) } }, 'on' => self::SCENARIO_EDIT], 'emailUniqueNew' => ['email', function ($attribute, $params) { $user = User::findByEmail($this->{$attribute}); if (!empty((array) $user)) { $this->addError($attribute, Yii::t('app', 'Email already exist')); } }, 'on' => self::SCENARIO_NEW], 'emailTrim' => ['email', 'trim'], 'oldPassCheck' => ['password_old', function ($attribute) { $user = User::findIdentity($this->id); if (!empty((array) $user)) { if ($user->validatePassword($this->password_old)) { $this->addError($attribute, Yii::t('app', 'Password Do not match')); } } }, 'on' => self::SCENARIO_EDIT]]; }
public function searchTreeView($params) { $user = User::findIdentity(Yii::$app->user->id); $query = User::find(); $query->where('status != ' . User::STATUS_DELETED); // $query->andwhere('id != '.Yii::$app->user->id); $query->andwhere('referrer IS NULL OR referrer = "' . $user->code . '" '); // if($params == null){ // $query->andwhere(['referrer'=>$user->code]); // // } $dataProvider = new ActiveDataProvider(['query' => $query, 'sort' => ['defaultOrder' => ['created_at' => SORT_DESC, 'first_name' => SORT_ASC]]]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to any records when validation fails $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['state' => $this->state, 'sex' => $this->sex, 'zip' => $this->zip, 'code' => $this->code, 'referrer' => $this->referrer, 'graduate_high_school' => $this->graduate_high_school]); if ($this->status != null) { $query->andFilterWhere(['status' => $this->status]); } $query->andFilterWhere(['like', 'first_name', $this->first_name])->orFilterWhere(['like', 'last_name', $this->first_name]); $query->andFilterWhere(['like', 'email', $this->email]); $query->andFilterWhere(['like', 'city', $this->city]); $query->andFilterWhere(['like', 'mobile', $this->mobile]); return $dataProvider; }
public function actionIndex($id) { $user = User::findIdentity($id); $comments = Comment::getRecentComments(); $sidebarCategories = Category::getSidebarCategories(); $tags = Tag::getTagList(); return $this->render('index', ['user' => $user, 'comments' => $comments, 'sidebarCategories' => $sidebarCategories, 'tags' => $tags]); }
public function resetPassword() { $this->_user = User::findIdentity(Yii::$app->user->id); if (!Yii::$app->getSecurity()->validatePassword($this->password, $this->_user->password_hash)) { throw new InvalidParamException(Yii::t('User', 'source_password_error')); } $this->_user->setPassword($this->new_password); return $this->_user->save(false); }
public function save_signature() { $user = User::findIdentity(Yii::$app->user->id); $user->signature = Functions::clear_text($this->signature); if ($user->save()) { return Html::decode($user->signature); } return false; }
/** * Creates a form model given a token. * * @param string $token * @param array $config name-value pairs that will be used to initialize the object properties * @throws \yii\base\InvalidParamException if token is empty or not valid */ public function __construct($id, $config = []) { $this->_user = User::findIdentity($id); if (!$this->_user) { throw new InvalidParamException('Unable to find user!'); } $this->id = $this->_user->id; $this->username = $this->_user->username; parent::__construct($config); }
/** * Check status verified * @param [type] $user_id [description] * @return [type] [description] */ function statusVerified($user_id) { $profile = static::findOne(['user_id' => $user_id, 'created_by' => $user_id]); $user = User::findIdentity($user_id); if ($profile->email != $user->email) { $email = $profile->email . ' <span class="label label-warning">Not Verified</span>'; } elseif ($profile->email === $user->email) { $email = $profile->email . ' <span class="label label-success">Verified</span>'; } return $email; }
public function save_age_date() { $user = User::findIdentity(Yii::$app->user->id); if ($user->age_date != $this->age_date) { $user->age_date = $this->age_date; if ($user->save()) { return Functions::get_is_age_from_date($this->age_date); } } return false; }
public function actionInputPenduduk() { // get user from class User by id $getUser = User::findIdentity(Yii::$app->user->id); // check user level, if level equals 1 then user is an admin, he can through frontend or backend, if else user is a user, he only can through frontend if ($getUser->level == 1) { return $this->render('input_penduduk'); } else { return $this->redirect(['../../frontend/web/', 'id' => Yii::$app->user->id]); } }
/** * Проверка доступа к ресурсу. * * @param int $userId Идентификатор пользователя. * @param \yii\rbac\Item $item Роль. * @param array $params Параметры для проверки доступа. * @return bool */ public function execute($userId, $item, $params) { // Если не указан обязательный параметр action. if (!isset($params['action']) || !in_array($params['action'], $this->actions)) { return false; } // Пользователь не может редактировать и удалять сам себя. if (in_array($params['action'], [self::ACTION_EDIT_USER, self::ACTION_DELETE_USER]) && $userId == $params['userId']) { return false; } // Админам, кроме редактирования, удаления самомго себя разрешаются все действия. $user = User::findIdentity($userId); if ($user->isAdmin()) { return true; } // Менеджерам запрещено выполнять какие-либо действия на пользователями. if ($user->isManager()) { return false; } // Если добавление пользователя. if ($params['action'] == self::ACTION_ADD_USER) { return true; } else { // Если не указан идентификатор пользователя, над которым выполняется действие. if (!isset($params['userId'])) { return false; } $actionUser = User::findIdentity($params['userId']); // Если пользователь, на которым выполняется действие из другой компании, запрещаем что-либо делать. if ($actionUser->getCompanyId() != $user->getCompanyId()) { return false; } // Если пользователь, над которым выполняется действие администратор, запрещаем действие. if ($actionUser->isAdmin()) { return false; } // Если действие редактирование или удаление и если пользователь оовнер или пользователь, который выполняет // действие босс и пользователь, над которым выполняется тоже босс, разрешаем выполнение. $isChangeUserAction = in_array($params['action'], [self::ACTION_EDIT_USER, self::ACTION_DELETE_USER]); if ($isChangeUserAction && ($user->isOwner() || $user->isBoss() && ($actionUser->isBoss() || $actionUser->isManager()))) { return true; } // Просматривать можно и овнерам и боссам. if (self::ACTION_VIEW_USER == $params['action']) { return true; } return false; } }
/** * Displays homepage. * * @return mixed */ public function actionIndex() { if (Yii::$app->user->isGuest) { return $this->render('index'); } else { $user = User::findIdentity(Yii::$app->user->id); //var_dump($user);die; $type = $user['type']; if ($type == 'Tutor' || $type == 'tutor') { return $this->redirect('index.php?r=file/index'); } else { return $this->render('studentHome'); } } }
/** * TODO: допилить, разделить * @param \yii\authclient\BaseClient $client * @return bool */ public function successAuthclientCallback($client) { $attributes = $client->getUserAttributes(); //TODO: добавить обновление данных if (!Yii::$app->getUser()->isGuest) { $userAuthClient = \common\models\UserAuthclient::findOne(["user_id" => Yii::$app->user->getId(), "provider" => $client->getId(), "provider_identifier" => $attributes["id"]]); if (!$userAuthClient) { $userAuthClient = new \common\models\UserAuthclient(["user_id" => Yii::$app->user->getId(), "provider" => $client->getId(), "provider_identifier" => $attributes["id"], "provider_data" => serialize($attributes)]); $userAuthClient->save(); } } else { $userAuthClient = \common\models\UserAuthclient::findOne(["provider" => $client->getId(), "provider_identifier" => $attributes["id"]]); if ($userAuthClient) { $user = \common\models\User::findIdentity($userAuthClient->getUserId()); if ($user) { return Yii::$app->user->login($user, 0); } } } }
/** * Lists all File models. * @return mixed */ public function actionIndex() { if (Yii::$app->user->isGuest) { return $this->redirect('index.php?r=site/login'); } else { $user = User::findIdentity(Yii::$app->user->id); //var_dump($user);die; $type = $user['type']; if ($type == 'Tutor' || $type == 'tutor') { $searchModel = new FileSearch(); $dataProvider = $searchModel->search(array('user' => Yii::$app->user->id)); } else { $searchModel = new FileSearch(); $dataProvider = $searchModel->search(array('user' => Yii::$app->user->id)); //filtering only self uploaded files $dataProvider->sort = ['defaultOrder' => ['user' => SORT_ASC]]; $dataProvider->query->where('user='******'index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'type' => $type]); } }
public function afterSave($insert, $changedAttributes) { parent::afterSave($insert, $changedAttributes); // Updates a timestamp attribute to the current timestamp if (!$insert) { User::findIdentity($this->user_id)->touch('updated_at'); } }
/** * is Admin? * @param string $id * @return boolean */ public static function isAdmin() { $user = User::findIdentity(Yii::$app->user->id); return $user->level == 1 ? true : false; }
<?php use yii\helpers\Html; use common\models\User; /** * @var yii\web\View $this * @var app\models\Comment $model */ $this->title = Yii::t('app', '回复主题', ['modelClass' => 'Comment']); $userImage = explode('.', User::findIdentity($model->author_id)->file); $userSmallImage = $userImage['0'] . '_small.' . $userImage['1']; ?> <li class="media" data-key="37182"> <a class="pull-left" href="/User/<?php echo $model->author_id; ?> " data-original-title="" title=""> <img class="media-object" src="/<?php echo $userSmallImage; ?> " alt=""> </a> <div class="media-body"> <div class="media-heading"> <a href="/User/<?php echo $model->author_id; ?> "><?php echo $model->author_name; ?>
/** * 获取我的代祷列表 * @param $user_id * @param $start_page * @param $page_no * @throws Exception * @return array */ protected function myIntercessionList($user_id, $start_page, $page_no) { $intercessionList = Intercession::findAllByUserId($user_id, $start_page, $page_no); //获取最新头像 $portraitInfo = Portrait::findByUserId($user_id); //获取用户信息 $userInfo = User::findIdentity($user_id); if (!$userInfo) { throw new Exception('用户不存在'); } //分类数据 $data = []; if ($intercessionList) { foreach ($intercessionList as $v) { //获取代祷更新列表 $updateList = IntercessionUpdate::getListWithIntercessionId($v['id']); $resultUpdateList = []; foreach ($updateList as $updateInfo) { $resultUpdateList[] = ['content' => $updateInfo['content'], 'create_time' => $updateInfo['created_at'] * 1000]; } $resultUpdateList = array_merge($resultUpdateList, [['content' => $v['content'], 'create_time' => $v['created_at'] * 1000]]); //获取代祷勇士 $intercessorsList = IntercessionJoin::getAllByIntercessionId($v['id']); $resultIntercessorsList = []; foreach ($intercessorsList as $intercessorsInfo) { $resultIntercessorsList[] = ['user_id' => $intercessorsInfo['id'], 'nick_name' => $intercessorsInfo['nickname']]; } //构造返回数据 $data[] = ['user_id' => $v['user_id'], 'intercession_id' => $v['id'], 'content_list' => $resultUpdateList, 'intercession_number' => $v['intercessions'], 'avatar' => !$portraitInfo ? '' : yii::$app->qiniu->getDomain() . '/' . $portraitInfo['portrait_name'], 'nick_name' => $userInfo['nickname'], 'time' => $v['created_at'] * 1000, 'relationship' => 0, 'position' => $v['position'], 'intercessors_list' => $resultIntercessorsList, 'is_interceded' => true, 'gender' => (int) $userInfo['gender']]; } } return $data; }
<?php use yii\helpers\Html; use common\models\User; use frontend\models\Societe; /* @var $this yii\web\View */ /* @var $user common\models\User */ $appLink = \Yii::$app->urlManager->createAbsoluteUrl(['home']); $societe_id = User::findIdentity(Yii::$app->user->getId())->id_societe; $societe_name = Societe::findOne($societe_id)->name; ?> <div class="password-reset"> <p><?php echo \Yii::t('app/user', 'Welcome to ') . $societe_name; ?> !</p> <p><?php echo \Yii::t('app/user', 'Your user is: ') . Html::encode($user->username); ?> </p> <p><?php echo \Yii::t('app/user', 'Your password is: ') . Html::encode($password); ?> </p> <p><?php echo \Yii::t('app/user', 'Access URL: ') . Html::a(Html::encode($appLink), \Yii::$app->name); ?> </p>
public function actionProfile() { if (Yii::$app->user->can("admin")) { $this->layout = "admin"; } Yii::$app->view->title = "Lifeguard - Profile"; $model = User::findIdentity(Yii::$app->user->id); if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($model->referrer != "" && User::findOne(["code" => $model->referrer]) === null) { Yii::$app->session->setFlash('warning', 'The Referrer code is wrong.'); } Yii::$app->getSession()->setFlash('success', 'Your profile was saved.'); } return $this->render('profile', ['model' => $model]); }
/** * @var \yii\web\View $this * @var \yii\gii\Generator[] $generators * @var \yii\gii\Generator $activeGenerator * @var string $content */ //$activeGenerator = Yii::$app->controller->generator; /* * 如果url中传递的id存在,判断是否是当前登录用户, * $userid == Yii::$app->user->id; * 1.是当前用户调用模块为1, * 2.不是当前模块调用模块为2 */ $userid = isset($_GET['id']) ? $_GET['id'] : Yii::$app->user->id; //url中的id $userImage = explode('.', User::findIdentity($userid)->file); $userMiddleImage = $userImage['0'] . '_middle.' . $userImage['1']; $userBigImage = $userImage['0'] . '_big.' . $userImage['1']; $this->beginContent('@app/views/layouts/main.php'); //$this->beginContent('@app/views/layouts/main.php'); ?> <style type="text/css"> .list-group .glyphicon { float: right; } </style> <div class="row"> <div class="col-lg-3 sidebar"> <div class="well"> <div class="media"> <div class="pull-left">
/** * Resets password. * * @return boolean if password was reset. */ public function resetPassword() { $user = User::findIdentity(\Yii::$app->user->id); $user->setPassword($this->password); return $user->save(false); }
public function actionReportOne() { if (!Yii::$app->user->can("admin")) { throw new NotFoundHttpException('The requested page does not exist.'); } $this->layout = "admin"; $user = User::findIdentity(Yii::$app->user->id); $perPage = Yii::$app->request->Get("per-page"); if (!isset($perPage)) { $perPage = 20; } $searchModel = new ReferrerSearch(); $dataProvider = $searchModel->reportOne(Yii::$app->request->queryParams); $dataProvider->pagination->pageSize = $perPage; return $this->render('report-one', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'user' => $user]); }
/** * Finds user by [[username]] * * @return User|null */ public function getUser() { return User::findIdentity(Yii::$app->user->id); }
public function validateOldPassword($attribute, $params) { if (!$this->hasErrors()) { $user = User::findIdentity(\Yii::$app->user->user_id); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, 'Password lama tidak cocok.'); } } }
public static function getAvatar($id) { $model = User::findIdentity($id); if ($model) { return \yii\helpers\Html::img('/upload/user/' . $id . '/avatar/avatar.jpg', ['width' => '100px']); } else { return false; } }
/** * */ public function actionChangeAvatar($id_user = null) { $model = new UploadForm(); //Récupération du dossier frontend/web/uploads/sha1(login)/ if ($id_user == NULL) { $user = Yii::$app->user->identity; } else { $user = User::findIdentity($id_user); } $accountUser = $user->findAccount(); if ($accountUser->getAvatar() != NULL) { $avatar = UploadFile::findIdentity($accountUser->avatar); } else { $avatar = NULL; } //var_dump($avatar);die; if (Yii::$app->request->isPost) { //Chemin du dossier upload de l'User $hash = sha1($user->username); $path = 'uploads/' . $hash; $model->imageFile = UploadedFile::getInstance($model, 'imageFile'); if ($id = $model->uploadAvatar($path)) { //Association user $accountUser->updateAvatar($id); // file is uploaded successfully Yii::$app->getSession()->setFlash('success', 'Avatar changé'); return $this->redirect(['index']); } else { echo "Echec de l'upload"; } } return $this->renderAjax('change-avatar', ['model' => $model, 'user' => $user, 'avatar' => $avatar]); }
/** * Изменение статуса */ public function actionChangestatus() { if (Yii::$app->getRequest()->getIsAjax() && Yii::$app->getRequest()->post()) { Yii::$app->getResponse()->format = Response::FORMAT_JSON; $params = Yii::$app->getRequest()->post(); if (empty($params['userId']) || empty($params['leadId']) || empty($params['selectedStatus'])) { return ['status' => false]; } /** @var \common\models\User $user */ $user = User::findIdentity($params['userId']); /** @var \common\models\Lead $lead */ $lead = Lead::findOne(['lead_id' => $params['leadId'], 'company_id' => $user->getCompanyId(), 'is_deleted' => false]); if (!$lead) { return ['status' => false]; } $lead->setStatus($params['selectedStatus']); $lead->setChangeStatusUserId($params['userId']); $status = $lead->save(); $this->leadLogger->write($lead, LeadActionLog::ACTION_CHANGE_STATUS); return ['status' => $status, 'selectedStatus' => $params['selectedStatus'], 'result' => ChangeLeadStatusWidget::widget(['userId' => $params['userId'], 'leadId' => $params['leadId'], 'status' => $params['selectedStatus']])]; } $this->redirect('/lead/index'); }