/** * Initiates the password reset process on behalf of the user * Generates a unique hash and an expiration time that the hash is valid up until (defaults to 15 minutes) * This key will internally expire (but not be expunged) after that time */ public function initPasswordResetProcess() { if (!$this->validate()) { return false; } $hash = Cii::generateSafeHash(); $expires = strtotime("+15 minutes"); $meta = UserMetadata::model()->findByAttributes(array('user_id' => $this->_user->id, 'key' => 'passwordResetCode')); if ($meta === NULL) { $meta = new UserMetadata(); } $meta->user_id = $this->_user->id; $meta->key = 'passwordResetCode'; $meta->value = $hash; $meta->save(); $meta = UserMetadata::model()->findByAttributes(array('user_id' => $this->_user->id, 'key' => 'passwordResetExpires')); if ($meta === NULL) { $meta = new UserMetadata(); } $meta->user_id = $this->_user->id; $meta->key = 'passwordResetExpires'; $meta->value = $expires; $meta->save(); $emailSettings = new EmailSettings(); $emailSettings->send($this->_user, Yii::t('ciims.email', 'Your Password Reset Information'), 'webroot.themes.' . Cii::getConfig('theme', 'default') . '.views.email.forgot', array('user' => $this->_user, 'hash' => $hash), true, true); // Set success flash Yii::app()->user->setFlash('success', Yii::t('ciims.controllers.Site', 'An email has been sent to {{email}} with further instructions on how to reset your password', array('{{email}}' => $this->email))); return true; }
/** * Overrides accesscontrol * @param CFilterChain $filterChain */ public function filterAccessControl($filterChain) { // Retrieve the AUTH Token and Email if they were set $this->xauthtoken = Cii::get($_SERVER, 'HTTP_X_AUTH_TOKEN', NULL); $this->xauthemail = Cii::get($_SERVER, 'HTTP_X_AUTH_EMAIL', NULL); // Determine the user associated with it, if any if ($this->xauthemail != NULL) { // If a user exists with that email address $user = Users::model()->findByAttributes(array('email' => $this->xauthemail)); if ($user == NULL) { break; } if ($user->status != Users::ACTIVE) { throw new CHttpException(403, Yii::t('Api.main', 'Only active users can access the API.')); } $q = new CDbCriteria(); $q->addCondition('t.key LIKE :key'); $q->addCondition('value = :value'); $q->addCondition('user_id = :user_id'); $q->params = array(':user_id' => $user->id, ':value' => $this->xauthtoken, ':key' => 'api_key%'); $meta = UserMetadata::model()->find($q); // And they have an active XAuthToken, set $this->user = the User object if ($meta != NULL) { $this->user = $user; } } $filter = new ApiAccessControlFilter(); $filter->user = $this->user; $filter->setRules($this->accessRules()); $filter->filter($filterChain); }
public function testUserEmailChange() { $newEmail = '*****@*****.**'; $model = $this->user; $profileForm = new ProfileForm(); $this->assertTrue($model !== NULL); $profileForm->load($model->id, true); $profileForm->email = $newEmail; // Verify that the profile form saves $this->assertTrue($profileForm->save()); // Verify that the base user model didn't change $model = $this->getUserModel(); $this->assertTrue($model->email == '*****@*****.**'); $newEmailModel = UserMetadata::model()->findByAttributes(array('user_id' => $this->user->id, 'key' => 'newEmailAddress')); // Verify that the new email is stored in the database $this->assertTrue($newEmailModel !== NULL); $this->assertTrue($newEmailModel->value == $newEmail); $key = UserMetadata::model()->findByAttributes(array('user_id' => $this->user->id, 'key' => 'newEmailAddressChangeKey')); $this->assertTrue($key !== NULL); $emailChangeForm = new EmailChangeForm(); $emailChangeForm->setUser($this->getUserModel()); $emailChangeForm->verificationKey = $key->value; $emailChangeForm->password = '******'; // Verify that the verification key works $this->assertTrue($emailChangeForm->validateVerificationKey()); // Veirfy that the email address changes $this->assertTrue($emailChangeForm->validate()); $this->assertTrue($emailChangeForm->save()); // Verify that the email has changed for the model now $model = Users::model()->findByAttributes(array('email' => '*****@*****.**')); $this->assertTrue($model->email == $newEmail); }
/** * Sends an invite to a new user * @return boolean */ public function invite() { if (!$this->validate()) { return false; } $user = new Users(); $user->attributes = array('email' => $this->email, 'firstName' => null, 'lastName' => null, 'displayName' => null, 'password' => null, 'user_role' => 5, 'status' => Users::PENDING_INVITATION); // Create a new user, but bypass validation if ($user->save(false)) { $meta = new UserMetadata(); $meta->attributes = array('user_id' => $user->id, 'key' => 'invitationKey', 'value' => Cii::generateSafeHash()); // If the key was savedm send the email out if ($meta->save()) { $emailSettings = new EmailSettings(); $emailSettings->send($user, Yii::t('ciims.models.InvitationForm', "You've Been Invited..."), 'webroot.themes.' . Cii::getConfig('theme', 'default') . '.views.email.invite', array('user' => $user, 'hash' => $meta->value), true, true); return true; } $user->delete(); } return false; }
/** * Makes the user an active user in the database, and deletes their activation token * @return boolean */ public function save() { $userId = $this->_meta->user_id; $this->_user = Users::model()->findByPk($userId); if (!$this->validate()) { return false; } $this->_user->status = Users::ACTIVE; if ($this->_user->save()) { return $this->_meta->delete(); } return false; }
/** * Create an account on this platform. * * @param string $email The email address. * @param string $nickname The nickname. * @param string $password The password in clear text (not encrypted). * @param bool $activation_required Specifies if the account activation is needed or not. If yes: generates an activation token. If no: the account will be stored as ACTIVE. * @param bool $notification Specifies if the user will be notified or not (via mail) about this action. * @param bool $update_account Specifies if the account already exists and then update its data. * @return User Returns the $user object. */ public static function createAccount($email, $nickname = null, $password = null, $activation_required = true, $notification = true, $update_account = false, $update_old_email = null) { $user = null; if (isset($email)) { $user = new User(); if ($update_account) { $user = User::model()->findByAttributes(array('email' => isset($update_old_email) ? $update_old_email : $email)); } $user->email = $email; if (!isset($nickname)) { $parts = explode('@', $email); $user->nickname = $parts[0]; } else { $user->nickname = $nickname; } $user->changeAccountPassword(isset($password) ? $password : ($password = self::generateRandomPassword())); $user->status = $activation_required ? User::STATUS_INACTIVE : User::STATUS_ACTIVE; if ($user->save()) { // TODO: write a log here /* created time */ if (!$update_account) { $user->addMeta(User::METADATA_KEY_ACCOUNT_CREATED_TIME, date('Y-m-d H:i:s', time())); } /* activation */ $activation_token = null; if ($activation_required) { $activation_token = self::generateActivationToken(); $meta = null; if ($update_account) { $meta = UserMetadata::model()->findByAttributes(array('user_id' => $user->id, 'key' => User::METADATA_KEY_ACCOUNT_ACTIVATION_TOKEN)); } if (isset($meta)) { $meta->value = $activation_token; $meta->save(); } else { $user->addMeta(User::METADATA_KEY_ACCOUNT_ACTIVATION_TOKEN, $activation_token); } } /* notification */ if ($notification) { BasicNotifier::sendTemplatedEmail($email, Yii::t('UsersModule.create', 'email.subject'), 'users/account_created', array('{USER_EMAIL_ADDRESS}' => $email, '{USER_PASSWORD}' => $password), Yii::app()->session['lang']); if ($activation_required) { $activation_link = Yii::app()->createAbsoluteUrl('users/account/activate?token=' . $activation_token); BasicNotifier::sendTemplatedEmail($email, Yii::t('UsersModule.activate', 'email.subject.required'), 'users/account_activation_required', array('{USER_ACTIVATION_LINK}' => $activation_link), Yii::app()->session['lang']); } } } } return $user; }
/** * Resets the user's password * @return boolean */ public function save() { if (!$this->validate()) { return false; } // Update the user's password $this->_user->password = $this->password; if ($this->_user->save()) { // Delete the hash and expires to prevent reuse attemps $this->_hash->delete(); $this->_expires->delete(); return true; } return false; }
/** * Updates the user's email address and rehashes their password since the password is bound to the email * @return boolean */ public function save() { if (!$this->validate()) { return false; } // This is super buggy for some reason $this->_user->email = $this->_newEmailAddress->value; // Save the model if ($this->_user->save()) { // Delete the metadata $this->_newEmailAddressChangeKey->delete(); $this->_newEmailAddress->delete(); return true; } return false; }
/** * Authenticates a user. * @return boolean whether authentication succeeds. */ public function authenticate($provider = NULL) { Yii::import('application.modules.hybridauth.Hybrid.Hybrid_Auth'); if (strtolower($provider) == 'openid') { if (!isset($_GET['openid-identity'])) { throw new CException(Yii::t('Hybridauth.main', "You chose OpenID but didn't provide an OpenID identifier")); } else { $params = array("openid_identifier" => $_GET['openid-identity']); } } else { $params = array(); } $hybridauth = new Hybrid_Auth($this->_getConfig()); $adapter = $hybridauth->authenticate($provider, $params); if ($adapter->isUserConnected()) { $this->userData = (array) $adapter->getUserProfile(); $this->userData['id'] = $this->userData['identifier']; // Map an email address if we aren't given one if ($this->userData['email'] == NULL) { $this->userData['email'] = $this->userData['id'] . '@' . $provider . '.com'; } // Attempt to find the user by the email address $user = Users::model()->findByAttributes(array('email' => $this->userData['email'])); $meta = false; // If we didn't find a match via email, check to see if they have logged in before by their provider id if ($user === NULL) { $meta = true; $user = UserMetadata::model()->findByAttributes(array('key' => $provider . 'Provider', 'value' => $this->userData['id'])); } // Set a default error code $this->errorCode = self::ERROR_UNKNOWN_IDENTITY; // Check to see if the email binding worked if ($user === NULL) { // If the user doesn't exist $this->errorCode = self::ERROR_USERNAME_INVALID; } else { // If the user does exist $this->id = $meta ? $user->user_id : $user->id; $this->errorCode = self::ERROR_NONE; } return !$this->errorCode; } }
/** * Creates a new user, and sends the appropriate messaging out * @return boolean */ public function save($sendEmail = true) { if (!$this->validate()) { return false; } $this->_user = new Users(); // Set the model attributes $this->_user->attributes = array('email' => $this->email, 'password' => $this->password, 'username' => $this->username, 'user_role' => 1, 'status' => $sendEmail ? Users::PENDING_INVITATION : Users::ACTIVE); // If we saved the user model, return true if ($this->_user->save()) { // This class my be extended by other modules, in which case we don't need to send an activation form if we don't want need it to. if ($sendEmail) { $meta = new UserMetadata(); $meta->attributes = array('user_id' => $this->_user->id, 'key' => 'activationKey', 'value' => Cii::generateSafeHash()); $meta->save(); // Send the registration email $emailSettings = new EmailSettings(); $emailSettings->send($this->_user, Yii::t('ciims.email', 'Activate Your Account'), 'base.themes.' . Cii::getConfig('theme', 'default') . '.views.email.register', array('user' => $this->_user, 'hash' => $meta->value), true, true); } return true; } return false; }
/** * Lets us know if the user likes a given content post or not * @param int $id The id of the content we want to know about * @return bool Whether or not the user likes the post */ public function likesPost($id = NULL) { if ($id === NULL) { return false; } $likes = UserMetadata::model()->findByAttributes(array('user_id' => $this->id, 'key' => 'likes')); if ($likes === NULL) { return false; } $likesArray = json_decode($likes->value, true); if (in_array($id, array_values($likesArray))) { return true; } return false; }
/** * Provides functionality for "liking and un-liking" a post * @param int $id The Content ID */ public function actionLike($id = NULL) { $this->layout = false; header('Content-type: application/json'); // Load the content $content = ContentMetadata::model()->findByAttributes(array('content_id' => $id, 'key' => 'likes')); if ($content === NULL) { $content = new ContentMetadata(); $content->content_id = $id; $content->key = 'likes'; $content->value = 0; } if ($id === NULL || $content === NULL) { echo CJavaScript::jsonEncode(array('status' => 'error', 'message' => Yii::t('ciims.controllers.Content', 'Unable to access post'))); return Yii::app()->end(); } // Load the user likes, create one if it does not exist $user = UserMetadata::model()->findByAttributes(array('user_id' => Yii::app()->user->id, 'key' => 'likes')); if ($user === NULL) { $user = new UserMetadata(); $user->user_id = Yii::app()->user->id; $user->key = 'likes'; $user->value = json_encode(array()); } $type = "inc"; $likes = json_decode($user->value, true); if (in_array($id, array_values($likes))) { $type = "dec"; $content->value -= 1; if ($content->value <= 0) { $content->value = 0; } $element = array_search($id, $likes); unset($likes[$element]); } else { $content->value += 1; array_push($likes, $id); } $user->value = json_encode($likes); if (!$user->save()) { echo CJavaScript::jsonEncode(array('status' => 'error', 'message' => Yii::t('ciims.controllers.Content', 'Unable to save user like'))); return Yii::app()->end(); } if (!$content->save()) { echo CJavaScript::jsonEncode(array('status' => 'error', 'message' => Yii::t('ciims.controllers.Content', 'Unable to save like'))); return Yii::app()->end(); } echo CJavaScript::jsonEncode(array('status' => 'success', 'type' => $type, 'message' => Yii::t('ciims.controllers.Content', 'Liked saved'))); return Yii::app()->end(); }
/** * Enables users who have recieved an invitation to setup a new account * @param string $id The activation id the of the user that we want to activate */ public function actionAcceptInvite($id = NULL) { $this->layout = '//layouts/main'; $this->setPageTitle(Yii::t('ciims.controllers.Site', '{{app_name}} | {{label}}', array('{{app_name}}' => Cii::getConfig('name', Yii::app()->name), '{{label}}' => Yii::t('ciims.controllers.Site', 'Accept Invitation')))); if ($id === NULL) { throw new CHttpException(400, Yii::t('ciims.controllers.Site', 'There was an error fulfilling your request.')); } // Make sure we have a user first $meta = UserMetadata::model()->findByAttributes(array('key' => 'invitationKey', 'value' => $id)); if ($meta === NULL) { throw new CHttpException(400, Yii::t('ciims.controllers.Site', 'There was an error fulfilling your request.')); } $model = new InviteForm(); $model->email = Users::model()->findByPk($meta->user_id)->email; if (Cii::get($_POST, 'InviteForm', NULL) !== NULL) { $model->attributes = Cii::get($_POST, 'InviteForm', NULL); $model->id = $meta->user_id; if ($model->acceptInvite()) { $meta->delete(); return $this->render('invitesuccess'); } } $this->render('acceptinvite', array('model' => $model)); }
/** * Retrieves a card by a given ID * @param string $id * @return [type] [description] */ public function actionCard($id = NULL) { $meta = UserMetadata::model()->findByAttributes(array('user_id' => Yii::app()->user->id, 'key' => 'dashboard')); if ($meta == NULL) { return true; } $uids = json_decode($meta->value, true); if (in_array($id, $uids)) { return $this->getCardById($id)->render(); } throw new CHttpException(400, Yii::t('Dashboard.main', 'You do not have permission to access this card')); }
/** * Enables users who have recieved an invitation to setup a new account * @param string $id The activation id the of the user that we want to activate */ public function actionAcceptInvite($id = NULL) { $this->layout = "main"; if ($id == NULL) { throw new CHttpException(400, Yii::t('ciims.controllers.Site', 'There was an error fulfilling your request.')); } // Make sure we have a user first $meta = UserMetadata::model()->findByAttributes(array('key' => 'activationKey', 'value' => $id)); if ($meta == NULL) { throw new CHttpException(400, Yii::t('ciims.controllers.Site', 'There was an error fulfilling your request.')); } $model = new InviteModel(); $model->email = Users::model()->findByPk($meta->user_id)->email; if (Cii::get($_POST, 'InviteModel', NULL) != NULL) { $model->attributes = Cii::get($_POST, 'InviteModel', NULL); if ($model->save($meta->user_id)) { $meta->delete(); return $this->render('invitesuccess'); } } $this->render('acceptinvite', array('model' => $model)); }
/** * BeforeAction method * The events defined here occur before every controller action that extends CiiController occurs. * This method will run the following tasks: * - Set the language for i18n * - Apply the correct theme * @param CAction $action The details of the action we want to run * @return CController::beforeAction($action) */ public function beforeAction($action) { try { if (Yii::app()->params['NewRelicAppName'] !== null) { $name = Yii::app()->params['NewRelicAppName']; } else { $name = Cii::getConfig('name', Yii::app()->name); } @Yii::app()->newRelic->setAppName($name); @Yii::app()->newRelic->setTransactionName($this->id, $action->id); } catch (Exception $e) { } // De-authenticate pre-existing sessions if (!Yii::app()->user->isGuest) { $apiKey = UserMetadata::model()->getPrototype('UserMetadata', array('user_id' => Yii::app()->user->id, 'key' => 'api_key'), array('value' => NULL)); if ($apiKey == NULL || !empty($apiKey->value)) { $activeSessionId = Yii::app()->cache->get($apiKey->value); if ($activeSessionId !== session_id()) { Yii::app()->cache->delete(Yii::app()->user->apiKey); Yii::app()->user->logout(); } } } // Sets the application language Cii::setApplicationLanguage(); // Sets the global theme for CiiMS $this->getTheme(); return parent::beforeAction($action); }
/** * Generates a new change key * @return boolean */ public function setNewEmailChangeKey() { $metadata = UserMetadata::model()->findByAttributes(array('user_id' => $this->_user->id, 'key' => 'newEmailAddressChangeKey')); if ($metadata == NULL) { $metadata = new UserMetadata(); $metadata->attributes = array('user_id' => $this->_user->id, 'key' => 'newEmailAddressChangeKey'); } // Generate a new key $metadata->value = Cii::generateSafeHash(); // Save the record if ($metadata->save()) { return $metadata->value; } throw new CHttpException(500, Yii::t('ciims.ProfileForm', 'Unable to save change key')); }
/** * Internal API endpoint for inviting new users to join the site * **/ public function actionCreate() { $validator = new CEmailValidator(); if (!$validator->validateValue(Cii::get($_POST, 'email', NULL))) { throw new CHttpException(400, Yii::t('Dashboard.main', 'The email address you provided is invalid.')); } if (Users::model()->countByAttributes(array('email' => Cii::get($_POST, 'email', NULL)))) { throw new CHttpException(400, Yii::t('Dashboard.main', 'A user with that email address already exists.')); } $user = new Users(); $user->attributes = array('status' => Users::PENDING_INVITATION, 'email' => Cii::get($_POST, 'email', NULL), 'user_role' => 5, 'about' => '', 'password' => '', 'displayName' => '', 'firstName' => '', 'lastName' => ''); $user->created = new CDbExpression('UTC_TIMESTAMP()'); $user->updated = new CDbExpression('UTC_TIMESTAMP()'); // Save the user, and ignore all validation if ($user->save(false)) { $hash = mb_strimwidth(hash("sha256", md5(time() . md5(hash("sha512", time())))), 0, 16); $meta = new UserMetadata(); $meta->user_id = $user->id; $meta->key = 'activationKey'; $meta->value = $hash; $meta->save(); // Send an invitation email $this->sendEmail($user, Yii::t('Dashboard.email', "You've Been Invited To Join a Blog!"), '/email/invite', array('user' => $user, 'hash' => $hash), true, true); // End the request return $this->renderPartial('/users/userList', array('data' => $user)); } throw new CHttpException(400, Yii::t('Dashboard.main', 'An unexpected error occured fulfilling your request.')); }
/** * Main mehod to handle login attempts. If the user passes authentication with their * chosen provider then it displays a form for them to choose their username and email. * The email address they choose is *not* verified. * * @throws Exception if a provider isn't supplied, or it has non-alpha characters */ private function hybridAuth($provider = NULL) { if ($provider == NULL) { throw new CException(Yii::t('Hybridauth.main', "You haven't supplied a provider")); } if (!function_exists('password_hash')) { require_once YiiBase::getPathOfAlias('ext.bcrypt.bcrypt') . '.php'; } $identity = new RemoteUserIdentity(); if ($identity->authenticate($provider)) { // If we found a user and authenticated them, bind this data to the user if it does not already exist $user = UserMetadata::model()->findByAttributes(array('key' => $provider . 'Provider', 'value' => $identity->userData['id'])); if ($user === NULL) { $user = new UserMetadata(); $user->user_id = Users::model()->findByAttributes(array('email' => $identity->userData['email']))->id; $user->key = $provider . 'Provider'; $user->value = $identity->userData['id']; $user->save(); } $user = Users::model()->findByPk($user->user_id); // Log the user in with just their email address $model = new LoginForm(true); // CiiMS 1.7 provided authentication schemes against md5 hashes. If we have any users in the system who still have md5 hashes // as their password, allow authentication, but immediatly upgrade their password to something more secure. $model->attributes = array('username' => isset($user->email) ? $user->email : $identity->userData['email'], 'password' => md5('PUBUSER')); // validate user input and redirect to the previous page if valid if ($model->validate() && $model->login()) { // Upgradee the user's password to bcrypt so they don't stick out in database dumps if ($user->password == md5('PUBUSER')) { $user->password = password_hash($identity->userData['email'], PASSWORD_BCRYPT, array('cost' => 13)); $user->save(); } $this->redirect(Yii::app()->user->returnUrl); } // If the prevvious authentication failed, then the user has been upgraded, and we should attempt to use the bcrypt hash isntead of the md5 one $model->attributes = array('username' => isset($user->email) ? $user->email : $identity->userData['email'], 'password' => password_hash($identity->userData['email'], PASSWORD_BCRYPT, array('cost' => 13))); // validate user input and redirect to the previous page if valid if ($model->validate() && $model->login()) { $this->redirect(Yii::app()->user->returnUrl); } throw new CException(Yii::t('Hybridauth.main', 'Unable to bind to local user')); } else { if ($identity->errorCode == RemoteUserIdentity::ERROR_USERNAME_INVALID) { // If the user authenticatd against the remote network, but we didn't find them locally // Create a local account, and bind this information to it. $user = new Users(); $user->attributes = array('email' => $identity->userData['email'], 'password' => password_hash($identity->userData['email'], PASSWORD_BCRYPT, array('cost' => 13)), 'firstName' => Cii::get($identity->userData, 'firstName', 'UNKNOWN'), 'lastName' => Cii::get($identity->userData, 'lastName', 'UNKNOWN'), 'displayName' => $provider == 'twitter' ? $identity->userData['firstName'] : $identity->userData['displayName'], 'user_role' => 1, 'status' => 1); $user->save(); $meta = new UserMetadata(); $meta->user_id = $user->id; $meta->key = $provider . 'Provider'; $meta->value = $identity->userData['id']; $meta->save(); // Log the user in with just their email address $model = new LoginForm(true); $model->attributes = array('username' => $identity->userData['email'], 'password' => password_hash($identity->userData['email'], PASSWORD_BCRYPT, array('cost' => 13))); // validate user input and redirect to the previous page if valid if ($model->validate() && $model->login()) { $this->redirect(Yii::app()->user->returnUrl); } throw new CException(Yii::t('Hybridauth.main', 'Unable to bind new user locally')); } else { // Panic? throw new CException(Yii::t('Hybridauth.main', 'We were able to authenticate you against the remote network, but could not sign you in locally.')); } } }
/** * Provides functionality to create a new user. This method will create a new user if the user does not already exist. * And then it will send an email invitation to the user so that they can join the blog. * @return array */ private function createUser() { $validator = new CEmailValidator(); if (!$validator->validateValue(Cii::get($_POST, 'email', NULL))) { throw new CHttpException(400, Yii::t('Api.user', 'The email address you provided is invalid.')); } if (Users::model()->countByAttributes(array('email' => Cii::get($_POST, 'email', NULL)))) { throw new CHttpException(400, Yii::t('Api.user', 'A user with that email address already exists.')); } // Passowrds cannot be set through the API unset($_POST['password']); // Relational data cannot be set through this API unset($_POST['comments']); unset($_POST['content']); unset($_POST['tags']); unset($_POST['metadata']); unset($_POST['role']); $user = new Users(); $user->attributes = array('status' => Users::PENDING_INVITATION, 'email' => Cii::get($_POST, 'email', NULL), 'user_role' => 1, 'about' => '', 'password' => '', 'displayName' => '', 'firstName' => '', 'lastName' => ''); $user->attributes = $_POST; $user->created = new CDbExpression('UTC_TIMESTAMP()'); $user->updated = new CDbExpression('UTC_TIMESTAMP()'); // Save the user, and ignore all validation if ($user->save(false)) { $hash = mb_strimwidth(hash("sha256", md5(time() . md5(hash("sha512", time())))), 0, 16); $meta = new UserMetadata(); $meta->user_id = $user->id; $meta->key = 'activationKey'; $meta->value = $hash; $meta->save(); // Send an invitation email $this->sendEmail($user, Yii::t('Api.user', "You've Been Invited To Join a Blog!"), 'application.modules.dashboard.views.email.invite', array('user' => $user, 'hash' => $hash), true, true); // End the request return $user->getAPIAttributes(array('password', 'activation_key')); } throw new CHttpException(400, Yii::t('Api.user', 'An unexpected error occured fulfilling your request.')); }
/** * Helper method to get the usermetadata object rather than calling getPrototype everywhere * @param string $key * @param mixed $value * @return UserMetadata prototype object */ public function getMetadataObject($key, $value = NULL) { return UserMetadata::model()->getPrototype('UserMetadata', array('user_id' => $this->id, 'key' => $key), array('user_id' => $this->id, 'key' => $key, 'value' => $value)); }
/** * Generates a new API key for this application * @return string */ protected function generateApiKey() { // Load the hashing factory $factory = new CryptLib\Random\Factory(); $meta = UserMetadata::model()->getPrototype('UserMetadata', array('user_id' => $this->getUser()->id, 'key' => 'api_key' . $this->app_name), array('user_id' => $this->getUser()->id, 'key' => 'api_key' . $this->app_name)); $meta->value = $factory->getLowStrengthGenerator()->generateString(16); if ($meta->save()) { return $meta->value; } throw new CHttpException(500, Yii::t('ciims.models.LoginForm', 'Unable to create API key, please try again.')); }
/** * * @param unknown $token */ public function actionEmail($token) { $success = false; $token_validity = UserMetadata::model()->findByAttributes(array('key' => User::METADATA_KEY_EMAIL_CHANGE_TOKEN, 'value' => $token)); if (isset($token_validity)) { $newEmail = UserMetadata::model()->findByAttributes(array('user_id' => $token_validity->user_id, 'key' => User::METADATA_KEY_EMAIL_CHANGE_NEW_ADDRESS)); if (isset($newEmail)) { $user = User::model()->findByAttributes(array('id' => $newEmail->user_id)); if (isset($user)) { $user->email = $newEmail->value; if ($user->save()) { $newEmail->delete(); $token_validity->delete(); $success = true; } } } } $this->render('email', array('success' => $success)); }