PHP Method User::find_by_username, codiad Code Examples

This page contains top rated real world PHP examples of method User::find_by_username from package codiad extracted from open source projects. You can rate examples to help us improve the quality of examples
Example #1
Show file File: Forgot_pass.php Project: samoldenburg/Stepmania-Leaderboards
0
 public function index()
 {
     if ($this->input->post()) {
         if (empty($this->input->post('username'))) {
             $this->content_view = "forgot_pass/index";
         } else {
             $user_to_reset = User::find_by_username($this->input->post('username'));
             $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
             $randstring = '';
             for ($i = 0; $i < 16; $i++) {
                 $randstring .= $characters[rand(0, strlen($characters))];
             }
             $user_to_reset->pass_key = $randstring;
             $user_to_reset->save();
             $link = "http://" . $_SERVER['HTTP_HOST'] . "/forgot_pass/reset_pass/" . $randstring;
             $email_content = "A password reset has been requested for your account. If you did not request this reset please disregard this message. Otherwise, open the link below to continue.<br /><a href=" . $link . ">" . $link . "</a>";
             $config = array('protocol' => 'sendmail', 'mailtype' => 'html', 'charset' => 'utf-8', 'wordwrap' => TRUE);
             $this->load->library('email', $config);
             $this->email->from('noreply@smleaderboards.net', 'Stepmania Leaderboards');
             $this->email->to($user_to_reset->email);
             $this->email->subject('Stepmania Leaderboards - Password Recovery');
             $this->email->message($email_content);
             $this->email->send();
             $this->content_view = "forgot_pass/recover_confirm";
         }
     } else {
         $this->content_view = "forgot_pass/index";
     }
 }
Example #2
Show file File: user.php Project: xetorthio/pearfarm_channel_server
0
 public static function authenticate($username, $password)
 {
     $user = User::find_by_username($username);
     if (!$user->active) {
         return false;
     }
     $hashed_password = static::hash_password($password, $user->salt);
     return $hashed_password === $user->password;
 }
Example #3
Show file File: UserTest.php Project: scottdavis/pearfarm_channel_server
0
 public function testMakesApiKey()
 {
     $user = User::create(array('username' => 'bobby', 'email' => 'foo@mail.com', 'password' => 'foo'));
     $api = $user->api_key;
     $user->active = 1;
     $user->save();
     $user2 = User::find_by_username('bobby');
     $this->assertEquals($api, $user2->api_key);
 }
Example #4
Show file File: UsersController.php Project: rajeshpillai/rugby-mvc
0
 function show($id)
 {
     $user = User::find($id);
     $all = User::find_by_username("rajesh");
     $allu = User::find_by_username_and_email("rajesh", "pillai.rajesh@gmail.com");
     ActiveRecord::println($all);
     ActiveRecord::println($allu);
     return $this->View(array('view' => 'show', 'model' => $user));
 }
Example #5
Show file File: login_controller.php Project: boulama/DreamVids
0
 public function create($request)
 {
     $data = $request->getParameters();
     if (isset($data['submitLogin']) && !Session::isActive()) {
         $is_admin = isset($data['is_admin']) && $data['is_admin'] == 1;
         $username = Utils::secure($data['username']);
         $password = Utils::secure($data['pass']);
         if (User::find_by_username($username)) {
             $user = User::find_by_username($username);
             $current_log_fail = $user->getLogFails();
             if (!$user->isAllowedToAttemptLogin()) {
                 $next_timestamp = $current_log_fail['next_try'];
                 $last_try_timestamp = $current_log_fail['last_try'];
                 $nb_try = $current_log_fail['nb_try'];
                 $next_try_tps = $next_timestamp - Utils::tps();
                 $next_try_min = floor($next_try_tps / 60);
                 $next_try_sec = round($next_try_tps - $next_try_min * 60);
                 $next_try_str = "{$next_try_min} m et {$next_try_sec} s";
                 $data = isset($data['redirect']) ? ['redirect' => $data['redirect']] : [];
                 $data['currentPageTitle'] = 'Connexion';
                 $response = !$is_admin ? new ViewResponse('login/login', $data) : new ViewResponse('admin/login/login', $data, true, 'layouts/admin_login.php', 401);
                 $response->addMessage(ViewMessage::error($nb_try . " tentatives de connexions à la suite pour ce compte. Veuillez patienter {$next_try_str}"));
                 return $response;
             }
             $realPass = User::find_by_username($username)->getPassword();
             if (password_verify($password, $realPass)) {
                 User::connect($username, 1);
                 $user->resetLogFails();
                 return new RedirectResponse($data['redirect'] ? urldecode($data['redirect']) : WEBROOT);
             } else {
                 if (sha1($password) == $realPass) {
                     $user->resetLogFails();
                     User::connect($username, 1)->setPassword(password_hash($password, PASSWORD_BCRYPT));
                     return new RedirectResponse($data['redirect'] ? urldecode($data['redirect']) : WEBROOT);
                 }
                 if (!$user->isIntervalBetweenTwoLogAttemptElapsed() || !$current_log_fail) {
                     $user->addLogFail();
                 } else {
                     $user->resetLogFails();
                     $user->addLogFail();
                 }
                 $data = isset($data['redirect']) ? ['redirect' => $data['redirect']] : [];
                 $data['currentPageTitle'] = 'Connexion';
                 $response = !$is_admin ? new ViewResponse('login/login', $data) : new ViewResponse('admin/login/login', $data, true, 'layouts/admin_login.php', 401);
                 $response->addMessage(ViewMessage::error('Mot de passe incorrect'));
                 return $response;
             }
         } else {
             $data = isset($data['redirect']) ? ['redirect' => $data['redirect']] : [];
             $data['currentPageTitle'] = 'Connexion';
             $response = !$is_admin ? new ViewResponse('login/login', $data) : new ViewResponse('admin/login/login', $data, true, 'layouts/admin_login.php', 401);
             $response->addMessage(ViewMessage::error('Ce nom d\'utilisateur n\'existe pas'));
             return $response;
         }
     }
 }
Example #6
Show file File: user.php Project: csiber/CodeIgniter-Starter
0
 public static function validate_login($username, $password)
 {
     $user = User::find_by_username($username, array('active' => 1));
     if ($user && $user->validate_password($password)) {
         User::login($user->id);
         return $user;
     } else {
         return FALSE;
     }
 }
Example #7
Show file File: VersionControllerTest.php Project: xetorthio/pearfarm_channel_server
0
 public function testDeleteBobsPackage()
 {
     $_SERVER['SERVER_NAME'] = 'bob.localhost.com';
     $count = Version::count();
     $p = Package::find_by_name('bobs_other_package');
     $v = Version::find('first', array('package_id' => $p->id, 'version' => '0.0.1'));
     $this->delete('delete', array(), array('id' => $v->package_id, 'version' => $v->id), array('user' => User::find_by_username('bob')->id));
     $this->assertEquals($count - 1, Version::count(array('cache' => false)));
     $this->assertFalse(Version::exists('id', $v->id));
     $this->assertRedirect(url_for('PackageController', 'show', $p->id));
 }
Example #8
Show file File: FileUploadTest.php Project: scottdavis/pearfarm_channel_server
0
 public function testUploadFailbadSig()
 {
     $localfile = FileUtils::join(NIMBLE_ROOT, 'test', 'data', 'joes_other_package-1.0.4.tgz');
     $sig = PackageVerifyTest::calculatePackageSignature($localfile);
     $user = User::find_by_username('joe');
     try {
         $p = Package::from_upload(array('file' => $localfile, 'sig' => $sig, 'user' => $user), true);
     } catch (NimbleException $e) {
         $this->assertEquals("Invalid package signature", $e->getMessage());
     }
 }
Example #9
Show file File: ChannelControllerTest.php Project: scottdavis/pearfarm_channel_server
0
 public function testUploadHtmlFailsnoFile()
 {
     $localfile = FileUtils::join(NIMBLE_ROOT, 'test', 'data', 'bobs_other_package-1.0.4.tgz');
     $_FILES = array();
     $_FILES['file'] = array();
     $_FILES['file']['tmp_name'] = '';
     $key = md5(time());
     $this->post('upload', array(), array('upload_key' => $key), array('upload_key' => md5(md5(time())), 'user' => User::find_by_username('bob')->id), 'html');
     $this->assertEquals($_SESSION['flashes']['notice'], 'Package channel  does not match bob.localhost.com');
     $this->assertRedirect(url_for('LandingController', 'user_index', User::find_by_username('bob')->username));
 }
Example #10
Show file File: PackageControllerTest.php Project: scottdavis/pearfarm_channel_server
0
 public function testDeleteBobsPackage()
 {
     $_SERVER['SERVER_NAME'] = 'bob.localhost.com';
     $count = Package::count();
     $v_count = Version::count();
     $p = Package::find_by_name('bobs_other_package');
     $versions = $p->count('versions');
     $this->delete('delete', array(), array('id' => $p->id), array('user' => User::find_by_username('bob')->id));
     $this->assertEquals($count - 1, Package::count(array('cache' => false)));
     $this->assertEquals($v_count - $versions, Version::count(array('cache' => false)));
     $this->assertRedirect('/');
 }
Example #11
Show file File: reset_token_functions.php Project: kamy333/rajah
0
function email_reset_token_username($username)
{
    //	$user = find_one_in_fake_db('users', 'username', sql_prep($username));
    $user = User::find_by_username($username);
    if ($user) {
        // This is where you would connect to your emailer
        // and send an email with a URL that includes the token.
        $user->send_email();
        return true;
    } else {
        return false;
    }
}
Example #12
Show file File: login_form.php Project: epochwolf/kairos
0
 public function validate()
 {
     $this->create_inital_user();
     $this->error_if_empty("username");
     $this->error_if_empty("password");
     $this->user = User::find_by_username($this->params["username"]);
     if ($this->user) {
         if ($this->user->check_password($this->params["password"])) {
             return true;
         } else {
             $this->add_error("password", "Invalid password");
         }
     } else {
         $this->add_error("username", "Invalid username");
     }
     return false;
 }
Example #13
Show file File: version_controller.php Project: scottdavis/pearfarm_channel_server
0
 public function show()
 {
     if ($this->is_logged_in()) {
         $this->login_user();
     }
     try {
         $user = User::find_by_username($_GET['username']);
         $this->package = Package::find('first', array('conditions' => array('user_id' => $user->id, 'name' => $_GET['package_name'])));
         $this->version = Version::find('first', array('conditions' => array('package_id' => $this->package->id, 'version' => $_GET['version'])));
         $this->title = $this->package->name . ' ' . $this->version->version;
         Nimble::set_title($this->title);
         $this->data = unserialize($this->version->meta);
     } catch (NimbleRecordNotFound $e) {
         Nimble::flash('notice', 'Version does not exist');
         $this->redirect_to('/');
     }
 }
Example #14
Show file File: package_controller.php Project: scottdavis/pearfarm_channel_server
0
 public function show()
 {
     try {
         $user = User::find_by_username($_GET['username']);
         switch ($this->format) {
             case 'xml':
                 $this->header('Content-Type: text/xml', 200);
                 $this->package = Package::find('first', array('conditions' => array('user_id' => $user->id, 'name' => $_GET['package_name'])));
                 echo $this->package->to_xml();
                 $this->layout = false;
                 $this->has_rendered = true;
                 break;
             case 'json':
                 $this->header('Content-type: application/json', 200);
                 $this->package = Package::find('first', array('conditions' => array('user_id' => $user->id, 'name' => $_GET['package_name'])));
                 echo $this->package->to_json();
                 $this->layout = false;
                 $this->has_rendered = true;
                 break;
             default:
                 if ($this->is_logged_in()) {
                     $this->login_user();
                 }
                 try {
                     $this->set_default_side_bar();
                     $this->package = Package::find('first', array('conditions' => array('user_id' => $user->id, 'name' => $_GET['package_name'])));
                     $this->title = $this->package->name;
                     Nimble::Set_title($this->title);
                     $this->versions = Version::find_all(array('limit' => '0,5', 'conditions' => array('package_id' => $this->package->id), 'order' => 'version DESC'));
                     $this->total_versions = $this->package->count('versions');
                     $this->version = $this->package->current_version();
                     if ($this->version !== false) {
                         $this->data = unserialize($this->version->meta);
                     }
                 } catch (NimbleRecordNotFound $e) {
                     Nimble::flash('notice', 'The package you were looking for does not exsist');
                     $this->redirect_to('/');
                 }
                 break;
         }
     } catch (NimbleRecordNotFound $e) {
         Nimble::flash('notice', 'The package you were looking for does not exsist');
         $this->redirect_to('/');
     }
 }
Example #15
Show file File: login_controller.php Project: scottdavis/pearfarm_channel_server
0
 public function login()
 {
     $this->title = 'Login';
     Nimble::set_title($this->title);
     try {
         if (isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && User::authenticate($_POST['username'], $_POST['password'])) {
             $user = User::find_by_username($_POST['username']);
             $_SESSION['user'] = $user->id;
             $this->redirect_if_logged_in();
         } else {
             Nimble::flash('notice', 'Invalid Login Information');
             $this->render('login/form.php');
         }
     } catch (NimbleRecordNotFound $e) {
         Nimble::flash('notice', 'Invalid Login Information');
         $this->render('login/form.php');
     }
 }
Example #16
Show file File: User.php Project: samoldenburg/Stepmania-Leaderboards
0
 /**
  * Determine login data
  */
 public static function validate_login($username, $password)
 {
     // Get User record
     $this_user = User::find_by_username($username);
     if (empty($this_user)) {
         return false;
     }
     // Set up variables
     $hashed_password = $this_user->password;
     $salt = $this_user->salt;
     $user_input = $password . $salt;
     // Do validation
     if (hash_equals($hashed_password, crypt($user_input, $hashed_password))) {
         return true;
     } else {
         return false;
     }
 }
Example #17
Show file File: Login.php Project: samoldenburg/Stepmania-Leaderboards
0
 public function index()
 {
     if ($_POST) {
         $username = $this->input->post('login_username');
         $password = $this->input->post('login_pass');
         $valid_login = User::validate_login($username, $password);
         if ($valid_login) {
             $this_user = User::find_by_username($username);
             $user_level = Usermeta::get_user_level($this_user->id);
             $session_data = array('user_id' => $this_user->id, 'username' => $this_user->username, 'password' => $this_user->password, 'email' => $this_user->email, 'display_name' => $this_user->display_name, 'user_level' => $user_level, 'chat_color' => get_chat_color(intval($user_level)), 'redirect' => $this->session->userdata('redirect'));
             $this->session->set_userdata($session_data);
             redirect($this->session->userdata('redirect'));
         } else {
             $this->content_view = 'login_error';
         }
     } else {
         redirect('home');
     }
 }
Example #18
Show file File: users_controller.php Project: Hield/imagesharing
0
 public function favorites()
 {
     $username = Request::get_id();
     $user = User::find_by_username($username);
     if (empty($user)) {
         redirect_to('pages', 'error');
     }
     $check = true;
     if (!isset($_SESSION['username'])) {
         $check = false;
     } else {
         if ($username != $_SESSION['username']) {
             $check = false;
         }
     }
     require_once 'models/image.php';
     $images = Image::find_by_favorite($user->id);
     require_once 'views/users/favorites.php';
 }
Example #19
Show file File: file_logger.php Project: scottdavis/pearfarm_channel_server
0
function doPackage($file_name)
{
    global $fp;
    $path = explode(DIRECTORY_SEPARATOR, $file_name);
    $file = array_pop($path);
    $username = array_pop($path);
    $package_split = explode('-', $file);
    $name = $package_split[0];
    try {
        $user = User::find_by_username($username);
        $package = Package::find('first', array('conditions' => array('user_id' => $user->id, 'name' => $name)));
        $current = (int) $package->num_downloads;
        $package->num_downloads = $current + 1;
        $package->save();
    } catch (Exception $e) {
        fwrite($fp, NIMBLE_ENV . " log failed\n" . $e->getMessage() . "\n");
        return;
    }
}
Example #20
Show file File: Access.php Project: Clon450/batata
0
 public static function start_processing(array $data, LoginController $ctrlLogin)
 {
     $callbackObj = new \stdClass();
     $callbackObj->user = null;
     $callbackObj->status = false;
     $callbackObj->error = null;
     $callbackObj->errors = array();
     $callbackObj = self::validateData($data, $callbackObj);
     if ($callbackObj->error) {
         return $callbackObj;
     }
     $user = User::find_by_username($data['username']);
     if (!is_null($user)) {
         $callbackObj->user = $user;
         $hash = \HXPHP\System\Tools::hashHX($data['password'], $user->salt);
         if ($user->password === $hash['password']) {
             $callbackObj->status = true;
         }
         $attempt_access = self::check_latest_attempt_to_access($callbackObj->user->id);
         if ($attempt_access < self::$minTime - 1) {
             $min = self::$minTime - 1;
             $callbackObj->error = true;
             array_push($callbackObj->errors, ['danger', '<p class="text-center"> Seu login foi bloqueado por motivos de segurança. </p>', '<p class="text-center"> Aguarde ' . ($min - $attempt_access) . ' minuto(s) e tente novamente. </p>']);
             $ctrlLogin->session->set('attemptAccess', 0);
             return $callbackObj;
         }
         var_dump($ctrlLogin->session->get('attemptAccess'));
         if ($ctrlLogin->session->get('attemptAccess') > self::$maxAttempt) {
             self::register_access_attempt($callbackObj->user->id);
             $ctrlLogin->session->set('attemptAccess', 0);
         }
         if ($callbackObj->status === false) {
             $attempt = $ctrlLogin->session->get('attemptAccess');
             $attempt++;
             $ctrlLogin->session->set('attemptAccess', $attempt);
         } else {
             return $callbackObj;
         }
     }
     $callbackObj->error = true;
     array_push($callbackObj->errors, self::$message['error_user_or_password']);
     return $callbackObj;
 }
Example #21
Show file File: User.php Project: pratikbgit/freelancerKit
0
 public static function validate_login($username, $password)
 {
     $user = User::find_by_username($username);
     $client = Client::find_by_email_and_inactive($username, 0);
     if ($user && $user->validate_password($password) && $user->status == 'active') {
         User::login($user->id, 'user_id');
         $update = User::find($user->id);
         $update->last_login = time();
         $update->save();
         return $user;
     } elseif ($client && $client->password == $password && $client->inactive == '0') {
         User::login($client->id, 'client_id');
         $update = Client::find($client->id);
         $update->last_login = time();
         $update->save();
         return $client;
     } else {
         return FALSE;
     }
 }
Example #22
Show file File: package_controller.php Project: xetorthio/pearfarm_channel_server
0
 public function show()
 {
     if ($this->is_logged_in()) {
         $this->login_user();
     }
     try {
         $this->set_default_side_bar();
         $user = User::find_by_username($_GET['username']);
         $this->package = Package::find('first', array('conditions' => array('user_id' => $user->id, 'name' => $_GET['package_name'])));
         $this->title = $this->package->name;
         Nimble::Set_title($this->title);
         $this->versions = Version::find_all(array('limit' => '0,5', 'conditions' => array('package_id' => $this->package->id), 'order' => 'version DESC'));
         $this->total_versions = $this->package->count('versions');
         $this->version = $this->package->current_version();
         if ($this->version !== false) {
             $this->data = unserialize($this->version->meta);
         }
     } catch (NimbleRecordNotFound $e) {
         Nimble::flash('notice', 'The package you were looking for does not exsist');
         $this->redirect_to('/');
     }
 }
Example #23
Show file File: UserControllerTest.php Project: scottdavis/pearfarm_channel_server
0
 public function setUp()
 {
     $_SERVER['SERVER_NAME'] = 'bob.localhost';
     $this->user = User::find_by_username('bob');
     $this->test_key = file_get_contents(getenv('HOME') . '/.ssh/id_openssl.pub');
 }
Example #24
Show file File: login_forgot_password_username.php Project: kamy333/rajah
0
<?php

require_once "../../includes/initialize.php";
$username = null;
$server_name = $_SERVER['PHP_SELF'];
$new_password = null;
if (request_is_post() && request_is_same_domain()) {
    if (!csrf_token_is_valid() || !csrf_token_is_recent()) {
        $message = "Sorry, request was not valid.";
    } else {
        $username = trim($_POST['username']);
        $valid = new FormValidation();
        $valid->validate_presences('username');
        if (empty($valid->errors)) {
            $user = User::find_by_username($username);
            if ($user) {
                $user->delete_reset_token();
                $user->create_reset_token();
                $user->send_email();
            } else {
                // Username was not found; don't do anything
            }
            // Message returned is the same whether the user
            // was found or not, so that we don't reveal which
            // usernames exist and which do not.
            $message = "A link to reset your password has been sent to the email address on file.";
        } else {
            $message = "Please enter a username.";
        }
    }
}
Example #25
Show file File: settings.php Project: timclifford/freelance-manager
0
 function user_create()
 {
     if ($_POST) {
         $config['upload_path'] = './files/media/';
         $config['encrypt_name'] = TRUE;
         $config['allowed_types'] = 'gif|jpg|jpeg|png';
         $config['max_width'] = '180';
         $config['max_height'] = '180';
         $this->load->library('upload', $config);
         if ($this->upload->do_upload()) {
             $data = array('upload_data' => $this->upload->data());
             $_POST['userpic'] = $data['upload_data']['file_name'];
         }
         unset($_POST['file-name']);
         unset($_POST['send']);
         unset($_POST['confirm_password']);
         if (!empty($_POST["access"])) {
             $_POST["access"] = implode(",", $_POST["access"]);
         }
         $_POST = array_map('htmlspecialchars', $_POST);
         $user_exists = User::find_by_username($_POST['username']);
         if (empty($user_exists)) {
             $user = User::create($_POST);
             if (!$user) {
                 $this->session->set_flashdata('message', 'error:' . $this->lang->line('messages_create_user_error'));
             } else {
                 $this->session->set_flashdata('message', 'success:' . $this->lang->line('messages_create_user_success'));
             }
         } else {
             $this->session->set_flashdata('message', 'error:' . $this->lang->line('messages_create_user_exists'));
         }
         redirect('settings/users');
     } else {
         $this->theme_view = 'modal';
         $this->view_data['title'] = $this->lang->line('application_create_user');
         $this->view_data['modules'] = Module::find('all', array('order' => 'sort asc', 'conditions' => array('type != ?', 'client')));
         $this->view_data['form_action'] = 'settings/user_create/';
         $this->content_view = 'settings/_userform';
     }
 }
Example #26
Show file File: lib.php Project: rboyatt/mahara
0
 /**
  * Grab a delegate object for auth stuff
  */
 public function request_user_authorise($token, $remotewwwroot)
 {
     global $USER, $SESSION;
     $this->must_be_ready();
     $peer = get_peer($remotewwwroot);
     if ($peer->deleted != 0 || $this->config['theyssoin'] != 1) {
         throw new XmlrpcClientException('We don\'t accept SSO connections from ' . institution_display_name($peer->institution));
     }
     $client = new Client();
     $client->set_method('auth/mnet/auth.php/user_authorise')->add_param($token)->add_param(sha1($_SERVER['HTTP_USER_AGENT']))->send($remotewwwroot);
     $remoteuser = (object) $client->response;
     if (empty($remoteuser) or !property_exists($remoteuser, 'username')) {
         // Caught by land.php
         throw new AccessDeniedException();
     }
     $create = false;
     $update = false;
     if ('1' == $this->config['updateuserinfoonlogin']) {
         $update = true;
     }
     // Retrieve a $user object. If that fails, create a blank one.
     try {
         $user = new User();
         if (get_config('usersuniquebyusername')) {
             // When turned on, this setting means that it doesn't matter
             // which other application the user SSOs from, they will be
             // given the same account in Mahara.
             //
             // This setting is one that has security implications unless
             // only turned on by people who know what they're doing. In
             // particular, every system linked to Mahara should be making
             // sure that same username == same person.  This happens for
             // example if two Moodles are using the same LDAP server for
             // authentication.
             //
             // If this setting is on, it must NOT be possible to self
             // register on the site for ANY institution - otherwise users
             // could simply pick usernames of people's accounts they wished
             // to steal.
             if ($institutions = get_column('institution', 'name', 'registerallowed', '1')) {
                 log_warn("usersuniquebyusername is turned on but registration is allowed for an institution. " . "No institution can have registration allowed for it, for security reasons.\n" . "The following institutions have registration enabled:\n  " . join("\n  ", $institutions));
                 throw new AccessDeniedException();
             }
             if (!get_config('usersallowedmultipleinstitutions')) {
                 log_warn("usersuniquebyusername is turned on but usersallowedmultipleinstitutions is off. " . "This makes no sense, as users will then change institution every time they log in from " . "somewhere else. Please turn this setting on in Site Options");
                 throw new AccessDeniedException();
             }
             $user->find_by_username($remoteuser->username);
         } else {
             $user->find_by_instanceid_username($this->instanceid, $remoteuser->username, true);
         }
         if ($user->get('suspendedcusr')) {
             die_info(get_string('accountsuspended', 'mahara', strftime(get_string('strftimedaydate'), $user->get('suspendedctime')), $user->get('suspendedreason')));
         }
     } catch (AuthUnknownUserException $e) {
         if (!empty($this->config['weautocreateusers'])) {
             $institution = new Institution($this->institution);
             if ($institution->isFull()) {
                 $institution->send_admin_institution_is_full_message();
                 throw new XmlrpcClientException('SSO attempt from ' . $institution->displayname . ' failed - institution is full');
             }
             $user = new User();
             $create = true;
         } else {
             log_debug("User authorisation request from {$remotewwwroot} failed - " . "remote user '{$remoteuser->username}' is unknown to us and auto creation of users is turned off");
             return false;
         }
     }
     /*******************************************/
     if ($create) {
         $user->passwordchange = 1;
         $user->active = 1;
         $user->deleted = 0;
         //TODO: import institution's expiry?:
         //$institution = new Institution($peer->institution);
         $user->expiry = null;
         $user->expirymailsent = 0;
         $user->lastlogin = time();
         $user->firstname = $remoteuser->firstname;
         $user->lastname = $remoteuser->lastname;
         $user->email = $remoteuser->email;
         $imported = array('firstname', 'lastname', 'email');
         //TODO: import institution's per-user-quota?:
         //$user->quota              = $userrecord->quota;
         $user->authinstance = empty($this->config['parent']) ? $this->instanceid : $this->parent;
         db_begin();
         $user->username = get_new_username($remoteuser->username);
         $user->id = create_user($user, array(), $this->institution, $this, $remoteuser->username);
         $locked = $this->import_user_settings($user, $remoteuser);
         $locked = array_merge($imported, $locked);
         /*
          * We need to convert the object to a stdclass with its own
          * custom method because it uses overloaders in its implementation
          * and its properties wouldn't be visible to a simple cast operation
          * like (array)$user
          */
         $userobj = $user->to_stdclass();
         $userarray = (array) $userobj;
         db_commit();
         // Now we have fired the create event, we need to re-get the data
         // for this user
         $user = new User();
         $user->find_by_id($userobj->id);
     } elseif ($update) {
         $imported = array('firstname', 'lastname', 'email');
         foreach ($imported as $field) {
             if ($user->{$field} != $remoteuser->{$field}) {
                 $user->{$field} = $remoteuser->{$field};
                 set_profile_field($user->id, $field, $user->{$field});
             }
         }
         if (isset($remoteuser->idnumber)) {
             if ($user->studentid != $remoteuser->idnumber) {
                 $user->studentid = $remoteuser->idnumber;
                 set_profile_field($user->id, 'studentid', $user->studentid);
             }
             $imported[] = 'studentid';
         }
         $locked = $this->import_user_settings($user, $remoteuser);
         $locked = array_merge($imported, $locked);
         $user->lastlastlogin = $user->lastlogin;
         $user->lastlogin = time();
         //TODO: import institution's per-user-quota?:
         //$user->quota              = $userrecord->quota;
         $user->commit();
     }
     if (get_config('usersuniquebyusername')) {
         // Add them to the institution they have SSOed in by
         $user->join_institution($peer->institution);
     }
     // See if we need to create/update a profile Icon image
     if ($create || $update) {
         $client->set_method('auth/mnet/auth.php/fetch_user_image')->add_param($remoteuser->username)->send($remotewwwroot);
         $imageobject = (object) $client->response;
         $u = preg_replace('/[^A-Za-z0-9 ]/', '', $user->username);
         $filename = get_config('dataroot') . 'temp/mpi_' . intval($this->instanceid) . '_' . $u;
         if (array_key_exists('f1', $client->response)) {
             $imagecontents = base64_decode($client->response['f1']);
             if (file_put_contents($filename, $imagecontents)) {
                 $imageexists = false;
                 $icons = false;
                 if ($update) {
                     $newchecksum = sha1_file($filename);
                     $icons = get_records_select_array('artefact', 'artefacttype = \'profileicon\' AND owner = ? ', array($user->id), '', 'id');
                     if (false != $icons) {
                         foreach ($icons as $icon) {
                             $iconfile = get_config('dataroot') . 'artefact/file/profileicons/originals/' . $icon->id % 256 . '/' . $icon->id;
                             $checksum = sha1_file($iconfile);
                             if ($newchecksum == $checksum) {
                                 $imageexists = true;
                                 unlink($filename);
                                 break;
                             }
                         }
                     }
                 }
                 if (false == $imageexists) {
                     $filesize = filesize($filename);
                     if (!$user->quota_allowed($filesize)) {
                         $error = get_string('profileiconuploadexceedsquota', 'artefact.file', get_config('wwwroot'));
                     }
                     require_once 'file.php';
                     $imagesize = getimagesize($filename);
                     if (!$imagesize || !is_image_type($imagesize[2])) {
                         $error = get_string('filenotimage');
                     }
                     $mime = $imagesize['mime'];
                     $width = $imagesize[0];
                     $height = $imagesize[1];
                     $imagemaxwidth = get_config('imagemaxwidth');
                     $imagemaxheight = get_config('imagemaxheight');
                     if ($width > $imagemaxwidth || $height > $imagemaxheight) {
                         $error = get_string('profileiconimagetoobig', 'artefact.file', $width, $height, $imagemaxwidth, $imagemaxheight);
                     }
                     try {
                         $user->quota_add($filesize);
                     } catch (QuotaException $qe) {
                         $error = get_string('profileiconuploadexceedsquota', 'artefact.file', get_config('wwwroot'));
                     }
                     require_once get_config('docroot') . '/artefact/lib.php';
                     require_once get_config('docroot') . '/artefact/file/lib.php';
                     // Entry in artefact table
                     $artefact = new ArtefactTypeProfileIcon();
                     $artefact->set('owner', $user->id);
                     $artefact->set('parent', ArtefactTypeFolder::get_folder_id(get_string('imagesdir', 'artefact.file'), get_string('imagesdirdesc', 'artefact.file'), null, true, $user->id));
                     $artefact->set('title', ArtefactTypeFileBase::get_new_file_title(get_string('profileicon', 'artefact.file'), (int) $artefact->get('parent'), $user->id));
                     // unique title
                     $artefact->set('description', get_string('uploadedprofileicon', 'artefact.file'));
                     $artefact->set('note', get_string('profileicon', 'artefact.file'));
                     $artefact->set('size', $filesize);
                     $artefact->set('filetype', $mime);
                     $artefact->set('width', $width);
                     $artefact->set('height', $height);
                     $artefact->commit();
                     $id = $artefact->get('id');
                     // Move the file into the correct place.
                     $directory = get_config('dataroot') . 'artefact/file/profileicons/originals/' . $id % 256 . '/';
                     check_dir_exists($directory);
                     rename($filename, $directory . $id);
                     if ($create || empty($icons)) {
                         $user->profileicon = $id;
                     }
                 }
                 $user->commit();
             } else {
                 log_warn(get_string('cantcreatetempprofileiconfile', 'artefact.file', $filename));
             }
         }
         if ($update) {
             $locked[] = 'profileicon';
         }
     }
     /*******************************************/
     // We know who our user is now. Bring her back to life.
     $USER->reanimate($user->id, $this->instanceid);
     // Set session variables to let the application know this session was
     // initiated by MNET. Don't forget that users could initiate their
     // sessions without MNET sometimes, which is why this data is stored in
     // the session object.
     $SESSION->set('mnetuser', $user->id);
     $SESSION->set('authinstance', $this->instanceid);
     if (isset($_SERVER['HTTP_REFERER'])) {
         $SESSION->set('mnetuserfrom', $_SERVER['HTTP_REFERER']);
     }
     if ($update && isset($locked)) {
         $SESSION->set('lockedfields', $locked);
     }
     return true;
 }
Example #27
Show file File: Control.php Project: Max201/nanocore
0
 /**
  * View user profile
  *
  * @param Request $request
  * @param $matches
  * @return mixed|string
  */
 public function profile(Request $request, $matches)
 {
     try {
         /** @var \User $user */
         $user = \User::find($matches['id']);
     } catch (\Exception $e) {
         return $this->error404($request);
     }
     // User access log filter
     $access_filter = ['conditions' => ['user_id = ?', $user->id]];
     // Paginator access log
     /** @var Listing $paginator */
     $paginator = NCService::load('Paginator.Listing', [$request->page, \Visit::count($access_filter)]);
     $access_filter['order'] = 'id DESC';
     $access_filter = array_merge($access_filter, $paginator->limit());
     // Unban user
     if ($request->get('unban')) {
         $user->ban_time = null;
         $user->ban_user_id = null;
         $user->ban_reason = null;
         $user->save();
         static::redirect_response($this->map->reverse('users.profile', ['id' => $user->id]));
     }
     if ($request->isMethod('post')) {
         $changed = false;
         // Edit rating
         $rating = intval($request->get('rating', 0));
         if ($user->rating != $rating) {
             $user->rating = $rating;
             $changed = true;
         }
         // Change ban user
         $ban_time = $request->get('ban_time', false);
         $ban_reason = $request->get('ban_reason', false);
         if ($ban_time) {
             if ($ban_time == '-1' || strtolower(trim($ban_time)) == 'forever') {
                 $ban_time = -1;
             } else {
                 $ban_time = strtotime($ban_time, time());
             }
             $user->ban($this->user, $ban_time, $ban_reason);
             $changed = true;
         }
         // Edit username
         $new_login = $request->get('username');
         if ($new_login && $new_login != $user->username) {
             $exists = \User::find_by_username($new_login);
             if ($exists && $exists->id) {
                 return static::json_response(['status' => $this->lang->translate('user.edit.exists', $new_login), 'class' => 'error']);
             } else {
                 $changed = true;
                 $user->username = $new_login;
             }
         }
         // Edit email
         $new_email = $request->get('email');
         if ($new_email && $new_email != $user->email) {
             $exists = \User::find_by_email($new_email);
             if ($exists && $exists->id) {
                 return static::json_response(['status' => $this->lang->translate('user.edit.exists_email', $new_email), 'class' => 'error']);
             } else {
                 $changed = true;
                 $user->email = $new_email;
             }
         }
         // Edit group
         $new_group = intval($request->get('group', $user->group_id));
         if (!\Group::find($new_group)) {
             return static::json_response(['status' => $this->lang->translate('user.edit.wrong_group'), 'class' => 'error']);
         } else {
             $changed = true;
             $user->group_id = $new_group;
         }
         // Change password
         $new_password = $request->get('new_password');
         if ($new_password) {
             $user->password = $new_password;
             if (strlen($new_password) > 5 && $user->save()) {
                 return static::json_response(['status' => $this->lang->translate('form.saved'), 'class' => 'success']);
             } else {
                 return static::json_response(['status' => $this->lang->translate('form.failed'), 'class' => 'error']);
             }
         }
         if ($changed && $user->save()) {
             return static::json_response(['status' => $this->lang->translate('form.saved'), 'class' => 'success']);
         } else {
             return static::json_response(['status' => $this->lang->translate('form.failed'), 'class' => 'error']);
         }
     }
     return $this->view->render('users/profile.twig', ['title' => $this->lang->translate('user.profile.name', $user->username), 'profile' => $user->to_array(), 'groups' => array_map(function ($i) {
         return $i->to_array();
     }, \Group::all()), 'visits_list' => \Visit::as_array(\Visit::find('all', $access_filter)), 'user_ips' => array_map(function ($ip) {
         $data = ['addr' => long2ip($ip->ip)];
         $data['banned'] = !Env::$kernel->ipwall->allowed(long2ip($ip->ip));
         return $data;
     }, \Visit::ips_by_user($user)), 'listing' => $paginator->pages(), 'page' => $paginator->cur_page]);
 }
Example #28
Show file File: index.php Project: tedz2usa/chatbox
0
// session_destroy();
require_once '../logs/constants.php';
$mysqli = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (isset($_POST['username'])) {
    if (authenticate_password($_POST['username'], $_POST['password'])) {
        $_SESSION['username'] = $_POST['username'];
    } else {
        // echo 'Not Authenticated!';
    }
}
$settings = get_app_settings();
$users = get_app_users();
$page_mode = get_page_mode();
$current_user;
if (is_logged_in()) {
    $current_user = User::find_by_username($_SESSION['username']);
}
function is_logged_in()
{
    return isset($_SESSION['username']);
}
function pre($obj)
{
    echo '<pre>';
    var_dump($obj);
    echo '</pre>';
}
function get_app_settings()
{
    global $mysqli;
    $settings = array('application_name' => 'My Chatroom', 'application_name_long' => 'Team Collaboration');
Example #29
Show file File: raffle.php Project: richardmountain/lanopsManager
0
    $tickets = RaffleTicket::find('all');
    if ($reset == 'active') {
        //Reset all tickets to active
        foreach ($tickets as $ticket) {
            $ticket->active = 1;
            $ticket->save();
        }
    } elseif ($reset == 'delete') {
        //Delete all tickets
        foreach ($tickets as $ticket) {
            $ticket->delete();
        }
    }
}
if (isset($_GET['add'])) {
    $thisUser = User::find_by_username($_POST['username']);
    addTicket($thisUser->userid, $_POST['game'], $_POST['number']);
}
if (isset($_GET['reset'])) {
    echo 'reset raffle';
    resetRaffle('active');
    header('Location: ' . $_SERVER['HTTP_REFERER']);
}
?>
<!--JAVASCRIPT EVENTS -->
<script>
	//Delete row from HTML table
  function addTicket()
  {
    //Reset any error messages
    document.getElementById("usernameInputDiv").classList.remove("has-error");
Example #30
Show file File: user.php Project: agiza/DreamVids
0
 /**
  * @return User
  */
 public static function connect($username, $remember)
 {
     if (User::find_by_username($username)) {
         $sessid = md5(uniqid());
         $expiration = $remember ? Utils::tps() + 365 * 86400 : Utils::tps() + 24 * 3600;
         $user = User::find_by_username($username);
         UserSession::create(array('user_id' => $user->id, 'session_id' => $sessid, 'expiration' => $expiration, 'remember' => $remember));
         setcookie('SESSID', $sessid, $expiration);
         return $user;
     }
 }