function testUser() { $this->startCodeCoverage(); $user = new User(); $user->Id = "non_numeric"; if (!($user->SetPassword("blah") === false)) { $this->fail("User::SetPassword didn't return false for non-numeric user id"); return 1; } if (!($user->IsAdmin() === false)) { $this->fail("User::IsAdmin didn't return false for non-numeric user id"); return 1; } $user->Id = ""; $user->Email = ""; if (!($user->GetName() === false)) { $this->fail("User::GetName didn't return false when given no user id"); return 1; } if (!($user->IsAdmin() === false)) { $this->fail("User::Exists didn't return false for no user id and no email"); return 1; } $user->Email = "simpletest@localhost"; if ($user->Exists() === false) { $this->fail("User::Exists returned false even though user exists"); return 1; } $id = $user->GetIdFromEmail("simpletest@localhost"); if ($id === false) { $this->fail("User::GetIdFromEmail returned false for a valid user"); return 1; } $user->Id = $id; $user->Admin = "1"; $user->FirstName = "administrator"; $user->Institution = "Kitware Inc."; if ($user->Exists() != true) { $this->fail("User::Exists failed given a valid user id"); return 1; } $user->Password = md5("simpletest"); // Coverage for update save $user->Save(); // Coverage for SetPassword $user->SetPassword(md5("simpletest")); $this->stopCodeCoverage(); return 0; }
public function testUser() { $this->startCodeCoverage(); $user = new User(); $user->Id = 'non_numeric'; if (!($user->SetPassword('blah') === false)) { $this->fail("User::SetPassword didn't return false for non-numeric user id"); return 1; } if (!($user->IsAdmin() === false)) { $this->fail("User::IsAdmin didn't return false for non-numeric user id"); return 1; } $user->Id = ''; $user->Email = ''; if (!($user->GetName() === false)) { $this->fail("User::GetName didn't return false when given no user id"); return 1; } if (!($user->IsAdmin() === false)) { $this->fail("User::Exists didn't return false for no user id and no email"); return 1; } $user->Email = 'simpletest@localhost'; if ($user->Exists() === false) { $this->fail('User::Exists returned false even though user exists'); return 1; } $id = $user->GetIdFromEmail('simpletest@localhost'); if ($id === false) { $this->fail('User::GetIdFromEmail returned false for a valid user'); return 1; } $user->Id = $id; $user->Admin = '1'; $user->FirstName = 'administrator'; $user->Institution = 'Kitware Inc.'; if ($user->Exists() != true) { $this->fail('User::Exists failed given a valid user id'); return 1; } $user->Password = md5('simpletest'); // Coverage for update save $user->Save(); // Coverage for SetPassword $user->SetPassword(md5('simpletest')); $this->stopCodeCoverage(); return 0; }
public function saveUser($req) { $profileVar = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; $profileClass = ucfirst(SIGN_IN_ELEMENT_MAPPING_FIELD_NAME); if ($this->user->user_level == 'Admin') { $user = new User(); $user->Load("email = ?", array($req->email)); if ($user->email == $req->email) { return new IceResponse(IceResponse::ERROR, "User with same email already exists"); } $user->Load("username = ?", array($req->username)); if ($user->username == $req->username) { return new IceResponse(IceResponse::ERROR, "User with same username already exists"); } $user = new User(); $user->email = $req->email; $user->username = $req->username; $password = $this->generateRandomString(6); $user->password = md5($password); $user->profile = empty($req->profile) || $req->profile == "NULL" ? NULL : $req->profile; $user->user_level = $req->user_level; $user->last_login = date("Y-m-d H:i:s"); $user->last_update = date("Y-m-d H:i:s"); $user->created = date("Y-m-d H:i:s"); $profile = null; if (!empty($user->profile)) { $profile = $this->baseService->getElement($profileClass, $user->profile, null, true); } $ok = $user->Save(); if (!$ok) { LogManager::getInstance()->info($user->ErrorMsg() . "|" . json_encode($user)); return new IceResponse(IceResponse::ERROR, "Error occured while saving the user"); } $user->password = ""; $user = $this->baseService->cleanUpAdoDB($user); if (!empty($this->emailSender)) { $usersEmailSender = new UsersEmailSender($this->emailSender, $this); $usersEmailSender->sendWelcomeUserEmail($user, $password, $profile); } return new IceResponse(IceResponse::SUCCESS, $user); } return new IceResponse(IceResponse::ERROR, "Not Allowed"); }
public function saveUser($req) { if ($this->user->user_level == 'Admin') { $user = new User(); $user->Load("email = ?", array($req->email)); if ($user->email == $req->email) { return new IceResponse(IceResponse::ERROR, "User with same email already exists"); } $user->Load("username = ?", array($req->username)); if ($user->username == $req->username) { return new IceResponse(IceResponse::ERROR, "User with same username already exists"); } $user = new User(); $user->email = $req->email; $user->username = $req->username; $password = $this->generateRandomString(6); $user->password = md5($password); $user->employee = empty($req->employee) || $req->employee == "NULL" ? NULL : $req->employee; $user->user_level = $req->user_level; $user->last_login = date("Y-m-d H:i:s"); $user->last_update = date("Y-m-d H:i:s"); $user->created = date("Y-m-d H:i:s"); $employee = null; if (!empty($user->employee)) { $employee = $this->baseService->getElement('Employee', $user->employee, null, true); } $ok = $user->Save(); if (!$ok) { error_log($user->ErrorMsg() . "|" . json_encode($user)); return new IceResponse(IceResponse::ERROR, "Error occured while saving the user"); } $user->password = ""; $user = $this->baseService->cleanUpAdoDB($user); if (!empty($this->emailSender)) { $usersEmailSender = new UsersEmailSender($this->emailSender, $this); $usersEmailSender->sendWelcomeUserEmail($user, $password, $employee); } return new IceResponse(IceResponse::SUCCESS, $user); } return new IceResponse(IceResponse::ERROR, "Not Allowed"); }
protected function createNewUsers() { $profileVar = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; $profileClass = ucfirst(SIGN_IN_ELEMENT_MAPPING_FIELD_NAME); $user = new User(); $user->username = '******'; $user->email = '*****@*****.**'; $user->password = '******'; $user->user_level = 'Manager'; $user->Save(); $this->usersArray[$user->username] = $user; $user = new User(); $user->username = '******'; $user->email = '*****@*****.**'; $user->password = '******'; $user->user_level = 'Profile'; $user->Save(); $this->usersArray[$user->username] = $user; $user = new User(); $user->Load("username = ?", array('admin')); $this->usersArray[$user->username] = $user; }
public function testSetup() { // Create a project with GitHub credentials named CDash. global $configure; $settings = ['Name' => 'CDash', 'Description' => 'CDash', 'CvsUrl' => 'github.com/Kitware/CDash', 'CvsViewerType' => 'github', 'BugTrackerFileUrl' => 'http://public.kitware.com/Bug/view.php?id=', 'repositories' => [['url' => 'https://github.com/Kitware/CDash', 'branch' => 'master', 'username' => $configure['github_username'], 'password' => $configure['github_password']]]]; $this->ProjectId = $this->createProject($settings); // Create some users for the CDash project. $users_details = array(array('email' => '*****@*****.**', 'firstname' => 'Dan', 'lastname' => 'LaManna'), array('email' => '*****@*****.**', 'firstname' => 'Jamie', 'lastname' => 'Snape'), array('email' => '*****@*****.**', 'firstname' => 'Zack', 'lastname' => 'Galbreath')); $userproject = new UserProject(); $userproject->ProjectId = $this->ProjectId; foreach ($users_details as $user_details) { $user = new User(); $user->Email = $user_details['email']; $user->FirstName = $user_details['firstname']; $user->LastName = $user_details['lastname']; $user->Password = md5('12345'); $user->Institution = 'Kitware'; $user->Admin = 0; $user->Save(); $user->AddProject($userproject); $this->Users[] = $user; } }
$password_is_good = false; if ($CDASH_PASSWORD_COMPLEXITY_COUNT > 1) { $error_msg = "Your password must contain at least {$CDASH_PASSWORD_COMPLEXITY_COUNT} characters from {$CDASH_MINIMUM_PASSWORD_COMPLEXITY} of the following types: uppercase, lowercase, numbers, and symbols."; } else { $error_msg = "Your password must contain at least {$CDASH_MINIMUM_PASSWORD_COMPLEXITY} of the following: uppercase, lowercase, numbers, and symbols."; } } } if (!$password_is_good) { $xml .= "<error>{$error_msg}</error>"; } else { $user = new User(); $user->Id = $userid; $user->Fill(); $user->Password = $md5pass; if ($user->Save()) { $xml .= '<error>Your password has been updated.</error>'; unset($_SESSION['cdash']['redirect']); } else { $xml .= '<error>Cannot update password.</error>'; } add_last_sql_error('editUser.php'); } } $xml .= '<user>'; $user = pdo_query('SELECT * FROM ' . qid('user') . " WHERE id='{$userid}'"); $user_array = pdo_fetch_array($user); $xml .= add_XML_value('id', $userid); $xml .= add_XML_value('firstname', $user_array['firstname']); $xml .= add_XML_value('lastname', $user_array['lastname']); $xml .= add_XML_value('email', $user_array['email']);
/** endElement function */ public function endElement($parser, $name) { parent::endElement($parser, $name); global $CDASH_DELETE_OLD_SUBPROJECTS; if (!$this->ProjectNameMatches) { return; } if ($name == 'PROJECT') { foreach ($this->SubProjects as $subproject) { if ($CDASH_DELETE_OLD_SUBPROJECTS) { // Remove dependencies that do not exist anymore, // but only for those relationships where both sides // are present in $this->SubProjects. // $dependencyids = $subproject->GetDependencies(); $removeids = array_diff($dependencyids, $this->Dependencies[$subproject->GetId()]); foreach ($removeids as $removeid) { if (array_key_exists($removeid, $this->SubProjects)) { $subproject->RemoveDependency($removeid); } else { $dep = pdo_get_field_value("SELECT name FROM subproject WHERE id='{$removeid}'", 'name', "{$removeid}"); add_log("Not removing dependency {$dep}({$removeid}) from " . $subproject->GetName() . 'because it is not a SubProject element in this Project.xml file', 'ProjectHandler:endElement', LOG_WARNING, $this->projectid); } } } // Add dependencies that were queued up as we processed the DEPENDENCY // elements: // foreach ($this->Dependencies[$subproject->GetId()] as $addid) { if (array_key_exists($addid, $this->SubProjects)) { $subproject->AddDependency($addid); } else { add_log('impossible condition: should NEVER see this: unknown DEPENDENCY clause should prevent this case', 'ProjectHandler:endElement', LOG_WARNING, $this->projectid); } } } if ($CDASH_DELETE_OLD_SUBPROJECTS) { // Delete old subprojects that weren't included in this file. $previousSubProjectIds = $this->Project->GetSubProjects(); foreach ($previousSubProjectIds as $previousId) { $found = false; foreach ($this->SubProjects as $subproject) { if ($subproject->GetId() == $previousId) { $found = true; break; } } if (!$found) { $subProjectToRemove = new SubProject(); $subProjectToRemove->SetId($previousId); $subProjectToRemove->Delete(); add_log("Deleted " . $subProjectToRemove->GetName() . " because it was not mentioned in Project.xml", 'ProjectHandler:endElement', LOG_WARNING, $this->projectid); } } } } elseif ($name == 'SUBPROJECT') { // Insert the SubProject. $this->SubProject->Save(); // Insert the label. $Label = new Label(); $Label->Text = $this->SubProject->GetName(); $Label->Insert(); $this->SubProjects[$this->SubProject->GetId()] = $this->SubProject; // Handle dependencies here too. $this->Dependencies[$this->SubProject->GetId()] = array(); foreach ($this->CurrentDependencies as $dependencyid) { $added = false; if ($dependencyid !== false && is_numeric($dependencyid)) { if (array_key_exists($dependencyid, $this->SubProjects)) { $this->Dependencies[$this->SubProject->GetId()][] = $dependencyid; $added = true; } } if (!$added) { add_log('Project.xml DEPENDENCY of ' . $this->SubProject->GetName() . ' not mentioned earlier in file.', 'ProjectHandler:endElement', LOG_WARNING, $this->projectid); } } // Check if the user is in the database. $User = new User(); $posat = strpos($this->Email, '@'); if ($posat !== false) { $User->FirstName = substr($this->Email, 0, $posat); $User->LastName = substr($this->Email, $posat + 1); } else { $User->FirstName = $this->Email; $User->LastName = $this->Email; } $User->Email = $this->Email; $User->Password = md5($this->Email); $User->Admin = 0; $userid = $User->GetIdFromEmail($this->Email); if (!$userid) { $User->Save(); $userid = $User->Id; } // Insert into the UserProject $UserProject = new UserProject(); $UserProject->EmailType = 3; // any build $UserProject->EmailCategory = 54; // everything except warnings $UserProject->UserId = $userid; $UserProject->ProjectId = $this->projectid; $UserProject->Save(); // Insert the labels for this user $LabelEmail = new LabelEmail(); $LabelEmail->UserId = $userid; $LabelEmail->ProjectId = $this->projectid; $Label = new Label(); $Label->SetText($this->SubProject->GetName()); $labelid = $Label->GetIdFromText(); if (!empty($labelid)) { $LabelEmail->LabelId = $labelid; $LabelEmail->Insert(); } } }
static function AddUser($fields, $use_captcha = false) { $data = array(); $validator = new Validate(); $result = $validator->AddValue('username', $fields['username'])->AddPattern('username-unique')->AddValue('email', $fields['email'])->AddPattern('email-unique')->Check(); if (isset($fields['password'])) { $result = $validator->AddValue('password', $fields['password'])->AddPattern('password')->Check() && $result; } if (isset($fields['cpassword'])) { $result = $validator->AddValue('cpassword', $fields['cpassword'])->AddRule('match', $fields['password'])->Check() && $result; } if ($use_captcha) { $result = Validate::ValidCaptcha($fields['recaptcha_challenge_field'], $fields['recaptcha_response_field']) && $result; } if ($result) { $data['username'] = $fields['username']; $data['email'] = $fields['email']; $data['password'] = isset($fields['password']) ? Validate::Encrypt($fields['password']) : ''; $data['user_type'] = isset($fields['user_type']) && $fields['user_type'] == 'admin' ? 'admin' : 'user'; $data['activation_state'] = isset($fields['activation_state']) && $fields['activation_state'] == '1' ? '1' : '0'; $info = array('phone', 'about', 'location', 'fullname', 'gender', 'social_id', 'social_type', 'activation_key', 'avatar'); foreach ($info as $value) { $data[$value] = isset($fields[$value]) ? Validate::Escape($fields[$value]) : ''; } $new_user = new User($data); if ($new_user->Save()) { return $new_user; } else { Error::Set("database", "databaseinsert"); } } return false; }
public function recharge() { $curUser = $this->checkLogin('enekpani'); $user = new User($_POST['loginId']); //crediting account if (isset($_POST['creditaccount'])) { $errorMsg = ''; //validation if (trim($_POST['qnt']) == '' || $_POST['qnt'] < 1) { $errorMsg = 'You must specify the quantity and it must not be less than one'; } if ($errorMsg == '') { if ($_POST['transType'] == 'credit') { ////check if admin have enogh //if($curUser->Balance ) $user->Balance += $_POST['qnt']; $qnt = abs($_POST['qnt']); //$curUser->Balance -= $_POST['qnt']; } else { if ($user->Balance >= $_POST['qnt']) { $user->Balance -= $_POST['qnt']; $qnt = -abs($_POST['qnt']); //$curUser->Balance += $_POST['qnt']; } else { $errorMsg = $user->Name . ' do not have up to ' . $_POST['qnt'] . ' units'; } } if ($errorMsg == '') { $success = $this->deductAccount($qnt); if ($success) { //if($curUser->LoginId != $user->LoginId){ // $curUser->Save(); //} $user->Save(); $errorMsg = 'Transaction saved'; } else { $errorMsg = "Low master account balance"; } } } } $error_code = $errorMsg == 'Transaction saved' ? 0 : 1; header('Location: ' . URL . 'users/manage/' . $_POST['loginId'] . '?notification=' . $errorMsg . '&error_code=' . $error_code); exit; }
static function Reactivate($fields) { $validator = new Validate(); $result = $validator->AddValue('email', $fields['email'])->AddPattern('email')->Check(); if (Config::Get("validation.use_captcha")) { $result = Validate::ValidCaptcha($fields['recaptcha_challenge_field'], $fields['recaptcha_response_field']); } if ($result) { $user = new User(); $result = $user->Load(array('email' => $fields['email'])); if ($result) { if ($user->Get('activation_state') == '1') { Error::Set("email", "alreadyactivated"); } else { $key = md5(time() . $fields['email']); $user->Set("activation_key", $key); $user->Save(); $url = Config::Get("base_url") . "auth/activate.php?key=" . $key; $url = '<a href="' . $url . '">' . $url . '</a>'; Email::SendEmail($fields['email'], Config::Get("success.activation_subject"), Config::Get("success.activation_message") . $url); return true; } } else { Error::Set("email", "usernotfound"); } } return false; }
/** startElement function */ public function startElement($parser, $name, $attributes) { parent::startElement($parser, $name, $attributes); // Check that the project name matches if ($name == 'PROJECT') { if (get_project_id($attributes['NAME']) != $this->projectid) { add_log("Wrong project name: " . $attributes['NAME'], "ProjectHandler::startElement", LOG_ERR, $this->projectid); $this->ProjectNameMatches = false; } } if (!$this->ProjectNameMatches) { return; } if ($name == 'PROJECT') { $this->SubProjects = array(); $this->Dependencies = array(); } else { if ($name == 'SUBPROJECT') { $this->SubProject = new SubProject(); $this->SubProject->SetProjectId($this->projectid); $this->SubProject->SetName($attributes['NAME']); if (array_key_exists("GROUP", $attributes)) { $this->SubProject->SetGroup($attributes['GROUP']); } $this->SubProject->Save(); // Insert the label $Label = new Label(); $Label->Text = $this->SubProject->GetName(); $Label->Insert(); $this->SubProjects[$this->SubProject->GetId()] = $this->SubProject; $this->Dependencies[$this->SubProject->GetId()] = array(); } else { if ($name == 'DEPENDENCY') { // A DEPENDENCY is expected to be: // // - another subproject that already exists (from a previous element in // this submission) // $dependentProject = new SubProject(); $dependentProject->SetName($attributes['NAME']); $dependentProject->SetProjectId($this->projectid); // The subproject's Id is automatically loaded once its name & projectid // are set. $dependencyid = $dependentProject->GetId(); $added = false; if ($dependencyid !== false && is_numeric($dependencyid)) { if (array_key_exists($dependencyid, $this->SubProjects)) { $this->Dependencies[$this->SubProject->GetId()][] = $dependencyid; $added = true; } } if (!$added) { add_log("Project.xml DEPENDENCY of " . $this->SubProject->GetName() . " not mentioned earlier in file: " . $attributes['NAME'], "ProjectHandler:startElement", LOG_WARNING, $this->projectid); } } else { if ($name == 'EMAIL') { $email = $attributes['ADDRESS']; // Check if the user is in the database $User = new User(); $posat = strpos($email, '@'); if ($posat !== false) { $User->FirstName = substr($email, 0, $posat); $User->LastName = substr($email, $posat + 1); } else { $User->FirstName = $email; $User->LastName = $email; } $User->Email = $email; $User->Password = md5($email); $User->Admin = 0; $userid = $User->GetIdFromEmail($email); if (!$userid) { $User->Save(); $userid = $User->Id; } // Insert into the UserProject $UserProject = new UserProject(); $UserProject->EmailType = 3; // any build $UserProject->EmailCategory = 54; // everything except warnings $UserProject->UserId = $userid; $UserProject->ProjectId = $this->projectid; $UserProject->Save(); // Insert the labels for this user $LabelEmail = new LabelEmail(); $LabelEmail->UserId = $userid; $LabelEmail->ProjectId = $this->projectid; $Label = new Label(); $Label->SetText($this->SubProject->GetName()); $labelid = $Label->GetIdFromText(); if (!empty($labelid)) { $LabelEmail->LabelId = $labelid; $LabelEmail->Insert(); } } } } } }
public static function Login(UserCredentials $credentials) { //Credentials check $res = 0; if ($credentials->Email && $credentials->Password) { $res = 3; $user = new User($credentials->Email); if ($user->mExists) { $res = 2; if ($user->CheckPassword($credentials->Password)) { $res = 4; //check if user is banned if (!$user->IsBanned()) { //Login :) $user->IsOnline = true; $user->LastLogin = date('Y-m-d H:i:s'); $user->Save(); $res = 1; } } } } return array('res' => $res, 'userid' => $user->Id); }
/** LDAP authentication */ function ldapAuthenticate($email, $password, $SessionCachePolicy, $rememberme) { global $loginerror; $loginerror = ''; include dirname(__DIR__) . '/config/config.php'; include_once 'models/user.php'; $ldap = ldap_connect($CDASH_LDAP_HOSTNAME); ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, $CDASH_LDAP_PROTOCOL_VERSION); ldap_set_option($ldap, LDAP_OPT_REFERRALS, $CDASH_LDAP_OPT_REFERRALS); // Bind as the LDAP user if authenticated ldap is enabled if ($CDASH_LDAP_AUTHENTICATED) { ldap_bind($ldap, $CDASH_LDAP_BIND_DN, $CDASH_LDAP_BIND_PASSWORD); } if (isset($ldap) && $ldap != '') { /* search for pid dn */ $result = ldap_search($ldap, $CDASH_LDAP_BASEDN, '(&(mail=' . $email . ')' . $CDASH_LDAP_FILTER . ')', array('dn', 'cn')); if ($result != 0) { $entries = ldap_get_entries($ldap, $result); @($principal = $entries[0]['dn']); if (isset($principal)) { // bind as this user if (@ldap_bind($ldap, $principal, $password) and strlen(trim($password)) != 0) { $sql = 'SELECT id,password FROM ' . qid('user') . " WHERE email='" . pdo_real_escape_string($email) . "'"; $result = pdo_query("{$sql}"); // If the user doesn't exist we add it if (pdo_num_rows($result) == 0) { @($givenname = $entries[0]['cn'][0]); if (!isset($givenname)) { $loginerror = 'No givenname (cn) set in LDAP, cannot register user into CDash'; return false; } $names = explode(' ', $givenname); $User = new User(); if (count($names) > 1) { $User->FirstName = $names[0]; $User->LastName = $names[1]; for ($i = 2; $i < count($names); $i++) { $User->LastName .= ' ' . $names[$i]; } } else { $User->LastName = $names[0]; } // Add the user in the database $storedPassword = md5($password); $User->Email = $email; $User->Password = $storedPassword; $User->Save(); $userid = $User->Id; } else { $user_array = pdo_fetch_array($result); $storedPassword = $user_array['password']; $userid = $user_array['id']; // If the password has changed we update if ($storedPassword != md5($password)) { $User = new User(); $User->Id = $userid; $User->SetPassword(md5($password)); } } if ($rememberme) { $cookiename = 'CDash-' . $_SERVER['SERVER_NAME']; $time = time() + 60 * 60 * 24 * 30; // 30 days; // Create a new password $keychars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $length = 32; $key = ''; $max = strlen($keychars) - 1; for ($i = 0; $i <= $length; $i++) { // random_int is available in PHP 7 and the random_compat PHP 5.x // polyfill included in the Composer package.json dependencies. $key .= substr($keychars, random_int(0, $max), 1); } $value = $userid . $key; setcookie($cookiename, $value, $time); // Update the user key pdo_query('UPDATE ' . qid('user') . " SET cookiekey='" . $key . "' WHERE id=" . qnum($userid)); } session_name('CDash'); session_cache_limiter($SessionCachePolicy); session_set_cookie_params($CDASH_COOKIE_EXPIRATION_TIME); @ini_set('session.gc_maxlifetime', $CDASH_COOKIE_EXPIRATION_TIME + 600); session_start(); // create the session array if (isset($_SESSION['cdash']['password'])) { $password = $_SESSION['cdash']['password']; } $sessionArray = array('login' => $email, 'passwd' => $storedPassword, 'ID' => session_id(), 'valid' => 1, 'loginid' => $userid); $_SESSION['cdash'] = $sessionArray; return true; } else { $loginerror = 'Wrong email or password.'; return false; } } else { $loginerror = 'User not found in LDAP'; } ldap_free_result($result); } else { $loginerror = 'Error occured searching the LDAP'; } ldap_close($ldap); } else { $loginerror = 'Could not connect to LDAP at ' . $CDASH_LDAP_HOSTNAME; } return false; }
// Get the long lasting token credentials $token_credentials = $connection->getAccessToken($_GET['oauth_verifier']); // Grab the details of this user $details = $connection->get("profile/details"); // Save it to the database $myUser->ResetValues(); // Check to see if this user is already in the DB $myUser->SetValue('username', $details->response->username); $myUser->GetInfo(NULL, array('username')); // Add the new token credentials $myUser->SetValue('oauth_token', $token_credentials['oauth_token']); $myUser->SetValue('oauth_token_secret', $token_credentials['oauth_token_secret']); // Create a unique ID for the session $myUser->SetValue('sessionid', uniqid()); // Update the user information if found or insert if new if (!$myUser->Save()) { throw new SimplException('Error Saving Formspring Client Token', 2, 'Error: Error Saving Formspring Client Token :' . $details->response->username); } // Set the session cookie if (!isset($_GET['delegate'])) { setcookie('session', $myUser->GetValue('sessionid'), time() + 3600 * 24 * 7); } else { // Setup the relationship $myAccountAccess->SetValue('user_id', $_GET['delegate']); $myAccountAccess->SetValue('delegate_id', $myUser->GetPrimary()); $myAccountAccess->SetValue('type', 'full'); if (!$myAccountAccess->Save()) { throw new SimplException('Error Saving Delegate Information', 2, 'Error: Error Saving Delegate Information. Delegate:' . $_GET['delegate']); } } // See if this user already exists in the DB
/** * API Method inserts a new User record and render response as JSON */ public function Create() { try { $json = json_decode(RequestUtil::GetBody()); if (!$json) { throw new Exception('The request body does not contain valid JSON'); } $user = new User($this->Phreezer); // TODO: any fields that should not be inserted by the user should be commented out // this is an auto-increment. uncomment if updating is allowed // $user->Iduser = $this->SafeGetVal($json, 'iduser'); $user->Institution = $this->SafeGetVal($json, 'institution'); $user->Fullname = $this->SafeGetVal($json, 'fullname'); $user->Username = $this->SafeGetVal($json, 'username'); $user->Password = $this->SafeGetVal($json, 'password'); $user->Notes = $this->SafeGetVal($json, 'notes'); $user->Code = $this->SafeGetVal($json, 'code'); $user->Timezone = $this->SafeGetVal($json, 'timezone'); $user->Lastlogin = date('Y-m-d H:i:s', strtotime($this->SafeGetVal($json, 'lastlogin'))); $user->Status = $this->SafeGetVal($json, 'status'); $user->Admin = $this->SafeGetVal($json, 'admin'); $user->Validate(); $errors = $user->GetValidationErrors(); if (count($errors) > 0) { $this->RenderErrorJSON('Please check the form for errors', $errors); } else { $user->Save(); $this->RenderJSON($user, $this->JSONPCallback(), true, $this->SimpleObjectParams()); } } catch (Exception $ex) { $this->RenderExceptionJSON($ex); } }
/** * API Method inserts a new User record and render response as JSON */ public function Create() { try { $json = json_decode(RequestUtil::GetBody()); if (!$json) { throw new Exception('The request body does not contain valid JSON'); } $user = new User($this->Phreezer); // TODO: any fields that should not be inserted by the user should be commented out // this is an auto-increment. uncomment if updating is allowed // $user->Id = $this->SafeGetVal($json, 'id'); $user->RoleId = $this->SafeGetVal($json, 'roleId'); $user->Username = $this->SafeGetVal($json, 'username'); $user->Password = $this->SafeGetVal($json, 'password'); $user->FirstName = $this->SafeGetVal($json, 'firstName'); $user->LastName = $this->SafeGetVal($json, 'lastName'); $user->Validate(); $errors = $user->GetValidationErrors(); if (count($errors) > 0) { $this->RenderErrorJSON('Please check the form for errors', $errors); } else { $user->Save(); $this->RenderJSON($user, $this->JSONPCallback(), true, $this->SimpleObjectParams()); } } catch (Exception $ex) { $this->RenderExceptionJSON($ex); } }
DB::Execute('UPDATE {P}UserSettings SET usrFlags=usrFlags|'.PERMISSION_MOD.' WHERE usrID='.DB::Q($_POST['add_mod'])); $_SESSION['notice'].='<li>'.$_POST['add_mod'].' added as a '.MOD_NAME.'.</li>'; } if(!empty($_POST['revoke']) && is_array($_POST['revoke']) && count($_POST['revoke'])>0) { if($lvl<999) die('No.'); $c=0; foreach($_POST['revoke'] as $modid) { $u=new User($modid); $u->Load(); if($u->getMACLevel()>=$lvl) die('No.'); $u->Flags&=~PERMISSION_MOD; // Remove mod flag $u->Flags&=~PERMISSION_SYSOP; // Remove admin flag $u->Save(); $c++; } $_SESSION['notice'].='<li>'.$c.' power users revoked.</li>'; } $_SESSION['notice']="<ul>{$_SESSION['notice']}</ul>"; } $page_title = 'Manage Users'; $mods=new TablePrinter('tblModerators'); $mods->DefineColumns(array(' ','UID','Last Action'),'Last Action'); $mods->SetTDClass('UID','uid'); $admins=new TablePrinter('tblAdmins'); $admins->DefineColumns(array(' ','UID','Last Action'),'Last Action'); $admins->SetTDClass('UID','uid');
/** Authentication function */ function register() { global $reg; include dirname(__DIR__) . '/config/config.php'; require_once 'include/pdo.php'; if (isset($_GET['key'])) { $key = pdo_real_escape_string($_GET['key']); $sql = 'SELECT * FROM ' . qid('usertemp') . " WHERE registrationkey='{$key}'"; $query = pdo_query($sql); if (pdo_num_rows($query) == 0) { $reg = 'The key is invalid.'; return 0; } $query_array = pdo_fetch_array($query); $email = $query_array['email']; // We copy the data from usertemp to user $user = new User(); $user->Email = $email; $user->Password = $query_array['password']; $user->FirstName = $query_array['firstname']; $user->LastName = $query_array['lastname']; $user->Institution = $query_array['institution']; if ($user->Save()) { pdo_query("DELETE FROM usertemp WHERE email='{$email}'"); return 1; } else { $reg = pdo_error(); return 0; } } elseif (isset($_POST['sent'])) { // arrive from register form $url = $_POST['url']; if ($url != 'catchbot') { $reg = 'Bots are not allowed to obtain CDash accounts!'; return 0; } $email = $_POST['email']; $passwd = $_POST['passwd']; $passwd2 = $_POST['passwd2']; if (!($passwd == $passwd2)) { $reg = 'Passwords do not match!'; return 0; } global $CDASH_MINIMUM_PASSWORD_LENGTH, $CDASH_MINIMUM_PASSWORD_COMPLEXITY, $CDASH_PASSWORD_COMPLEXITY_COUNT; $complexity = getPasswordComplexity($passwd); if ($complexity < $CDASH_MINIMUM_PASSWORD_COMPLEXITY) { if ($CDASH_PASSWORD_COMPLEXITY_COUNT > 1) { $reg = "Your password must contain at least {$CDASH_PASSWORD_COMPLEXITY_COUNT} characters from {$CDASH_MINIMUM_PASSWORD_COMPLEXITY} of the following types: uppercase, lowercase, numbers, and symbols."; } else { $reg = "Your password must contain at least {$CDASH_MINIMUM_PASSWORD_COMPLEXITY} of the following: uppercase, lowercase, numbers, and symbols."; } return 0; } if (strlen($passwd) < $CDASH_MINIMUM_PASSWORD_LENGTH) { $reg = "Your password must be at least {$CDASH_MINIMUM_PASSWORD_LENGTH} characters."; return 0; } $fname = $_POST['fname']; $lname = $_POST['lname']; $institution = $_POST['institution']; if ($email && $passwd && $passwd2 && $fname && $lname && $institution) { $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}"); pdo_select_db("{$CDASH_DB_NAME}", $db); $passwd = md5($passwd); $email = pdo_real_escape_string($email); $sql = 'SELECT email FROM ' . qid('user') . " WHERE email='{$email}'"; if (pdo_num_rows(pdo_query($sql)) > 0) { $reg = "{$email} is already registered."; return 0; } $sql = 'SELECT email FROM ' . qid('usertemp') . " WHERE email='{$email}'"; if (pdo_num_rows(pdo_query($sql)) > 0) { $reg = "{$email} is already registered. Check your email if you haven't received the link to activate yet."; return 0; } $passwd = pdo_real_escape_string($passwd); $fname = pdo_real_escape_string($fname); $lname = pdo_real_escape_string($lname); $institution = pdo_real_escape_string($institution); if ($CDASH_REGISTRATION_EMAIL_VERIFY) { $keychars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $length = 40; $key = ''; $max = strlen($keychars) - 1; for ($i = 0; $i < $length; $i++) { // random_int is available in PHP 7 and the random_compat PHP 5.x // polyfill included in the Composer package.json dependencies. $key .= substr($keychars, random_int(0, $max), 1); } $date = date(FMT_DATETIME); $sql = 'INSERT INTO ' . qid('usertemp') . " (email,password,firstname,lastname,institution,registrationkey,registrationdate)\n VALUES ('{$email}','{$passwd}','{$fname}','{$lname}','{$institution}','{$key}','{$date}')"; } else { $user = new User(); $user->Email = $email; $user->Password = $passwd; $user->FirstName = $fname; $user->LastName = $lname; $user->Institution = $institution; $user->Save(); } if (pdo_query($sql)) { if ($CDASH_REGISTRATION_EMAIL_VERIFY) { $currentURI = get_server_URI(); // Send the email $emailtitle = 'Welcome to CDash!'; $emailbody = 'Hello ' . $fname . ",\n\n"; $emailbody .= "Welcome to CDash! In order to validate your registration please follow this link: \n"; $emailbody .= $currentURI . '/register.php?key=' . $key . "\n"; $serverName = $CDASH_SERVER_NAME; if (strlen($serverName) == 0) { $serverName = $_SERVER['SERVER_NAME']; } $emailbody .= "\n-CDash on " . $serverName . "\n"; if (cdashmail("{$email}", $emailtitle, $emailbody)) { add_log('email sent to: ' . $email, 'Registration'); } else { add_log('cannot send email to: ' . $email, 'Registration', LOG_ERR); } $reg = "A confirmation email has been sent. Check your email (including your spam folder) to confirm your registration!\n"; $reg .= 'You need to activate your account within 24 hours.'; return 0; } return 1; } else { $reg = pdo_error(); return 0; } } else { $reg = 'Please fill in all of the required fields'; return 0; } } return 0; }
exit; } else { if (isset($_POST['USERNAME']) && isset($_POST['PWD']) && isset($_POST['PWDR'])) { //TODO Clear Input if ($_POST['USERNAME'] == "" || $_POST['PWD'] == "" || $_POST['PWDR'] == "") { throw new Exception("Fields cannot be empty"); } if ($_POST['PWD'] != $_POST['PWDR']) { throw new Exception("Two passwords are different"); } $new = new User(); $new->SetID($_POST['USERNAME']); $new->SetPassword($_POST['PWD']); $new->SetAdmin(TRUE); $new->SetValid(TRUE); $new->Save(); $msg = "User added successfully"; } } } } catch (Exception $e) { $error = $e->getMessage(); } ?> <html> <head> <title>RaspiControl</title> <meta charset="utf-8"/> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi"/>
<?php include_once "../includes/header.inc.php"; include_once "../includes/needLogIn.inc.php"; require_once "../Classes/User.class.php"; $user = new User(); if (isset($PARAMS['password'])) { $u = $_SESSION['username']; $p = $PARAMS['password']; $user->username = $u; $user->Find(); if ($user->variables && $user->delete_date == "" && md5(base64_encode($p)) == $user->password) { $user->delete_date = date("Ymd"); $user->Save(); $datos = array("status" => "OK"); print_r(json_encode($datos)); } else { if ($user->variables && $user->delete_date == "" && md5(base64_encode($p)) != $user->password) { $datos = array("status" => "WrongPassword"); print_r(json_encode($datos)); } else { if (!$user->variables || $user->delete_date != "") { $datos = array("status" => "NoResults"); print_r(json_encode($datos)); } } } } else { $datos = array("status" => "WrongData"); print_r(json_encode($datos)); }
include_once '../Models/User.php'; $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null; $method = $_SERVER['REQUEST_METHOD']; $format = isset($_REQUEST['format']) ? $_REQUEST['format'] : 'web'; $view = null; switch ($action . '_' . $method) { case 'create_GET': $model = User::Blank(); $view = "users/edit.php"; break; case 'save_POST': $sub_action = empty($_REQUEST['id']) ? 'created' : 'updated'; $errors = User::Validate($_REQUEST); if (!$errors) { $errors = User::Save($_REQUEST); // var_dump($errors); } if (!$errors) { if ($format == 'json') { header("Location: ?action=edit&format=json&id={$_REQUEST['id']}"); } else { header("Location: ?sub_action={$sub_action}&id={$_REQUEST['id']}"); } die; } else { //my_print($errors); $model = $_REQUEST; $view = "users/edit.php"; } break;
} else { $fname = $_POST['fname']; $lname = $_POST['lname']; $institution = $_POST['institution']; if ($email && $passwd && $passwd2 && $fname && $lname && $institution) { $User = new User(); if ($User->GetIdFromEmail($email)) { $xml .= add_XML_value('error', 'Email already registered!'); } else { $passwdencryted = md5($passwd); $User->Email = $email; $User->Password = $passwdencryted; $User->FirstName = $fname; $User->LastName = $lname; $User->Institution = $institution; if ($User->Save()) { $xml .= add_XML_value('warning', 'User ' . $email . ' added successfully with password:'******'error', 'Cannot add user'); } } } else { $xml .= add_XML_value('error', 'Please fill in all of the required fields'); } } } elseif (isset($_POST['makenormaluser'])) { if ($postuserid > 1) { $update_array = pdo_fetch_array(pdo_query('SELECT firstname,lastname FROM ' . qid('user') . " WHERE id='" . $postuserid . "'")); pdo_query('UPDATE ' . qid('user') . " SET admin=0 WHERE id='" . $postuserid . "'"); $xml .= '<warning>' . $update_array['firstname'] . ' ' . $update_array['lastname'] . ' is not administrator anymore.</warning>'; } else {
include "include.common.php"; include "server.includes.inc.php"; if (empty($user)) { if (!empty($_REQUEST['username']) && !empty($_REQUEST['password'])) { $suser = null; $ssoUserLoaded = false; include 'login.com.inc.php'; if (empty($suser)) { $suser = new User(); $suser->Load("(username = ? or email = ?) and password = ?", array($_REQUEST['username'], $_REQUEST['username'], md5($_REQUEST['password']))); } if ($suser->password == md5($_REQUEST['password']) || $ssoUserLoaded) { $user = $suser; saveSessionObject('user', $user); $suser->last_login = date("Y-m-d H:i:s"); $suser->Save(); if (!$ssoUserLoaded && !empty($baseService->auditManager)) { $baseService->auditManager->user = $user; $baseService->audit(IceConstants::AUDIT_AUTHENTICATION, "User Login"); } if ($user->user_level == "Admin") { header("Location:" . CLIENT_BASE_URL . "?g=admin&n=dashboard&m=admin_Admin"); } else { header("Location:" . CLIENT_BASE_URL . "?g=modules&n=dashboard&m=module_Personal_Information"); } } else { header("Location:" . CLIENT_BASE_URL . "login.php?f=1"); } } } else { if ($user->user_level == "Admin") {
protected function sendMessage($sender, $message, $recepients, $loginId = '') { if (!class_exists('Message')) { $this->loadModel('Message'); } if (!class_exists('BulkSMS')) { $this->loadModel('BulkSMS'); } if (empty($loginId)) { $loginId = $_SESSION['loginId']; } $user = new User($loginId); $len = strlen($message); $msgNo = $len < 160 ? 1 : ($len - $len % 160) / 160; $msgNo = $len > 160 && $len % 160 != 0 ? $msgNo + 1 : $msgNo; $count = ceil(count(explode(',', $recepients)) * $msgNo); $avu = $user->Balance * 1; $uneeded = $count * UNITS_PER_SMS; if ($user->Balance < $uneeded) { return 'Insufficient balance'; } $recepients = str_replace(',0', ',234', $recepients); $url = API_URL . 'api/sendMessage?returnDetails=1&loginId=' . API_USERNAME . '&password='******'&sender=' . urlencode($sender) . '&message=' . urlencode($message) . '&recipients=' . urlencode(trim($recepients)); $xml = file_get_contents($url); //check if message sent and deduct if (strpos($xml, '1701') !== FALSE) { $user->Balance -= $count * UNITS_PER_SMS; $user->Save(); $notification = "Messae sent"; $bulksSMS = new BulkSMS(); $bulksSMS->LoginId = $user->LoginId; $bulksSMS->Message = $message; $bulksSMS->Sender = $sender; $bulksSMS->Status = '1701'; $bulksSMS->Count = $count; $bulksSMS->Save(); $messages = array(); $nos = explode(',', $recepients); foreach ($nos as $no) { if (empty($no)) { continue; } $sms = new Message(); $sms->BulkSMSId = $bulksSMS->Id; $sms->Number = $no; $sms->Message = $message; $sms->Sender = $sender; $sms->RefId = -1; $sms->Status = '1701'; $messages[] = $sms; } $bulksSMS->SaveMessages($messages); } return $xml; }