public function setUp()
 {
     $user = new User(null, 'test_auth', 'test_mail', 'My Name');
     $user->save();
     $user->set_password('password');
     $this->user = $user;
 }
Example #2
0
 protected function render_body()
 {
     if (!empty($_POST)) {
         $errors = $this->validate_first_name(isset($_POST['first-name']) ? $_POST['first-name'] : "");
         $errors .= $this->validate_last_name(isset($_POST['last-name']) ? $_POST['last-name'] : "");
         $errors .= $this->validate_username(isset($_POST['username']) ? $_POST['username'] : "");
         $errors .= $this->validate_password(isset($_POST['password']) ? $_POST['password'] : "");
         $errors .= $this->validate_academic_year(isset($_POST['academic-year']) ? $_POST['academic-year'] : "");
         if ($errors) {
             $this->render_register_form($errors);
         } else {
             $user = new User();
             $user->set_first_name($_POST['first-name']);
             $user->set_last_name($_POST['last-name']);
             $user->set_username($_POST['username']);
             $user->set_password($_POST['password']);
             $user->set_academic_year($_POST['academic-year']);
             $user_model = new User_model();
             if ($user_model->store_user($user, false, false, true) == false) {
                 $this->render_register_form('Username already exists.');
             } else {
                 $this->redirect_to_main_page();
             }
         }
     } else {
         $this->render_register_form();
     }
 }
Example #3
0
 public function create_user($username, $password, $email, $phone, $bdate, $information, $interests, $city, $image)
 {
     $user = new User();
     try {
         $user->set_username(Validation::username($username));
     } catch (Exception $ex) {
         echo 'Failed: ', $ex->getMessage();
         exit;
     }
     try {
         $user->set_password(Validation::password($password));
     } catch (Exception $ex) {
         echo 'Failed: ', $ex->getMessage();
         exit;
     }
     try {
         $user->set_email(Validation::email($email));
     } catch (Exception $ex) {
         echo 'Failed: ', $ex->getMessage();
         exit;
     }
     try {
         $user->set_phone(Validation::phone($phone));
     } catch (Exception $ex) {
         echo 'Failed: ', $ex->getMessage();
         exit;
     }
     try {
         $user->set_bdate(Validation::bdate($bdate));
     } catch (Exception $ex) {
         echo 'Failed: ', $ex->getMessage();
         exit;
     }
     try {
         $user->set_information(Validation::information($information));
     } catch (Exception $ex) {
         echo 'Failed: ', $ex->getMessage();
         exit;
     }
     try {
         $user->set_interests(Validation::interests($interests));
     } catch (Exception $ex) {
         echo 'Failed: ', $ex->getMessage();
         exit;
     }
     try {
         $user->set_city(Validation::city($city));
     } catch (Exception $ex) {
         echo 'Failed: ', $ex->getMessage();
         exit;
     }
     try {
         $user->set_image(Validation::image($image));
     } catch (Exception $ex) {
         echo 'Failed: ', $ex->getMessage();
         exit;
     }
     return $user;
 }
Example #4
0
 public function login($username, $password)
 {
     $query = "SELECT * FROM " . UserDAO::USER_TABLE . " WHERE username = '******' AND password='******'";
     $result = mysqli_query($this->conn, $query);
     if ($result && mysqli_num_rows($result) > 0) {
         $userBD = mysqli_fetch_array($result);
         $user = new User();
         $user->set_ID($userBD['iduser']);
         $user->set_username($userBD['username']);
         $user->set_password($userBD['password']);
         return $user;
     }
     return null;
 }
Example #5
0
 public function get_all()
 {
     $userlist = array();
     $this->db->connect();
     $sql = "SELECT * FROM users";
     $result = $this->db->fetchquery($sql);
     while ($row = $result->fetch_assoc()) {
         $user = new User();
         $user->set_id($row['id']);
         $user->set_username($row['username']);
         $user->set_password($row['password']);
         array_push($userlist, $user);
     }
     return $userlist;
 }
Example #6
0
function init_user_from_post_data(&$_user = NULL)
{
    if (!$_user) {
        $_user = new User();
        $_user->set_name($_POST['username']);
    }
    $_user->set_password($_POST['password']);
    $_user->set_firstname($_POST['firstname']);
    $_user->set_lastname($_POST['lastname']);
    $_user->set_mail($_POST['mail'], $_POST['publicmail'] == 'on');
    $_user->set_do_notify($_POST['do_notify']);
    $_user->set_homepage($_POST['homepage']);
    $_user->set_im($_POST['im']);
    return $_user;
}
 function test_password()
 {
     $user = new User();
     $rand = md5(rand());
     $user->username = '******' . $rand;
     $user->fullname = 'This is the name';
     $user->email = "{$rand}@email.com";
     $user->save();
     $user->set_password('abc.com');
     $this->assertTrue($user->check_password('abc.com'));
     $this->assertFalse($user->check_password('abc.codffdm'));
     //to check with the DB
     $user_g = User::by_email($user->email);
     $this->assertTrue($user_g->check_password('abc.com'));
     $this->assertFalse($user_g->check_password('abc.codffdm'));
 }
Example #8
0
 public static function create_on_install()
 {
     # Create System user
     $system_user_name = NEECHY_USER;
     $system_user_email = '*****@*****.**';
     $system_user = new User(array('name' => $system_user_name, 'email' => $system_user_email, 'status' => self::$STATUS_LEVELS['NEW']));
     $system_user->set_password(NeechySecurity::random_hex());
     $system_user->save();
     # Create Owner (user currently logged in)
     $app_engine_user = AppAuthService::user();
     if ($app_engine_user) {
         $owner_name = $app_engine_user->getNickname();
         $owner_email = $app_engine_user->getEmail();
         $owner = new User(array('name' => $owner_name, 'email' => $owner_email, 'status' => self::$STATUS_LEVELS['NEW']));
         $owner->set_password(NeechySecurity::random_hex());
         $owner->save();
     } else {
         $owner = null;
     }
     return array($system_user, $owner);
 }
Example #9
0
 private function _map_posted_data()
 {
     $user = new User();
     $user->set_user_name($_POST['user_name']);
     $user->set_first_name($_POST['first_name']);
     $user->set_last_name($_POST['last_name']);
     $user->set_contact_number($_POST['contact_number']);
     if (isset($_POST['user_type'])) {
         $user->set_user_type($_POST['user_type']);
     }
     $user->set_user_status($_POST['user_status']);
     if (isset($_POST['password'])) {
         $user->set_password($_POST['password']);
     }
     if ($_POST['user_type'] == 'organization') {
         $user->set_name($_POST['name']);
         $user->set_doe($_POST['doe']);
         $user->set_address($_POST['address']);
         $user->set_objective($_POST['objective']);
         //store file
         $filename = $_FILES['img']['name'];
         $path = PUBLIC_PATH . "/pictures/orgPictures/";
         move_uploaded_file($_FILES['img']['tmp_name'], $path . $filename);
         $savepath = PUBLIC_PATH2 . "/pictures/orgPictures/";
         $user->set_img($savepath . $filename);
     } elseif ($_POST['user_type'] == 'welfare') {
         $user->set_welf_name($_POST['welf_name']);
         $user->set_welf_doe($_POST['welf_doe']);
         $user->set_welf_service($_POST['welf_service']);
         $user->set_welf_address($_POST['welf_address']);
         $user->set_welf_objective($_POST['welf_objective']);
         //store file
         $filename = $_FILES['img']['name'];
         $path = PUBLIC_PATH . "/pictures/welfPictures/";
         move_uploaded_file($_FILES['img']['tmp_name'], $path . $filename);
         $savepath = PUBLIC_PATH2 . "/pictures/welfPictures/";
         $user->set_welf_img($savepath . $filename);
     }
     return $user;
 }
Example #10
0
/**
* Change user password
* This function creates a new random 8 character password,
*  sets it in the database and emails it to the user
* @return boolean true or false on success of function
* @see make_seed()
*/
function changePassword()
{
    global $conf;
    $adminemail = $conf['app']['adminEmail'];
    $title = $conf['app']['title'];
    $use_logon_name = (bool) $conf['app']['useLogonName'];
    // Check if user exists
    $email = stripslashes(trim($_POST['email_address']));
    // Connect to database
    $AuthDB = new AuthDB();
    $id = $AuthDB->userExists($email);
    if (empty($id)) {
        CmnFns::do_error_box(translate('Sorry, we could not find that user in the database.'), '', false);
        return false;
    } else {
        $user = new User($id);
        $result = $user->get_user_data();
    }
    // Generate new 8 character password by choosing random
    // ASCII characters between 48 and 122
    // (valid password characters)
    $pwd = '';
    $num = 0;
    for ($i = 0; $i < 8; $i++) {
        // Seed random for older versions of PHP
        mt_srand(make_seed());
        if ($i % 2 == 0) {
            $num = mt_rand(97, 122);
        } else {
            if ($i % 3 == 0) {
                $num = mt_rand(48, 58);
            } else {
                $num = mt_rand(63, 90);
            }
        }
        // Uppercase letters and '@ ?'
        // Put password together
        $pwd .= chr($num);
    }
    // Set password in database
    $user->set_password($pwd);
    // Send email to user
    $sub = translate('Your New Password', array($title));
    $msg = translate_email('new_password', $result['fname'], $conf['app']['title'], $pwd, CmnFns::getScriptURL(), $adminemail);
    $msg .= $use_logon_name ? "\r\n" . translate('Your logon name is', array($result['logon_name'])) : '';
    // Send email
    $mailer = new PHPMailer();
    $mailer->AddAddress($result['email'], $result['fname']);
    $mailer->FromName = $conf['app']['title'];
    $mailer->From = $adminemail;
    $mailer->Subject = $sub;
    $mailer->Body = $msg;
    $mailer->Send();
    return true;
}
Example #11
0
            }
        } else {
            $out = new intOutput("generic_err");
        }
    }
    if ($_GET['action'] == "register") {
        if ($GLOBALS['conf']['public'] == true) {
            $_POST['username'] = str_replace("..", "", $_POST['username']);
            $_POST['username'] = str_replace("/", "", $_POST['username']);
            $_POST['username'] = str_replace("\\", "", $_POST['username']);
            $u = $User->filter("username", $_POST['username']);
            if (isset($u[0])) {
                $out = new intOutput("generic_err");
            } else {
                $p = new User();
                $p->username = $_POST['username'];
                $p->email = $_POST['email'];
                $p->set_password($_POST['password']);
                $p->logged = 0;
                $p->save();
                echo "0";
            }
        } else {
            die('User registration disabled');
        }
    }
    if ($_GET['action'] == "public") {
        require "../configuration.php";
        echo $GLOBALS['conf']['public'];
    }
}
Example #12
0
 private function page_admin_users_create()
 {
     // If the form is POSTed, validate data and save user
     // FIXME: move validate to User object. see beginnings of User::validate()
     if (isset($_POST['login'])) {
         $success = true;
         // login valid?
         if (!isset($_POST['login']) || strlen($_POST['login']) < 2) {
             $success = false;
             $this->flash_error("Login must be 2 characters or longer");
         }
         // firstname valid?
         if (!isset($_POST['first_name']) || strlen($_POST['first_name']) < 2) {
             $success = false;
             $this->flash_error("First name must be 2 characters or longer");
         }
         // lastname valid?
         if (!isset($_POST['last_name']) || strlen($_POST['last_name']) < 2) {
             $success = false;
             $this->flash_error("Last name must be 2 characters or longer");
         }
         // password check?
         if (!isset($_POST['password']) || !isset($_POST['password_verify']) || strlen($_POST['password']) < 2) {
             $success = false;
             $this->flash_error("Password must be 2 characters or longer");
         } else {
             if ($_POST['password'] != $_POST['password_verify']) {
                 $success = false;
                 $this->flash_error("Password confirmation did not match");
             }
         }
         // unique login?
         $users = $this->conf->get_array('/users');
         if (is_array($users) && in_array($_POST['login'], $users)) {
             $success = false;
             $this->flash_error("Login already in use");
         }
         $user = new User();
         $user->login = $_POST['login'];
         $user->first_name = $_POST['first_name'];
         $user->last_name = $_POST['last_name'];
         $user->roles = $_POST['roles'];
         // enforce admin if genesis
         if ($this->genesis()) {
             $user->roles[] = 'admin';
         }
         $success &= $user->set_password($_POST['password']);
         $users[] = $user->login;
         $success &= $this->conf->set_array('/users', $users);
         if ($success) {
             $this->flash_success("User created");
         } else {
             $this->flash_error("User creation failed");
             $this->smarty->assign('login', $_POST['login']);
             $this->smarty->assign('first_name', $_POST['first_name']);
             $this->smarty->assign('last_name', $_POST['last_name']);
         }
     }
     if ($this->genesis()) {
         $this->smarty->assign('admin_checked', 'checked');
         $this->smarty->assign('admin_disabled', 'disabled');
     }
     $this->content = './tpl/admin/users/create.tpl';
 }
Example #13
0
     // We want all logins to be lowercase to guarantee uniqueness regardless of the database case handling for UNIQUE indexes:
     $login = utf8_strtolower($login);
     $UserCache =& get_UserCache();
     if ($UserCache->get_by_login($login)) {
         // The login is already registered
         param_error($dummy_fields['login'], sprintf(T_('The login &laquo;%s&raquo; is already registered, please choose another one.'), $login));
     }
 }
 if ($Messages->has_errors()) {
     // Stop registration if the errors exist
     break;
 }
 $DB->begin();
 $new_User = new User();
 $new_User->set('login', $login);
 $new_User->set_password($pass1);
 $new_User->set('ctry_ID', $country);
 $new_User->set('firstname', $firstname);
 $new_User->set('lastname', $lastname);
 $new_User->set('gender', $gender);
 $new_User->set('source', $source);
 $new_User->set_email($email);
 $new_User->set_datecreated($localtimenow);
 if ($registration_ask_locale) {
     // set locale if it was prompted, otherwise let default
     $new_User->set('locale', $locale);
 }
 if (!empty($invitation)) {
     // Invitation code was entered on the form
     $SQL = new SQL();
     $SQL->SELECT('ivc_source, ivc_grp_ID');
Example #14
0
 public function set_user_password($user_password)
 {
     parent::set_password($user_password);
 }
Example #15
0
function process_page($app, $action, &$var)
{
    $var['domain_count'] = Domain::count();
    $var['user_count'] = User::count();
    $var['domains'] = Domain::list_all();
    if (!isset($var['domain_id'])) {
        if (isset($_COOKIE['app/users/domain_id'])) {
            $var['domain_id'] = filter_var($_COOKIE['app/users/domain_id'], FILTER_SANITIZE_STRING);
            if (Domain::list_by_id($var['domain_id']) == null) {
                $var['domain_id'] = 0;
            }
        } else {
            $var['domain_id'] = 0;
        }
    }
    if ($var['domain_id'] != 0) {
        $var['users'] = User::list_by_domain_id($var['domain_id']);
        $var['active_domain'] = Domain::list_by_id($var['domain_id']);
    } else {
        $var['users'] = User::list_all();
    }
    switch ($app->action) {
        case 'select_domain':
            setcookie('app/users/domain_id', $var['domain_id']);
            $app->reload();
            break;
        case 'edit_user':
            $user = User::list_by_id($var['user_id']);
            $var['user_email'] = $user->get_email();
            $var['user_password'] = '';
            if ($user->is_admin()) {
                $var['user_admin'] = 'on';
            } else {
                unset($var['user_admin']);
            }
            break;
        case 'insert_new_user':
            $user = new User();
            $user->set_email($var['user_email']);
            $user->set_password($var['user_password']);
            $user->set_domain_id($var['domain_id']);
            $user->set_admin(isset($var['user_admin']));
            if ($user->insert()) {
                $app->reload();
            } else {
                $app->action = 'new_user';
            }
            break;
        case 'update_edit_user':
            $user = User::list_by_id($var['user_id']);
            $user->set_email($var['user_email']);
            $user->set_password($var['user_password']);
            $user->set_admin(isset($var['user_admin']));
            if ($user->update()) {
                $app->reload();
            } else {
                $app->action = 'edit_user';
            }
            break;
        case 'delete_user':
            $user = User::list_by_id($var['user_id']);
            if ($user->delete()) {
                $app->reload();
            }
            break;
    }
}
Example #16
0
<?php

$ci =& get_instance();
$usr = new User();
$usr->get_by_id($ci->input->post('id'));
$usr->name = $ci->input->post('name');
$usr->level = $ci->input->post('level');
$usr->set_password($ci->input->post('password'));
$usr->email = $ci->input->post('email');
$usr->save();
redirect($ci->app->app_url("viewusr"));
Example #17
0
     }
     if (strlen($_POST["password1"]) <= 5) {
         die("error_newpw_too_short");
     }
     $salt = mysql_fetch_object(mysql_query("SELECT `value` FROM `system` WHERE `name` = 'salt'"));
     $current_password = MD5($salt->value . $_POST["cpassword"]);
     $current_password_no_salt = MD5($_POST["cpassword"]);
     if ($current_password != $user->password and $current_password_no_salt != $user->password) {
         die("error_old_pw_incorrect");
     }
     $new_password = MD5($salt->value . $_POST["password1"]);
     $new_password_no_salt = MD5($_POST["password1"]);
     if ($new_password == $user->password or $new_password_no_salt == $user->password) {
         die("error_same_new_pw");
     }
     $user->set_password($_POST["password1"]);
     if (!isset($_REQUEST["inactive_user"])) {
         $user->set_last_seen("change_user_info:password");
     }
     die("done");
 case "edit_display_name":
     $query = mysql_query("SELECT * FROM `users`");
     while ($row = mysql_fetch_object($query)) {
         if (strtolower($row->display_name) == strtolower($_POST["display_name"])) {
             die("error_display_name_used");
         }
     }
     $user->set_display_name($_POST["display_name"]);
     if (!isset($_REQUEST["inactive_user"])) {
         $user->set_last_seen("change_user_info:display_name");
     }
Example #18
0
 protected function get_object($array)
 {
     $user = new User();
     $user->set_first_name(isset($array['first_name']) ? $array['first_name'] : null);
     $user->set_last_name(isset($array['last_name']) ? $array['last_name'] : null);
     $user->set_username(isset($array['username']) ? $array['username'] : null);
     $user->set_password(isset($array['password']) ? $array['password'] : null);
     $user->set_academic_year(isset($array['academic_year']) ? $array['academic_year'] : null);
     $user->set_term(isset($array['term']) ? $array['term'] : null);
     $user->set_major(isset($array['major']) ? $array['major'] : null);
     $user->set_level_code(isset($array['level_code']) ? $array['level_code'] : null);
     $user->set_degree(isset($array['degree']) ? $array['degree'] : null);
     $user->set_profile_photo(isset($array['profile_photo']) ? $array['profile_photo'] : null);
     $user->set_visibility(isset($array['visibility']) ? $array['visibility'] : 2);
     return $user;
 }
Example #19
0
function addUser()
{
    global $tool, $propertyForm;
    $newUser = new User();
    $tempInfo = array();
    $infoKey = array("full", "user", "password", "email");
    foreach ($infoKey as $index => $key) {
        $tempInfo[$key] = htmlspecialchars(trim($_POST[$key]), ENT_QUOTES);
    }
    //add slashes to these 2 to make sure it does not display wrongly
    $tempInfo[user] = addslashes($tempInfo[user]);
    $tempInfo[full] = addslashes($tempInfo[full]);
    //checks if the name is empty, if not set all the names and insert them
    if ($newUser->set_user_name($tempInfo[user])) {
        //set all the values to the query
        $newUser->set_full_name($tempInfo[full]);
        $newUser->set_password($tempInfo[password]);
        $newUser->set_email($tempInfo[email]);
        $newUser->set_user_type('local');
        //if the insert is sucessful reload the page with the new values
        if ($newUser->insert()) {
            $status = "success";
            echo "<script language='javascript'>LoadPage(\"configurations.php?action=userManage&mode=edit&add=" . $status . "\", 'settingsInfo');</script>";
            //echo "<meta http-equiv=\"REFRESH\" content=\"0;url=".$_SERVER['PHP_SELF']."?action=userManage&add=$status\">";
        } else {
            $propertyForm->error("Warning: Failed to add user. Reason: " . $newUser->get_error(), $_GET['ID']);
        }
    } else {
        $propertyForm->error("Warning: Failed to add user. Reason: " . $newUser->get_error(), $_GET['ID']);
    }
}
Example #20
0
 /**
  * Event handler: called when a user attemps to login.
  *
  * This function will check if the user exists in the LDAP directory and create it locally if it does not.
  *
  * @param array 'login', 'pass' and 'pass_md5'
  */
 function LoginAttempt(&$params)
 {
     global $localtimenow;
     global $Settings, $Hit, $evo_charset;
     // Check if LDAP is available:
     if (!function_exists('ldap_connect')) {
         $this->debug_log('This PHP installation does not support LDAP functions.');
         return false;
         // Login failed!
     }
     // Get ready to go through ALL LDAP Servers configured in the plugin:
     $search_sets = $this->Settings->get('search_sets');
     if (empty($search_sets)) {
         $this->debug_log('No LDAP servers have been configured in the LDAP plugin settings.');
         return false;
         // Login failed!
     }
     // Detect if we already have a local user with the same login:
     $UserCache =& get_Cache('UserCache');
     if ($local_User =& $UserCache->get_by_login($params['login'])) {
         $this->debug_log('User <b>' . $params['login'] . '</b> already exists locally. We will UPDATE it with the latest LDAP attibutes.');
         $update_mode = true;
         // Try to find a number of a search set which was used on successful logging previous time by current user:
         $user_search_set_num = intval($this->UserSettings->get('search_set_num', $local_User->ID));
         if ($user_search_set_num > 0 && isset($search_sets[$user_search_set_num])) {
             // We have found this, Reorder the array to use the successful set firstly:
             $success_search_set = $search_sets[$user_search_set_num];
             unset($search_sets[$user_search_set_num]);
             $search_sets = array($user_search_set_num => $success_search_set) + $search_sets;
         }
     } else {
         $update_mode = false;
     }
     $this->debug_log(sprintf('LDAP plugin will attempt to login with login=<b>%s</b> / pass=<b>%s</b> / MD5 pass=<b>%s</b>', $params['login'], $params['pass'], $params['pass_md5']));
     // ------ Loop through list of configured LDAP Servers: ------
     foreach ($search_sets as $l_id => $l_set) {
         $this->debug_log('Step 1 : STARTING LDAP AUTH WITH SERVER #' . $l_id);
         // --- CONNECT TO SERVER ---
         $server_port = explode(':', $l_set['server']);
         $server = $server_port[0];
         $port = isset($server_port[1]) ? $server_port[1] : 389;
         if (!empty($l_set['disabled'])) {
             $this->debug_log('Skipping disabled LDAP server &laquo;' . $server . ':' . $port . '&raquo;!');
             continue;
         }
         if (!($ldap_conn = @ldap_connect($server, $port))) {
             $this->debug_log('Could not connect to LDAP server &laquo;' . $server . ':' . $port . '&raquo;!');
             continue;
         }
         $this->debug_log('Connected to server &laquo;' . $server . ':' . $port . '&raquo;..');
         $ldap_rdn = str_replace('%s', $params['login'], $l_set['rdn']);
         $this->debug_log('Using RDN &laquo;' . $ldap_rdn . '&raquo; for binding...');
         // --- SET PROTOCOL VERSION ---
         // Get protocol version to use:
         if (!ldap_get_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $initial_protocol_version)) {
             $this->debug_log('Failed to get LDAP_OPT_PROTOCOL_VERSION.');
             $initial_protocol_version = null;
         }
         $protocol_version = isset($l_set['protocol_version']) ? $l_set['protocol_version'] : 'auto';
         // new setting in 2.01
         if ($protocol_version[0] == 'v') {
             // transform "vX" => "X"
             $try_versions = array(substr($protocol_version, 1));
         } else {
             // "auto"
             $try_versions = array(3, 2);
             if (isset($initial_protocol_version)) {
                 array_unshift($try_versions, $initial_protocol_version);
             }
             $try_versions = array_unique($try_versions);
         }
         $this->debug_log('We will try protocol versions: ' . implode(', ', $try_versions));
         // --- VERIFY USER CREDENTIALS BY BINDING TO SERVER ---
         // you might use this for testing with Apache DS: if( !@ldap_bind($ldap_conn, 'uid=admin,ou=system', 'secret') )
         // Bind:
         $bound = false;
         $bind_errors = array();
         foreach ($try_versions as $try_version) {
             $this->debug_log(sprintf('Trying to connect with protocol version: %s / RDN: %s / pass: %s', $try_version, $ldap_rdn, $params['pass']));
             ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $try_version);
             if (@ldap_bind($ldap_conn, $ldap_rdn, $params['pass'])) {
                 // Success
                 $this->debug_log('Binding worked.');
                 $bound = true;
                 break;
             } else {
                 $this->debug_log('Binding failed. Errno: ' . ldap_errno($ldap_conn) . ' Error: ' . ldap_error($ldap_conn));
             }
         }
         if (!$bound) {
             if (isset($initial_protocol_version)) {
                 // Reset this for the next search set:
                 ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $initial_protocol_version);
             }
             continue;
         }
         $this->debug_log('User successfully bound to server.');
         // --- STEP 2 : TRY TO OBTAIN MORE INFO ABOUT USER ---
         // Search user info
         $filter = str_replace('%s', $params['login'], $l_set['search_filter']);
         $this->debug_log(sprintf('Step 2 : Now querying for additional user info. base_dn: <b>%s</b>, filter: <b>%s</b>', $l_set['base_dn'], $filter));
         $search_result = @ldap_search($ldap_conn, $l_set['base_dn'], $filter);
         if (!$search_result) {
             // this may happen with an empty base_dn
             $this->debug_log('Invalid ldap_search result. Skipping to next search set. Errno: ' . ldap_errno($ldap_conn) . ' Error: ' . ldap_error($ldap_conn));
             continue;
         }
         $search_info = ldap_get_entries($ldap_conn, $search_result);
         //$this->debug_log( 'Results returned by LDAP Server: <pre>'.var_export( $search_info, true ).'</pre>' );
         if ($search_info['count'] != 1) {
             // We have found 0 or more than 1 users, which is a problem...
             $this->debug_log('# of entries found with search: ' . $search_info['count'] . ' - Skipping...');
             /*
             for ($i=0; $i<$search_info["count"]; $i++) {
             	echo "dn: ". $search_info[$i]["dn"] ."<br>";
             	echo "first cn entry: ". $search_info[$i]["cn"][0] ."<br>";
             	echo "first email entry: ". $search_info[$i]["mail"][0] ."<p>";
             }
             */
             continue;
         }
         $this->debug_log('User info has been found.');
         // --- CREATE OR UPDATE USER ACCOUNT IN B2EVO ---
         if ($update_mode == false) {
             $this->debug_log('Step 3 : Creating a local user in b2evolution...');
             $local_User = new User();
             $local_User->set('login', $params['login']);
             $local_User->set('locale', locale_from_httpaccept());
             // use the browser's locale
             $local_User->set_datecreated($localtimenow);
             // $local_User->set( 'level', 1 );
         } else {
             // User exists already exists
             $this->debug_log('Step 3 : Updating the existing local user.');
         }
         $this->debug_log('Randomize password in b2evolution DB and autoactivate user.');
         // Generate a random password (we never want LDAP users to be able to login without a prior LDAP check) (also on update, just in case...
         $local_User->set_password(generate_random_passwd(32));
         // $params['pass'] );
         $local_User->set('status', 'autoactivated');
         // Activate the user automatically (no email activation necessary)
         // Convert each input string to current server encoding:
         $exclude_encoding_fields = array('uid', 'mail', 'jpegphoto');
         if (isset($search_info[0]) && is_array($search_info[0])) {
             foreach ($search_info[0] as $search_info_key => $search_info_data) {
                 if (isset($search_info_data[0]) && is_string($search_info_data[0]) && !in_array($search_info_key, $exclude_encoding_fields)) {
                     // Convert string from LDAP server encoding to current server encoding:
                     $search_info[0][$search_info_key][0] = convert_charset($search_info_data[0], $l_set['encoding'], $evo_charset);
                 }
             }
         }
         // Make some updates:
         // mail -> email:
         if (isset($search_info[0]['mail'][0])) {
             $local_User->set_email($search_info[0]['mail'][0]);
         }
         // uid -> nickname
         if (isset($search_info[0]['uid'][0])) {
             $this->debug_log('UID: <b>' . $search_info[0]['uid'][0] . '</b>');
             $local_User->set('nickname', $search_info[0]['uid'][0]);
         } else {
             // if not found, use login.
             $local_User->set('nickname', $params['login']);
         }
         // givenname -> Firstname:
         if (isset($search_info[0]['givenname'][0])) {
             $this->debug_log('First name (givenname): <b>' . $search_info[0]['givenname'][0] . '</b>');
             $local_User->set('firstname', $search_info[0]['givenname'][0]);
         }
         // sn -> Lastname:
         if (isset($search_info[0]['sn'][0])) {
             $this->debug_log('Last name (sn): <b>' . $search_info[0]['sn'][0] . '</b>');
             $local_User->set('lastname', $search_info[0]['sn'][0]);
         }
         // roomnumber -> user field "roomnumber" (if not found, autocreate it in group "Address")
         if (isset($search_info[0]['roomnumber'][0])) {
             $this->debug_log('Room number: <b>' . $search_info[0]['roomnumber'][0] . '</b>');
             $this->userfield_update_by_code($local_User, 'roomnumber', $search_info[0]['roomnumber'][0], 'Address', 'Room Number', 'word');
         }
         // businesscategory -> user field "businesscategory" (if not found, autocreate it in group "About me")
         if (isset($search_info[0]['businesscategory'][0])) {
             $this->debug_log('Business Category: <b>' . $search_info[0]['businesscategory'][0] . '</b>');
             $this->userfield_update_by_code($local_User, 'businesscategory', $search_info[0]['businesscategory'][0], 'About me', 'Business Category', 'text');
         }
         // telephonenumber -> user field "officephone" (if not found, autocreate it in group "Phone")
         if (isset($search_info[0]['telephonenumber'][0])) {
             $this->debug_log('Office phone: <b>' . $search_info[0]['telephonenumber'][0] . '</b>');
             $this->userfield_update_by_code($local_User, 'officephone', $search_info[0]['telephonenumber'][0], 'Phone', 'Office phone', 'phone');
         }
         // mobile -> user field "cellphone" (if not found, autocreate it in group "Phone")
         if (isset($search_info[0]['mobile'][0])) {
             $this->debug_log('Cell phone: <b>' . $search_info[0]['mobile'][0] . '</b>');
             $this->userfield_update_by_code($local_User, 'cellphone', $search_info[0]['mobile'][0], 'Phone', 'Cell phone', 'phone');
         }
         // employeenumber -> user field "employeenumber" (if not found, autocreate it in group "About me")
         if (isset($search_info[0]['employeenumber'][0])) {
             $this->debug_log('Employee number: <b>' . $search_info[0]['employeenumber'][0] . '</b>');
             $this->userfield_update_by_code($local_User, 'employeenumber', $search_info[0]['employeenumber'][0], 'About me', 'Employee number', 'word');
         }
         // title -> user field "title" (if not found, autocreate it in group "About me")
         if (isset($search_info[0]['title'][0])) {
             $this->debug_log('Title: <b>' . $search_info[0]['title'][0] . '</b>');
             $this->userfield_update_by_code($local_User, 'title', $search_info[0]['title'][0], 'About me', 'Title', 'word');
             $userfield_title = $search_info[0]['title'][0];
             // Use this as role for all organizations below
         } else {
             $userfield_title = '';
         }
         // departmentnumber -> join Organization with the same name (create if doesn't exist)
         if (isset($search_info[0]['departmentnumber'][0])) {
             $this->debug_log('Department Number: <b>' . $search_info[0]['departmentnumber'][0] . '</b>');
             $this->userorg_update_by_name($local_User, $search_info[0]['departmentnumber'][0], $userfield_title);
         }
         // o -> join Organization with the same name (create if doesn't exist)
         if (isset($search_info[0]['o'][0])) {
             $this->debug_log('Organization: <b>' . $search_info[0]['o'][0] . '</b>');
             $this->userorg_update_by_name($local_User, $search_info[0]['o'][0], $userfield_title);
         }
         // telexnumber -> user field "officefax" (if not found, autocreate it in group "Phone")
         if (isset($search_info[0]['telexnumber'][0])) {
             $this->debug_log('Office FAX: <b>' . $search_info[0]['telexnumber'][0] . '</b>');
             $this->userfield_update_by_code($local_User, 'officefax', $search_info[0]['telexnumber'][0], 'Phone', 'Office FAX', 'phone');
         }
         // ---- GROUP STUFF ----
         if ($update_mode == true) {
             // Updating existing user
             $this->debug_log('Updating existing user: we do NOT touch the primary group.');
             $local_User->dbupdate();
             $this->debug_log('OK -- User has been updated.');
         } else {
             // Try to assign prilary group from the search results:
             $assigned_group = false;
             if (!empty($l_set['assign_user_to_group_by'])) {
                 $this->debug_log('Plugin is configured to assign the Primary Group by the ' . $l_set['assign_user_to_group_by'] . ' key...');
                 if (isset($search_info[0][$l_set['assign_user_to_group_by']]) && isset($search_info[0][$l_set['assign_user_to_group_by']][0])) {
                     // There is info we want to assign by
                     $assign_by_value = $search_info[0][$l_set['assign_user_to_group_by']][0];
                     $this->debug_log('User info says has ' . $l_set['assign_user_to_group_by'] . ' = "<b>' . $assign_by_value . '</b>"');
                     $GroupCache =& get_Cache('GroupCache');
                     if ($users_Group =& $GroupCache->get_by_name($assign_by_value, false)) {
                         // A group with the users value returned exists.
                         $local_User->set_Group($users_Group);
                         $assigned_group = true;
                         $this->debug_log('Assigning User to existing Primary Group.');
                     } else {
                         $this->debug_log('Group with that name does not exist...');
                         if ($new_Group =& $this->usergroup_create($l_set['tpl_new_grp_ID'], $assign_by_value)) {
                             // Link the user to new created group:
                             $local_User->set_Group($new_Group);
                             $assigned_group = true;
                             $this->debug_log('Assigned User to new Primary Group.');
                         }
                     }
                 }
             }
             if (!$assigned_group) {
                 // Default group:
                 $this->debug_log('Falling back to default primary group...');
                 $users_Group = NULL;
                 $fallback_grp_ID = $this->Settings->get('fallback_grp_ID');
                 if (empty($fallback_grp_ID)) {
                     $this->debug_log('No default/fallback primary group configured.');
                     $this->debug_log('User NOT created, try next LDAP server...');
                     //Continue to next LDAP server:
                     continue;
                 } else {
                     $GroupCache =& get_Cache('GroupCache');
                     $users_Group =& $GroupCache->get_by_ID($fallback_grp_ID);
                     if ($users_Group) {
                         // either $this->default_group_name is not given or wrong
                         $local_User->set_Group($users_Group);
                         $assigned_group = true;
                         $this->debug_log('Using default/fallback primary group: <b>' . $users_Group->get('name') . '</b>');
                     } else {
                         $this->debug_log('Default/fallback primary group does not exist (' . $fallback_grp_ID . ').');
                         $this->debug_log('User NOT created, try next LDAP server...');
                         //Continue to next LDAP server:
                         continue;
                     }
                 }
             }
             $local_User->dbinsert();
             $UserCache->add($local_User);
             $this->debug_log('OK -- User has been created.');
         }
         // Remember this settings number in order use this first in next logging time by current user:
         $this->UserSettings->set('search_set_num', $l_id, $local_User->ID);
         $this->UserSettings->dbupdate();
         // Assign user to organizations:
         $this->userorg_assign_to_user($local_User);
         // jpegphoto -> Save as profile pictue "ldap.jpeg" and associate with user
         if (isset($search_info[0]['jpegphoto'][0])) {
             $this->debug_log('Photo: <img src="data:image/jpeg;base64,' . base64_encode($search_info[0]['jpegphoto'][0]) . '" />');
             // Save to disk and attach to user:
             $this->userimg_attach_photo($local_User, $search_info[0]['jpegphoto'][0], !empty($l_set['expand_pics']));
         }
         // --- EXTRA GROUPS ---
         if (!empty($l_set['secondary_grp_search_filter'])) {
             global $app_version;
             if (evo_version_compare($app_version, '6.7.0-alpha') < 0) {
                 // The plugin is used on b2evo 6.6
                 $this->debug_log('Secondary groups not handled. This feature requires b2evolution v6.7.0-alpha or newer.');
             } elseif (empty($l_set['secondary_grp_name_attribute'])) {
                 $this->debug_log('Missing name attribute for secondary groups');
             } else {
                 $filter = str_replace('%s', $params['login'], $l_set['secondary_grp_search_filter']);
                 $grp_name_attribute = $l_set['secondary_grp_name_attribute'];
                 $this->debug_log(sprintf('Step 4 : Now querying for secondary groups. base_dn: <b>%s</b>, filter: <b>%s</b>, name attribue=<b>%s</b>', $l_set['secondary_grp_base_dn'], $filter, $grp_name_attribute));
                 $search_result = @ldap_search($ldap_conn, $l_set['secondary_grp_base_dn'], $filter, array($grp_name_attribute));
                 if (!$search_result) {
                     // this may happen with an empty base_dn
                     $this->debug_log('Invalid ldap_search result. No secondary groups will be assigned. Errno: ' . ldap_errno($ldap_conn) . ' Error: ' . ldap_error($ldap_conn));
                 } else {
                     $search_info = ldap_get_entries($ldap_conn, $search_result);
                     // $this->debug_log( 'Results returned by LDAP Server: <pre>'.var_export( $search_info, true ).'</pre>' );
                     $secondary_groups = array();
                     // $this->debug_log( 'Secondary groups name prefix: <pre>'.var_export( $l_set['secondary_grp_name_prefix'], true ).'</pre>' );
                     // Walk through results:
                     foreach ($search_info as $group_candidate) {
                         if (is_array($group_candidate) && isset($group_candidate[$grp_name_attribute][0])) {
                             $group_candidate_cn = $group_candidate[$grp_name_attribute][0];
                             if (empty($l_set['secondary_grp_name_prefix']) || strpos($group_candidate_cn, $l_set['secondary_grp_name_prefix']) === 0) {
                                 // prefix is ok
                                 $this->debug_log('Accepted Secondary Group: ' . $group_candidate_cn);
                                 $secondary_groups[] = $group_candidate_cn;
                             } else {
                                 // prefix is NOT ok
                                 $this->debug_log('REJECTED Secondary Group: ' . $group_candidate_cn);
                             }
                         }
                     }
                     // Hardcode two secondary groups:
                     // $secondary_groups = array( 'Blog B members', 'Blog D Members' );
                     $this->debug_log('Secondary groups to be assigned: <pre>' . var_export($secondary_groups, true) . '</pre>');
                     // Update secondary groups for the User:
                     $this->usersecgroup_update($local_User, $secondary_groups, $l_set['tpl_new_secondary_grp_ID']);
                 }
             }
         }
         if (isset($initial_protocol_version)) {
             ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $initial_protocol_version);
         }
         // --- CONSIDER THE LOGIN ATTEMPT TO BE SUCCESSFUL AND WE ACCEPT IT ---
         // Update this value which has been passed by REFERENCE:
         $params['pass_ok'] = true;
         return true;
         // Login was a success (but return "true" does not trigger anything special in b2evolution)
     }
     if (isset($initial_protocol_version)) {
         ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $initial_protocol_version);
     }
     return false;
     // Login failed!
 }
Example #21
0
 /**
  * @throws UserIDMissingException
  */
 public static function change_password()
 {
     if ($_GET['id']) {
         if ($_GET['nextpage'] == 1) {
             if ($_POST['password']) {
                 $page_1_passed = true;
             } else {
                 $page_1_passed = false;
                 $error = "You must enter a new password.";
             }
         } elseif ($_GET['nextpage'] > 1) {
             $page_1_passed = true;
         } else {
             $page_1_passed = false;
             $error = "";
         }
         if ($page_1_passed == false) {
             $template = new HTMLTemplate("base/user/admin/user/change_password.html");
             $paramquery = $_GET;
             $paramquery['nextpage'] = "1";
             $params = http_build_query($paramquery, '', '&#38;');
             $template->set_var("params", $params);
             $template->set_var("error", $error);
             $template->output();
         } else {
             $user = new User($_GET['id']);
             $paramquery = $_GET;
             $paramquery['action'] = "detail";
             unset($paramquery['nextpage']);
             $params = http_build_query($paramquery, '', '&#38;');
             if ($user->set_password($_POST['password'])) {
                 Common_IO::step_proceed($params, "Set New Password", "Operation Successful", null);
             } else {
                 Common_IO::step_proceed($params, "Set New Password", "Operation Failed", null);
             }
         }
     } else {
         throw new UserIDMissingException();
     }
 }
Example #22
0
 /**
  * @see AuthInterface::forgot_password()
  * @param string $username
  * @param string $name
  * @return bool
  */
 public function forgot_password($username, $mail)
 {
     if ($username and $mail) {
         $system_log = new SystemLog(null);
         if (User::exist_username($username)) {
             $user_id = User::get_user_id_by_username($username);
             $user = new User($user_id);
             if ($user->check_mail(strtolower($mail))) {
                 if ($user->get_boolean_user_entry("user_inactive") == false) {
                     $new_password = User::generate_password();
                     $mail = new Mail();
                     $mail->set_recipient($user_id);
                     $mail->set_subject("Your New Open-LIMS Password");
                     $mail->set_text("Your new password: "******"must_change_password", true);
                         // Password sended successfully
                         $system_log->create($user_id, 1, 1, "Password Send", "Forgot Password", "auth.php", null, null);
                         return true;
                     } else {
                         // Error via sending
                         throw new AuthForgotPasswordSendFailedException("", 0);
                     }
                 } else {
                     // Inactive User
                     $system_log->create($user_id, 1, 1, "Inactive User", "Forgot Password", "auth.php", null, null);
                     throw new AuthUserNotFoundException("", 0);
                 }
             } else {
                 // Wrong E-Mail
                 $system_log->create($user_id, 1, 0, "Wrong E-Mail", "Forgot Password", "auth.php", null, null);
                 throw new AuthUserNotFoundException("", 0);
             }
         } else {
             // User Not Found
             $system_log->create(null, 1, 0, "User \"" . $username . "\" Not Found", "Forgot Password", "auth.php", null, null);
             throw new AuthUserNotFoundException("", 0);
         }
     } else {
         throw new AuthUserNotFoundException("", 0);
     }
 }
Example #23
0
function changePass()
{
    global $propertyForm;
    $oldpass = $_POST[oldpass];
    $newpass1 = $_POST[newpass1];
    $newpass2 = $_POST[newpass2];
    $status == false;
    $user_id = $_SESSION[userid];
    $user_name = $_SESSION[username];
    $user = new User($user_id);
    if (empty($oldpass)) {
        $error = "Old password is empty<br>";
    } elseif (empty($newpass1)) {
        $error = "new password is empty<br>";
    } elseif (empty($newpass2)) {
        $error = "new password (confirm) is empty<br>";
    } elseif ($newpass2 != $newpass1) {
        $error = "new password are not the same<br>";
    } elseif (!$user->is_local_user($user_name, 'local')) {
        $error = "Sorry you're not a local user so can not change your password<br>\n\t\t\tYou are probably an LDAP user. Please contact your admin<br>";
    } elseif (!$user->authenticate_user($user_name, $oldpass)) {
        $error = "Old password incorrect<br>";
    } elseif (!$user->set_password($newpass1)) {
        $error = $user->get_error();
    } elseif (!$user->update()) {
        $error = $user->get_error();
        return false;
    } else {
        $status = "success";
    }
    if ($status == "success") {
        echo "<script language='javascript'>LoadPage(\"userSettings.php?action=widgetsManagement&mode=edit&update=" . $status . "\", 'settingsInfo');</script>";
    } else {
        $propertyForm->warning("Warning: Failed to update password. Reason: " . $error);
    }
}