function create($name) { $this->user->setName($name); $this->user->set('role', 'user'); $this->user->set('email', $name . '@service.com'); $this->user->save(); return true; }
function user_model_test($delete) { $user = new UserModel("Not", "Here", "*****@*****.**", "password", date("Y-m-d H:i:s")); $user->save(); $user->print_fields(); $user->set("failed_login_attempts", 3); $user->set("first_name", "User"); $user->set("last_name", "McUsage"); $user->save(); $user->print_fields(); if ($delete) { $user->delete(); } $um = UserModel::find(UserModel::first()->id); $um->print_fields(); $um = UserModel::find(UserModel::last()->id); $um->print_fields(); UserModel::find(999); }
/** * 修改用户信息[密码] * PUT /user/1 * @method PUT_infoAction * @param integer $id [description] * @author NewFuture */ public function PUT_infoAction($id = 0) { $id = $this->auth($id); $response['status'] = 0; if (!Input::put('password', $password, 'isMd5')) { $response['info'] = '新的密码格式不对'; } elseif (!Input::put('old', $old_pwd, 'isMd5')) { $response['info'] = '请输入原密码'; } else { /*数据库中读取用户数据*/ $user = UserModel::field('password,number')->find($id); $number = $user->number; if (!$user || Encrypt::encryptPwd($old_pwd, $number) != $user['password']) { $response['info'] = '原密码错误'; } elseif (UserModel::set('password', Encrypt::encryptPwd($password, $number))->save($id) >= 0) { $response['info'] = '修改成功'; $response['status'] = 1; } else { $response['info'] = '修改失败'; } } $this->response = $response; }
public function registerJson() { $user = new UserModel(); $returnto = Ajde::app()->getRequest()->getPostParam('returnto', false); $username = Ajde::app()->getRequest()->getPostParam($user->usernameField); $password = Ajde::app()->getRequest()->getPostParam('password'); $passwordCheck = Ajde::app()->getRequest()->getPostParam('passwordCheck'); $email = Ajde::app()->getRequest()->getPostParam('email', false); $fullname = Ajde::app()->getRequest()->getPostParam('fullname', false); $return = array(false); $shadowUser = new UserModel(); if (empty($username) || empty($password)) { $return = array('success' => false, 'message' => __("Please provide " . $user->usernameField . " and password")); } else { if ($shadowUser->loadByField($shadowUser->usernameField, $username)) { $return = array('success' => false, 'message' => __(ucfirst($user->usernameField) . " already exist")); } else { if ($password !== $passwordCheck) { $return = array('success' => false, 'message' => __("Passwords do not match")); } else { if (empty($email)) { $return = array('success' => false, 'message' => __("Please provide an e-mail address")); } else { if (Ajde_Component_String::validEmail($email) === false) { $return = array('success' => false, 'message' => __('Please provide a valid e-mail address')); } else { if ($shadowUser->loadByField('email', $email)) { $return = array('success' => false, 'message' => __("A user with this e-mail address already exist")); } else { if (empty($fullname)) { $return = array('success' => false, 'message' => __("Please provide a full name")); } else { $user->set('email', $email); $user->set('fullname', $fullname); if ($user->add($username, $password)) { $user->login(); Ajde_Session_Flash::alert(sprintf(__('Welcome %s, you are now logged in.'), $fullname)); $return = array('success' => true, 'returnto' => $returnto); } else { $return = array('success' => false, 'message' => __("Something went wrong")); } } } } } } } } return $return; }
$sql = new \yangzie\YZE_SQL(); $sql->from("\\yangzie\\UserModel", "u")->where("u", "name", \yangzie\YZE_SQL::EQ, "aaaaa"); $user2->set("email", "12345"); $user2->save(YZE_SQL::INSERT_NOT_EXIST, $sql); echo "\r\n"; echo $user2->get_key() && $user2->Get("email") == "1234" ? "INSERT_NOT_EXIST true" : "INSERT_NOT_EXIST false"; $user2->remove(); //测试不存在时添加,存在更新 $user3 = new UserModel(); $user3->set("name", "aa"); $user3->set("register_time", "2015-12-17 17:50:30"); $sql = new \yangzie\YZE_SQL(); $sql->from("\\yangzie\\UserModel", "u")->where("u", "name", \yangzie\YZE_SQL::EQ, "aaaaa"); $user3->set("email", "123456"); $user3->save(YZE_SQL::INSERT_NOT_EXIST_OR_UPDATE, $sql); echo "\r\n"; echo $user3->get_key() && $user3->Get("email") == "123456" ? "INSERT_NOT_EXIST_OR_UPDATE true" : "INSERT_NOT_EXIST_OR_UPDATE false"; //测试不存在时添加,存在更新 $user3 = new UserModel(); $user3->set("name", "aa"); $user3->set("register_time", "2015-12-17 17:50:30"); $sql = new \yangzie\YZE_SQL(); $sql->from("\\yangzie\\UserModel", "u")->where("u", "name", \yangzie\YZE_SQL::EQ, "aaaaaaaa"); $user3->set("email", "1234567"); $user3->save(YZE_SQL::INSERT_NOT_EXIST_OR_UPDATE, $sql); echo "\r\n"; echo $user3->get_key() && $user3->Get("email") == "1234567" ? "INSERT_NOT_EXIST_OR_UPDATE true" : "INSERT_NOT_EXIST_OR_UPDATE false"; //删除 $user->remove(); echo "\r\n"; echo $user->get_key() > 0 ? "remove false" : "remove true";
/** * This is the handler the standard registration login form. * * @param Form $form * * @return bool|string */ public static function RegisterHandler(Form $form) { $p1 = $form->getElement('pass'); $p2 = $form->getElement('pass2'); /////// VALIDATION \\\\\\\\ // All other validation can be done from the model. // All set calls will throw a ModelValidationException if the validation fails. try{ $user = new \UserModel(); $password = null; $user->set('email', $form->getElement('email')->get('value')); $user->enableAuthDriver('datastore'); /** @var \Core\User\AuthDrivers\datastore $auth */ $auth = $user->getAuthDriver('datastore'); if($form->getElement('pwgen') && $form->getElementValue('pwgen')){ $password = $auth->pwgen(); $auth->setPassword($password); $user->set('password_raw', $password); } // Users can be created with no password. They will be prompted to set it on first login. if($p1->get('value') || $p2->get('value')){ if($p1->get('value') != $p2->get('value')){ $p1->setError('t:MESSAGE_ERROR_USER_REGISTER_PASSWORD_MISMATCH'); $p2->set('value', ''); return false; } $passresult = $auth->setPassword($p1->get('value')); if($passresult !== true){ $p1->setError($passresult === false ? 'Invalid password' : $passresult); $p2->set('value', ''); return false; } // Do not set the password_raw value here as we do not wish for it to be sent to the user via email. } } catch(\ModelValidationException $e){ // Make a note of this! \SystemLogModel::LogSecurityEvent('/user/register', $e->getMessage()); \Core\set_message($e->getMessage(), 'error'); return false; } catch(\Exception $e){ // Make a note of this! \SystemLogModel::LogSecurityEvent('/user/register', $e->getMessage()); \Core\set_message(DEVELOPMENT_MODE ? $e->getMessage() : 'An unknown error occurred', 'error'); return false; } // Otherwise, w00t! Record this user into a nonce and forward to step 2 of registration. $nonce = NonceModel::Generate( '20 minutes', null, [ 'user' => $user, 'redirect' => $form->getElementValue('redirect'), ] ); return '/user/register2/' . $nonce; }
/** * View to accept and process the FB login post. * * This will redirect to the registration page if the user doesn't exist, * will throw an error and display a link to enable FB if it's not enabled already, * or will simply log the user in via Facebook and sync his/her settings. */ public function login() { $view = $this->getView(); $request = $this->getPageRequest(); $view->ssl = true; $view->record = false; $auths = \Core\User\Helper::GetEnabledAuthDrivers(); if (!isset($auths['facebook'])) { // Facebook isn't enabled, simply redirect to the home page. \Core\redirect('/'); } if (!FACEBOOK_APP_ID) { \Core\redirect('/'); } if (!FACEBOOK_APP_SECRET) { \Core\redirect('/'); } if (!$request->isPost()) { return View::ERROR_BADREQUEST; } $facebook = new Facebook(['appId' => FACEBOOK_APP_ID, 'secret' => FACEBOOK_APP_SECRET]); // Did the user submit the facebook login request? if (isset($_POST['login-method']) && $_POST['login-method'] == 'facebook' && $_POST['access-token']) { try { $facebook->setAccessToken($_POST['access-token']); /** @var int $fbid The user ID from facebook */ $fbid = $facebook->getUser(); /** @var array $user_profile The array of user data from Facebook */ $user_profile = $facebook->api('/me'); } catch (Exception $e) { \Core\set_message($e->getMessage(), 'error'); \Core\go_back(); return null; } /** @var \UserModel|null $user */ $user = UserModel::Find(['email' => $user_profile['email']], 1); if (!$user) { if (ConfigHandler::Get('/user/register/allowpublic')) { // If public registration is enabled, then redirect the user to the registration page to complete their registration. $user = new UserModel(); $user->set('email', $user_profile['email']); $user->enableAuthDriver('facebook'); $user->disableAuthDriver('datastore'); /** @var \Facebook\UserAuth $auth */ $auth = $user->getAuthDriver('facebook'); $auth->syncUser($_POST['access-token']); // Otherwise, w00t! Record this user into a nonce and forward to step 2 of registration. $nonce = NonceModel::Generate('20 minutes', null, ['user' => $user, 'redirect' => $_POST['redirect']]); \Core\redirect('/user/register2/' . $nonce); } else { // Log this as a login attempt! $logmsg = 'Failed Login (Facebook). Email not registered' . "\n" . 'Email: ' . $user_profile['email'] . "\n"; \SystemLogModel::LogSecurityEvent('/user/login', $logmsg); \Core\set_message('Your Facebook email (' . $user_profile['email'] . ') does not appear to be registered on this site.', 'error'); \Core\go_back(); return null; } } elseif (!$user->get('active')) { // The model provides a quick cut-off for active/inactive users. // This is the control managed with in the admin. $logmsg = 'Failed Login. User tried to login before account activation' . "\n" . 'User: '******'email') . "\n"; \SystemLogModel::LogSecurityEvent('/user/login', $logmsg, null, $user->get('id')); \Core\set_message('Your account is not active yet.', 'error'); \Core\go_back(); return null; } try { /** @var \Facebook\UserAuth $auth */ $auth = $user->getAuthDriver('facebook'); } catch (Exception $e) { \Core\set_message('Your account does not have Facebook logins enabled! <a href="' . \Core\resolve_link('/facebook/enable') . '">Do you want to enable Facebook?</a>', 'error'); \Core\go_back(); return null; } if (!$user->isActive()) { \Core\set_message('Your account is not active!', 'error'); \Core\go_back(); return null; } // Well yay the user is available and authencation driver is ready! $auth->syncUser($_POST['access-token']); if ($_POST['redirect']) { // The page was set via client-side javascript on the login page. // This is the most reliable option. $url = $_POST['redirect']; } elseif (REL_REQUEST_PATH == '/facebook/login') { // If the user came from the registration page, get the page before that. $url = '/'; } else { // else the registration link is now on the same page as the 403 handler. $url = REL_REQUEST_PATH; } // Well, record this too! \SystemLogModel::LogSecurityEvent('/user/login', 'Login successful (via Facebook)', null, $user->get('id')); // yay... $user->set('last_login', \CoreDateTime::Now('U', \Time::TIMEZONE_GMT)); $user->save(); \Core\Session::SetUser($user); // Allow an external script to override the redirecting URL. $overrideurl = \HookHandler::DispatchHook('/user/postlogin/getredirecturl'); if ($overrideurl) { $url = $overrideurl; } \Core\redirect($url); } else { \Core\go_back(); } }
public function registerJson() { $user = new UserModel(); $returnto = Ajde::app()->getRequest()->getPostParam('returnto', false); $username = Ajde::app()->getRequest()->getPostParam($user->usernameField); $password = Ajde::app()->getRequest()->getPostParam('password', ''); $passwordCheck = Ajde::app()->getRequest()->getPostParam('passwordCheck', ''); $providername = Ajde::app()->getRequest()->getPostParam('provider', false); $email = Ajde::app()->getRequest()->getPostParam('email', false); $fullname = Ajde::app()->getRequest()->getPostParam('fullname', false); $return = [false]; $shadowUser = new UserModel(); $provider = false; if ($providername) { $sso = config('user.sso.providers'); if (!in_array($providername, $sso)) { Ajde_Http_Response::redirectNotFound(); } $classname = 'Ajde_User_Sso_' . ucfirst($providername); /* @var $provider Ajde_User_SSO_Interface */ $provider = new $classname(); } if (empty($username)) { $return = ['success' => false, 'message' => trans('Please provide a ' . $user->usernameField . '')]; } else { if (!$provider && empty($password)) { $return = ['success' => false, 'message' => trans('Please provide a password')]; } else { if ($shadowUser->loadByField($shadowUser->usernameField, $username)) { $return = ['success' => false, 'message' => trans(ucfirst($user->usernameField) . ' already exist')]; } else { if (!$provider && $password !== $passwordCheck) { $return = ['success' => false, 'message' => trans('Passwords do not match')]; } else { if (empty($email)) { $return = ['success' => false, 'message' => trans('Please provide an e-mail address')]; } else { if (Ajde_Component_String::validEmail($email) === false) { $return = ['success' => false, 'message' => trans('Please provide a valid e-mail address')]; } else { if ($shadowUser->loadByField('email', $email)) { $return = ['success' => false, 'message' => trans('A user with this e-mail address already exist')]; } else { if (empty($fullname)) { $return = ['success' => false, 'message' => trans('Please provide a full name')]; } else { if ($provider && !$provider->getData()) { $return = ['success' => false, 'message' => trans('Something went wrong with fetching your credentials from an external service')]; } else { $user->set('email', $email); $user->set('fullname', $fullname); if ($user->add($username, $password)) { if ($provider) { $sso = new SsoModel(); $sso->populate(['user' => $user->getPK(), 'provider' => $providername, 'username' => $provider->getUsernameSuggestion(), 'avatar' => $provider->getAvatarSuggestion(), 'profile' => $provider->getProfileSuggestion(), 'uid' => $provider->getUidHash(), 'data' => serialize($provider->getData())]); $sso->insert(); $user->copyAvatarFromSso($sso); } $user->login(); $user->storeCookie($this->includeDomain); Ajde_Session_Flash::alert(sprintf(trans('Welcome %s, you are now logged in'), $fullname)); $return = ['success' => true, 'returnto' => $returnto]; } else { $return = ['success' => false, 'message' => trans('Something went wrong')]; } } } } } } } } } } return $return; }
/** * Import the given data into the destination Model. * * @param array $data Indexed array of records to import/merge from the external source. * @param array $options Any options required for the import, such as merge, key, etc. * @param boolean $output_realtime Set to true to output the log in real time as the import happens. * * @throws Exception * * @return \Core\ModelImportLogger */ public static function Import($data, $options, $output_realtime = false) { $log = new \Core\ModelImportLogger('User Importer', $output_realtime); $merge = isset($options['merge']) ? $options['merge'] : true; $pk = isset($options['key']) ? $options['key'] : null; if(!$pk) { throw new Exception( 'Import requires a "key" field on options containing the primary key to compare against locally.' ); } // Load in members from the group // Set the default group on new accounts, if a default is set. $defaultgroups = \UserGroupModel::Find(["default = 1"]); $groups = []; $gnames = []; foreach($defaultgroups as $g) { /** @var \UserGroupModel $g */ $groups[] = $g->get('id'); $gnames[] = $g->get('name'); } if(sizeof($groups)) { $log->log('Found ' . sizeof($groups) . ' default groups for new users: ' . implode(', ', $gnames)); } else { $log->log('No groups set as default, new users will not belong to any groups.'); } $log->log('Starting ' . ($merge ? '*MERGE*' : '*skipping*' ) . ' import of ' . sizeof($data) . ' users'); foreach($data as $dat) { if(isset($dat[$pk])){ // Only check the information if the primary key is set on this record. if($pk == 'email' || $pk == 'id') { // These are the only two fields on the User object itself. $user = UserModel::Find([$pk . ' = ' . $dat[ $pk ]], 1); } else { $uucm = UserUserConfigModel::Find(['key = ' . $pk, 'value = ' . $dat[ $pk ]], 1); if($uucm) { $user = $uucm->getLink('UserModel'); } else { // Try the lookup from the email address instead. // This will force accounts that exist to be synced up correctly. // The only caveat to this is that users will not be updated with the foreign key if merge is disabled. $user = UserModel::Find(['email = ' . $dat['email']], 1); } } } else{ $user = null; } $status_type = $user ? 'Updated' : 'Created'; if($user && !$merge) { $log->duplicate('Skipped user ' . $user->getLabel() . ', already exists and merge not requested'); // Skip to the next record. continue; } if(!$user) { // All incoming users must have an email address! if(!isset($dat['email'])) { $log->error('Unable to import user without an email address!'); // Skip to the next record. continue; } // Meta fields that may or may not be present, but should be for reporting purposes. if(!isset($dat['registration_ip'])) { $dat['registration_ip'] = REMOTE_IP; } if(!isset($dat['registration_source'])) { $dat['registration_source'] = \Core\user()->exists() ? 'admin' : 'self'; } if(!isset($dat['registration_invitee'])) { $dat['registration_invitee'] = \Core\user()->get('id'); } // New user! $user = new UserModel(); } // No else needed, else is there IS a valid $user object and it's setup ready to go. // Handle all the properties for this user! foreach($dat as $key => $val){ if($key == 'avatar' && strpos($val, '://') !== false){ // Sync the user avatar. $log->actionStart('Downloading ' . $dat['avatar']); $f = new \Core\Filestore\Backends\FileRemote($dat['avatar']); $dest = \Core\Filestore\Factory::File('public/user/avatar/' . $f->getBaseFilename()); if($dest->identicalTo($f)) { $log->actionSkipped(); } else { $f->copyTo($dest); $user->set('avatar', 'public/user/avatar/' . $dest->getBaseFilename()); $log->actionSuccess(); } } elseif($key == 'profiles' && is_array($val)) { $new_profiles = $val; // Pull the current profiles from the account $profiles = $user->get('external_profiles'); if($profiles && is_array($profiles)) { $current_flat = []; foreach($profiles as $current_profile) { $current_flat[] = $current_profile['url']; } // Merge in any *actual* new profile foreach($new_profiles as $new_profile) { if(!in_array($new_profile['url'], $current_flat)) { $profiles[] = $new_profile; } } unset($new_profile, $new_profiles, $current_flat, $current_profile); } else { $profiles = $new_profiles; unset($new_profiles); } $user->set('external_profiles', $profiles); } elseif($key == 'backend'){ // Was a backend requested? // This gets merged instead of replaced entirely. $user->enableAuthDriver($val); } elseif($key == 'groups'){ $user->setGroups($val); } else{ // Default Behaviour, // save the key into whatever field it was set to go to. $user->set($key, $val); } } try { // Set the default groups loaded from the system. if(!$user->exists()){ $user->setGroups($groups); } $status = $user->save(); } catch(Exception $e) { $log->error($e->getMessage()); // Skip to the next. continue; } if($status) { $log->success($status_type . ' user ' . $user->getLabel() . ' successfully!'); } else { $log->skip('Skipped user ' . $user->getLabel() . ', no changes detected.'); } } $log->finalize(); return $log; }