public function login($email, $password) { $user = new User(); if ($user->getIdentity() != $email) { throw new \Vegas\Security\Authentication\Exception\InvalidCredentialException(); } $this->di->get('auth')->authenticate($user, $password); }
public function load(ObjectManager $manager) { $user = new User(); $user->setUsername('superadmin'); $user->setFirstname('Super'); $user->setLastname('Admin'); $user->setPassword(password_hash('123456', PASSWORD_BCRYPT)); $user->setEmail('*****@*****.**'); $user->setCreatedAt(new \DateTime()); $user->setStatus(User::STATUS_ACTIVE); $user->setGroup($this->getReference('super_group')); $manager->persist($user); $manager->flush(); }
/** * @param Post $post * @return boolean */ public function mentionHandler($post) { $usernames = MentionHelper::find($post->message); if (!empty($usernames)) { foreach ($usernames as $username) { /** @var User $mentioned */ $mentioned = User::findByUsername($username); if (!$mentioned instanceof User) { continue; } $exist = UserMention::find()->where(['post_id' => $post->id, 'mention_user_id' => $mentioned->id, 'status' => UserMention::MENTION_SATUS_UNVIEWED])->exists(); if ($exist) { continue; } $currentUser = Yii::$app->getUser()->getIdentity(); $model = new UserMention(); $model->user_id = $currentUser->id; $model->mention_user_id = $mentioned->id; $model->post_id = $post->id; $model->topic_id = $post->topic->id; $model->status = UserMention::MENTION_SATUS_UNVIEWED; if ($mentioned->notify_mention_web == 1) { $model->save(); } if ($mentioned->notify_mention_email == 1) { \Yii::$app->mailer->compose(['text' => 'mention'], ['model' => $model, 'topic' => $post->topic])->setFrom([Yii::$app->config->get('support_email') => Yii::$app->config->get('site_title')])->setTo([$model->mentionUser->email => $model->mentionUser->username])->setSubject('#' . $post->id . ' ' . $post->topic->subject)->send(); } } return true; } return false; }
/** * Send emails to reviewers with contributions to need review. * If reviewer has no any reviews - does not send it. * Collect contributions by project IDs. */ public function actionSendReviewerEmail() { // get projects /* @var $projects Project */ $projects = Project::find()->all(); // get active reviewers /* @var $reviewers User[] */ $reviewers = User::find(['status' => User::STATUS_ACTIVE])->indexBy('id')->all(); // collect contributions to need review for each project foreach ($reviewers as $reviewer) { $this->logInfo('Collect reviews for: ', $reviewer->getContributorName()); $contributionsByProjects = []; foreach ($projects as $project) { $aggregator = new ContributionAggregator(['projectId' => $project->id, 'reviewerId' => $reviewer->id, 'type' => ContributionAggregator::TYPE_NOT_FINISHED]); $statistic = $aggregator->aggregateByContributor(); if (!empty($statistic)) { $contributionsByProjects[$project->id] = ['project' => $project, 'statistic' => $statistic]; } } $this->logInfo('Total projects to review: ', count($contributionsByProjects)); if (!empty($contributionsByProjects)) { // send email to reviewer $result = $this->sendEmailToReviewer($reviewer, $contributionsByProjects); $this->logInfo('Send e-mail to ' . $reviewer->getContributorEmail() . ': ', $result ? 'done' : 'error'); } } }
public static function getActiveUsers() { $array_ids = static::find()->select(['user_id'])->where('user_id > 0')->asArray()->all(); $ids = \yii\helpers\ArrayHelper::getColumn($array_ids, 'user_id'); $users = User::find()->select(['id', 'username'])->where(['IN', 'id', $ids])->asArray()->all(); return $users; }
/** * Validates user's password * * @param string $attribute * @param array $params */ public function validatePassword($attribute, $params) { $this->user = null; if (!$this->hasErrors()) { $this->user = User::findByUsername($this->email); if (!$this->user instanceof User) { // user not found $this->addError($attribute, Yii::t('user', 'Wrong user name or password')); return; } /* @var $api UserModule */ $api = Yii::$app->getModule('user'); if (!$api->checkUserPassword($this->user, $this->{$attribute})) { $this->addError($attribute, Yii::t('user', 'Wrong user name or password')); return; } // switch user status if (!$this->user->canSignIn()) { switch ($this->user->status) { case User::STATUS_BLOCKED: $this->addError($attribute, Yii::t('user', 'An account is blocked')); break; default: $this->addError($attribute, Yii::t('user', 'An account is unactive')); break; } } } }
/** * @inheritdoc */ public function init() { if (!$this->model instanceof User) { throw new InvalidParamException('Model must be an instance of ' . User::className()); } $this->items = [['url' => ['/user/user-manager/update', 'id' => $this->model->id], 'label' => Yii::t('user', 'Common settings')], ['url' => ['/user/user-manager/vcs-bindings', 'id' => $this->model->id], 'label' => Yii::t('user', 'VCS bindings')]]; parent::init(); }
/** * @inheritdoc */ public function init() { if (!$this->authUser instanceof User) { throw new InvalidParamException('AuthUser must be an instance of ' . User::className()); } $this->items = [['url' => ['/user/profile/index'], 'label' => Yii::t('user', 'Common settings')], ['url' => ['/user/profile/vcs-bindings'], 'label' => Yii::t('user', 'VCS bindings')]]; parent::init(); }
public function login($email, $password) { $user = User::findFirst(['conditions' => 'email = :email:', 'bind' => ['email' => $email]]); if (!$user) { throw new \Vegas\Security\Authentication\Exception\InvalidCredentialException(); } $this->di->get('auth')->authenticate($user, $password); }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = User::find(); $dataProvider = new ActiveDataProvider(['query' => $query]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'status' => $this->status, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at]); $query->andFilterWhere(['like', 'username', $this->username])->andFilterWhere(['like', 'auth_key', $this->auth_key])->andFilterWhere(['like', 'password_hash', $this->password_hash])->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])->andFilterWhere(['like', 'email', $this->email]); return $dataProvider; }
/** * Validate user model * * @throws NotFoundHttpException */ public function init() { if (!$this->model instanceof User && $this->userId) { $userId = is_scalar($this->userId) ? (int) $this->userId : 0; $this->model = User::findOne($userId); } if (!$this->model instanceof User) { throw new NotFoundHttpException(); } $this->userModule = Yii::$app->getModule('user'); parent::init(); }
/** * @name 角色用户分配列表 */ public function actionUser($id) { $auth = Yii::$app->authManager; $users = User::find()->where(['status' => 10])->andWhere('id>1')->orderBy('username')->all(); $users_info = []; foreach ($users as $k => $v) { $pin = strtoupper(substr(Pinyin::pinyin($v['username']), 0, 1)); $users_info[$pin][$v['id']] = ['username' => $v['username'], 'pinyin' => Pinyin::pinyin($v['username']), 'is_sel' => $auth->getAssignment($id, $v['id']) ? 1 : 0]; } $keys = array_keys($users_info); return $this->render('user', ['user' => $users_info, 'keys' => $keys, 'role_name' => $id]); }
protected function inlineUserMention($Excerpt) { if (preg_match('/\\B@([a-zA-Z][\\w-]+)/', $Excerpt['context'], $matches)) { /** @var User $user */ $user = User::findByUsername($matches[1]); if ($user) { return ['extent' => strlen($matches[0]), 'element' => ['name' => 'a', 'text' => $matches[0], 'attributes' => ['href' => '/user/' . $user->id, 'class' => 'user-mention']]]; } else { return ['markup' => $matches[0], 'extent' => strlen($matches[0])]; } } }
/** * Creates a new administrative user's account. */ public function actionAdminCreate() { $password = $this->prompt('Enter password:'******'required' => true]); if (!$password) { return self::EXIT_CODE_ERROR; } // create user model $user = new User(); $user->setAttributes(['name' => $this->name, 'email' => $this->email, 'status' => User::STATUS_ACTIVE]); $user->newPassword = $password; $this->stdout("\n"); if (!$user->validate()) { // validation errors $this->stdout('Validation errors...' . "\n", Console::FG_YELLOW); foreach ($user->getErrors() as $attribute => $errors) { $error = reset($errors); $this->stdout($user->getAttributeLabel($attribute) . ': ', Console::FG_RED); $this->stdout($error . "\n"); } return self::EXIT_CODE_ERROR; } /* @var $api UserModule */ $api = Yii::$app->getModule('user'); try { $api->createAdmin($user); $this->stdout('User successfully created. ID: ' . $user->id . "\n", Console::FG_GREEN); } catch (Exception $ex) { // Database error $this->stdout('Database error.' . "\n", Console::FG_RED); return self::EXIT_CODE_ERROR; } }
/** * Prepare testing data and returns it * * @return array */ protected function prepareFixtures() { /* @var $contributor User */ $contributor = $this->getModule('Yii2')->grabFixture('users', 'activeUser1'); /* @var $reviewer User */ $reviewer = $this->getModule('Yii2')->grabFixture('users', 'activeUser2'); // authorized user model $authModel = new Auth(['identityClass' => User::className(), 'identity' => $reviewer]); /* @var $project Project */ $project = $this->getModule('Yii2')->grabFixture('projects', 'gitProject'); /* @var $history BaseCommit[] */ $history = $project->getRepositoryObject()->getHistory(1, 0); $this->assertNotEmpty($history); $commit = $history[0]; $this->assertInstanceOf(BaseCommit::className(), $commit); return [$contributor, $reviewer, $authModel, $project, $commit]; }
/** * Retrieve contributor model by vcs type, contributorName, contributorEmail. * * If contributor registered at the system, returns it, if else - returns UnregisteredContributor model. * * @see UserAccount * @see User * * @param string $vcsType VCS type (git, hg, etc.) * @param string $contributorName VCS contributor name (e.g. commiter name) * @param string $contributorEmail VCS contributor e-mail (e.g. commiter e-mail, if exists) * * @return ContributorInterface Returns registered user, or UnregisteredContributor model. */ public function getContributor($vcsType, $contributorName, $contributorEmail = null) { /* @var $cached ContributorInterface[] */ static $cached = []; $cacheKey = $vcsType . '_' . $contributorName . '_' . $contributorEmail; if (!isset($cached[$cacheKey])) { /* @var $res ActiveQuery */ $res = User::find()->joinWith('accounts')->orWhere([UserAccount::tableName() . '.username' => $contributorName, UserAccount::tableName() . '.type' => $vcsType]); if (!empty($contributorEmail)) { $res->orWhere([User::tableName() . '.email' => $contributorEmail]); } $res->groupBy(User::tableName() . '.id'); $cached[$cacheKey] = $res->one(); if (!$cached[$cacheKey]) { // contributor not found // set as unregistered $cached[$cacheKey] = new UnregisteredContributor(['contributorName' => $contributorName, 'contributorEmail' => $contributorEmail]); } } return $cached[$cacheKey]; }
/** * @return string */ public function actionMention() { if (Yii::$app->getRequest()->getIsAjax()) { Yii::$app->response->format = Response::FORMAT_JSON; $id = substr(Yii::$app->getRequest()->get('id'), 1); $query = Yii::$app->getRequest()->get('query'); if (is_numeric($id)) { $posts = Post::find()->with(['user' => function ($query) { /** @var \yii\db\Query $query */ $query->andWhere(['not in', 'id', Yii::$app->getUser()->getId()]); }])->where(['topic_id' => $id])->orderBy(['created_at' => SORT_DESC])->asArray()->all(); $users = ArrayHelper::getColumn($posts, 'user'); $usernames = array_unique(ArrayHelper::getColumn($users, 'username')); $usernames = array_diff($usernames, ['']); } else { $usernames = User::find()->where(['like', 'username', $query . '%', false])->orderBy(['number_posts' => SORT_DESC])->limit(5)->asArray()->all(); $usernames = ArrayHelper::getColumn($usernames, 'username'); } $usernames = array_values($usernames); return $usernames; } throw new NotFoundHttpException(); }
public function actionNotifications($id = 0) { if (Yii::$app->request->get('id') == 0 && !Yii::$app->getUser()->getIsGuest()) { $id = Yii::$app->getUser()->getIdentity()->getId(); } /** @var User $user */ $user = User::findOne(['id' => $id]); if (!$user || !Yii::$app->getUser()->can('updateProfile', ['user' => $user])) { throw new NotFoundHttpException(); } $model = new NotifyForm(); if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { $user->notify_mention_email = (int) $model->notify_mention_email; $user->notify_mention_web = (int) $model->notify_mention_web; $user->save(); } } else { $model->notify_mention_email = $user->notify_mention_email; $model->notify_mention_web = $user->notify_mention_web; } return $this->render('notifications', ['user' => $user, 'model' => $model]); }
/** * Test model validation and save */ public function testValidationSaveAndDelete() { $model = new ContributionReview(); $attributes = ['commit_id' => [['value' => null, 'isValid' => false], ['value' => [], 'isValid' => false], ['value' => ['wrong string'], 'isValid' => false], ['value' => str_repeat('A', 41), 'isValid' => false], ['value' => 1, 'isValid' => false], ['value' => md5(uniqid()), 'isValid' => true]], 'project_id' => [['value' => null, 'isValid' => false], ['value' => [], 'isValid' => false], ['value' => ['wrong string'], 'isValid' => false], ['value' => 'string', 'isValid' => false], ['value' => $this->getModule('Yii2')->grabFixture('projects', 'gitProject')->id, 'isValid' => true]], 'date' => [['value' => null, 'isValid' => false], ['value' => [], 'isValid' => false], ['value' => ['wrong string'], 'isValid' => false], ['value' => 'string', 'isValid' => false], ['value' => 1, 'isValid' => false], ['value' => date('Y-m-d H:i:s'), 'isValid' => true]], 'contributor_id' => [['value' => null, 'isValid' => true], ['value' => [], 'isValid' => true], ['value' => '', 'isValid' => true], ['value' => 'wrong integer', 'isValid' => false], ['value' => ['wrong integer'], 'isValid' => false], ['value' => $this->getModule('Yii2')->grabFixture('users', 'activeUser1')->id, 'isValid' => true]], 'reviewer_id' => [['value' => null, 'isValid' => true], ['value' => [], 'isValid' => true], ['value' => '', 'isValid' => true], ['value' => 'wrong integer', 'isValid' => false], ['value' => ['wrong integer'], 'isValid' => false], ['value' => $this->getModule('Yii2')->grabFixture('users', 'activeUser2')->id, 'isValid' => true]], 'message' => [['value' => null, 'isValid' => true], ['value' => 0, 'isValid' => false], ['value' => [], 'isValid' => true], ['value' => ['wrong string'], 'isValid' => false], ['value' => 'test message', 'isValid' => true]], 'contributor_email' => [['value' => null, 'isValid' => true], ['value' => [], 'isValid' => true], ['value' => 0, 'isValid' => false], ['value' => ['wrong string'], 'isValid' => false], ['value' => 'test contributor', 'isValid' => true]], 'contributor_name' => [['value' => null, 'isValid' => false], ['value' => [], 'isValid' => false], ['value' => 0, 'isValid' => false], ['value' => '', 'isValid' => false], ['value' => ['wrong string'], 'isValid' => false], ['value' => 'test contributor', 'isValid' => true]], 'repo_type' => [['value' => null, 'isValid' => false], ['value' => [], 'isValid' => false], ['value' => 0, 'isValid' => false], ['value' => '', 'isValid' => false], ['value' => ['wrong string'], 'isValid' => false], ['value' => 'wrong repo', 'isValid' => false], ['value' => 'svn', 'isValid' => true], ['value' => 'git', 'isValid' => true], ['value' => 'hg', 'isValid' => true]], 'reviewed' => [['value' => null, 'isValid' => true], ['value' => [], 'isValid' => true], ['value' => ['wrong string'], 'isValid' => false], ['value' => 'string', 'isValid' => false], ['value' => 1, 'isValid' => false], ['value' => date('Y-m-d H:i:s'), 'isValid' => true]]]; $this->getModule('\\Helper\\Unit')->validateModelAttributes($model, $attributes, $this); $this->assertTrue($model->validate()); $this->assertTrue($model->save()); $this->assertInstanceOf(Project::className(), $model->project); $this->assertEquals($model->project->id, $this->getModule('Yii2')->grabFixture('projects', 'gitProject')->id); $this->assertInstanceOf(User::className(), $model->contributor); $this->assertEquals($model->contributor->id, $this->getModule('Yii2')->grabFixture('users', 'activeUser1')->id); $this->assertInstanceOf(User::className(), $model->reviewer); $this->assertEquals($model->reviewer->id, $this->getModule('Yii2')->grabFixture('users', 'activeUser2')->id); // test unique model $attributes = $model->getAttributes(); unset($attributes['id']); $newModel = new ContributionReview(); $newModel->setAttributes($attributes); $this->assertFalse($newModel->validate()); $this->assertArrayHasKey('commit_id', $newModel->getErrors()); // delete test $this->assertEquals(1, $model->delete()); }
/** * Filters for userlist page. * @param $params array * @return ActiveDataProvider */ public function search($params) { // create ActiveQuery $query = User::find()->select(['id', 'username', 'number_posts', 'created_at']); $dataProvider = new ActiveDataProvider(['query' => $query]); $dataProvider->pagination = new Pagination(['forcePageParam' => false, 'pageSizeLimit' => false, 'defaultPageSize' => 50]); if (!($this->load($params) && $this->validate())) { $query->addOrderBy(['created_at' => SORT_ASC]); return $dataProvider; } $query->andFilterWhere(['like', 'username', $this->username]); $colomn = 'created_at'; if (strcasecmp($this->sort_by, 'username') == 0) { $colomn = 'username'; } elseif (strcasecmp($this->sort_by, 'number_posts') == 0) { $colomn = 'number_posts'; } if (strcasecmp($this->sort_dir, 'ASC') == 0) { $query->addOrderBy([$colomn => SORT_ASC]); } elseif (strcasecmp($this->sort_dir, 'DESC') == 0) { $query->addOrderBy([$colomn => SORT_DESC]); } return $dataProvider; }
public function setAuthor(\user\models\User $author) { $author->addPost($this); $this->author = $author; }
/** * Authenticates authorized user * * @param Identity $oauthIdentity * @throws \User\Services\Exception\SignUpFailedException */ public function authenticate(Identity $oauthIdentity) { $auth = $this->di->get('serviceManager')->getService('auth:auth'); try { $authIdentity = $auth->authenticateByEmail($oauthIdentity->getEmail()); } catch (IdentityNotFoundException $ex) { $userService = $this->di->get('serviceManager')->getService('user:user'); $userModel = new User(); //store identity values without id, service and accessToken $identityValues = $oauthIdentity->toArray(); unset($identityValues['id']); unset($identityValues['service']); unset($identityValues['accessToken']); $userModel->writeAttributes($identityValues); //try to create new account if (!$userService->createAccount($userModel)) { throw new SignUpFailedException(); } $authIdentity = $auth->authenticateByEmail($oauthIdentity->getEmail()); } $this->afterAuthentication($authIdentity, $oauthIdentity); }
/** * @param UserModel $userEntity * @return bool */ public function createAccount(UserModel $userEntity) { $result = $userEntity->save(); return $result; }
/** * @inheritdoc */ public function rules() { return [['email', 'required', 'message' => Yii::t('app/form', 'Required email')], ['email', 'filter', 'filter' => 'trim'], ['email', 'email', 'enableIDN' => true, 'message' => Yii::t('app/form', 'Valid email')], ['email', 'unique', 'targetClass' => User::className(), 'message' => Yii::t('app/form', 'Unique email')], ['username', 'filter', 'filter' => 'trim'], ['username', 'required', 'message' => Yii::t('app/form', 'Required username')], ['username', 'string', 'min' => 2, 'tooShort' => Yii::t('app/form', 'String short username')], ['username', 'string', 'max' => 40, 'tooLong' => Yii::t('app/form', 'String long username')], ['username', 'match', 'pattern' => '/^[a-zA-Z]/', 'message' => Yii::t('app/form', 'Username match first letter')], ['username', 'match', 'pattern' => '/^[\\w-]+$/', 'message' => Yii::t('app/form', 'Username match common')], ['username', 'unique', 'targetClass' => User::className(), 'message' => Yii::t('app/form', 'Unique username')], ['password', 'required', 'message' => 'Введите пароль.'], ['password', 'string', 'min' => 6, 'tooShort' => 'Пароль должен содержать минимум {min} символа.'], ['password', 'string', 'max' => 32, 'tooLong' => 'Пароль не должен быть длиннее {max} символов.'], ['repassword', 'required', 'message' => 'Введите пароль повторно.'], ['repassword', 'compare', 'compareAttribute' => 'password', 'message' => 'Введенные пароли не совпадают.'], ['termsAgree', 'boolean'], ['termsAgree', 'required', 'requiredValue' => true, 'message' => 'Вам необходимо согласиться с правилами сайта.'], ['verifyCode', 'required', 'message' => 'Введите код безопасности с изображения.'], ['verifyCode', 'captcha', 'captchaAction' => '/captcha/default/index', 'message' => 'Код безопасности указан неверно.']]; }
/** * @return ActiveQuery */ public function getUser() { return $this->hasOne(User::className(), ['id' => 'user_id'])->inverseOf('posts'); }
/** * Finds user model by the form given username. * @return User|null current user model. * If null, it means the current user model will be not found with this username. */ public function getUser() { if (!isset($this->_user)) { if ($this->scenario == 'email') { $this->_user = User::findByEmail($this->email); } elseif ($this->scenario == 'token') { $this->_user = User::findOne(['password_change_token' => $this->token]); } } return $this->_user; }
/** * Finds the User model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return User the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = User::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
/** * Returns user's model * * @return ActiveQuery */ public function getUser() { return $this->hasOne(User::className(), ['id' => 'user_id']); }
/** * Finds user model by the form given username. * @return User|null current user model. * If null, it means the current user model will be not found with this username. */ public function getUser() { if (!$this->_user instanceof User) { $this->_user = User::findByEmail($this->email); } return $this->_user; }
/** * @param integer $id user profile identificator * @return string content */ public function actionView($id) { $user = User::findOne(['id' => $id]); return $this->render('view', ['user' => $user]); }