I have an installation of Codeigniter, IonAuth + Hybridauth which I am reworking so my users can choose their own username instead of generating one using the first and last names returned by facebook.
So in my code below I check to see if a username was posted, if not I want to load the choose_username view but for some reason the view is not loading and its completely skipping that section which is why I added die('Why no view')
Update: This first piece of code runs fine in a new controller
Checkout the code here:
if(isset($_POST['username'])){
$username = $this->input->post('username', TRUE);
die($username);
}else{
$this->data['message'] = 'Please choose a username.';
$this->data['template'] = 'guests/partials/choose_username';
$this->load->view('guests/template/standard', $this->data);
die('Why no view?');
};
Longer version:
function login_provider($provider = '')
{
if(empty($provider)) redirect();
try
{
// create an instance for Hybridauth with the configuration file
$this->load->library('HybridAuthLib');
if ($this->hybridauthlib->serviceEnabled($provider))
{
// try to authenticate the selected $provider
$service = $this->hybridauthlib->authenticate($provider);
if ($service->isUserConnected())
{
// grab the user profile
$user_profile = $service->getUserProfile();
////////////
//var_dump($user_profile);
//die();
////////////
$provider_uid = $user_profile->identifier;
if($this->ion_auth->login_by_provider($provider,$provider_uid))
{
$data['user_profile'] = $this->ion_auth->user_by_provider();
//$this->load->view('auth/user_profile',$data);
$user = $this->ion_auth->user()->row();
//Redirect to custom subdomain
$url = explode('://',site_url());
if (strpos(site_url(),$user->username) !== false) {
redirect($url[0].'://'.str_replace('www','',$url[1]).'dashboard','refresh');
}
else{
redirect($url[0].'://'.$user->username.str_replace('www','',$url[1]).'dashboard');
};
}
else
{ // if authentication does not exist and email is not in use, then we create a new user
//Check if username was posted
if(isset($_POST['username'])){
$username = $this->input->post('username', TRUE);
die($username);
}else{
$this->data['message'] = 'Please choose a username.';
$this->data['template'] = 'guests/partials/choose_username';
$this->load->view('guests/template/standard', $this->data);
die('Why no view?');
};
So when I run the above code, all i get is a blank page with: Why no view.
As above, usually when I run into this sort of issue it's from a bug in the view code.
Also, I don't know what, is actually being passed by this post in the event of there not being username data but you might want to also be checking for an empty value for username. This is probably not the issue but it would be good to confirm that the initial if is evaluating the way you expect.
Related
I'm having some issues with a request from my boss.
I'm using the http://www.html-form-guide.com/ Registration forms he has created for use (I've attached the link just in case anyone want to use or look at it)
So I'm pretty new to PHP, but I've been gaining a crazy amount of knowledge.
Here is my problem - I need to make this form Register the user than Login Automatically. (This form has a Email confirmation system)
So I've managed to bypass the Email Confirmation and get the user to register, but I can't seem to figure out how to get auto login.
Here is what I've traced in the code:
function RegisterUser()
{
if(!isset($_POST['submitted']))
{
return false;
}
$formvars = array();
if(!$this->ValidateRegistrationSubmission())
{
return false;
}
$this->CollectRegistrationSubmission($formvars);
if(!$this->SaveToDatabase($formvars))
{
return false;
}
/*if(!$this->SendUserConfirmationEmail($formvars))
{
return false;
}*/
$this->SendAdminIntimationEmail($formvars);
$this->AutoLogin($formvars);// My call
return true;
}
This will pull in the name, email and password - put them in an array then send it off for validation and sanitation. I've placed a call function here.
After which I'll need to manually login with:
function Login()
{
if(empty($_POST['email']))
{
$this->HandleError("Email is empty!");
return false;
}
if(empty($_POST['password']))
{
$this->HandleError("Password is empty!");
return false;
}
$email = trim($_POST['email']);
$password = trim($_POST['password']);
if(!isset($_SESSION)){ session_start(); }
if(!$this->CheckLoginInDB($email,$password))
{
return false;
}
$_SESSION[$this->GetLoginSessionVar()] = $email;
return true;
}
So I took the last portion of the login function and made:
function AutoLogin(&$formvars)
{
$email = trim($formvars['email']);
$password = trim($formvars['password']);
if(!isset($_SESSION)){ session_start(); }
if(!$this->CheckLoginInDB($email,$password))
{
return false;
}
$_SESSION[$this->GetLoginSessionVar()] = $email;
return true;
}
I did an echo $email; echo $password; exit; test and I can see that the email and password are appearing. But the "Session" (I think) is not starting or the Check Login is not getting the data.
function CheckLogin()
{
if(!isset($_SESSION)){ session_start(); }
$sessionvar = $this->GetLoginSessionVar();
if(empty($_SESSION[$sessionvar]))
{
return false;
}
return true;
}
Now I see the is a CheckLoginInDB which is:
function CheckLoginInDB($email,$password)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$email = $this->SanitizeForSQL($email);
$pwdmd5 = md5($password);
$qry = "Select name, email, pagecode, welcome from $this->tablename where email='$email' and password='$pwdmd5' and confirmcode='y'";
$result = mysql_query($qry,$this->connection);
if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Error logging in. The email or password does not match");
return false;
}
$row = mysql_fetch_assoc($result);
$_SESSION['name_of_user'] = $row['name'];
$_SESSION['email_of_user'] = $row['email'];
$_SESSION['pagecode_of_user'] = $row['pagecode'];
$_SESSION['welcome_user'] = $row['welcome'];
return true;
}
What I can gather from this, its just a standard checking the database to see if this user exists and returning the results.
I've searching through stackoverflow and can't seem to see an answer to my problem.
I looked into Cookies, but I don't think that is something I really need here.
My questions are:
How can I make this bad boy start the session on registration?
Is my thinking on calling the AutoLogin(&$formvars) the right idea?
Have I gone wrong with this AutoLogin function syntax?
Just in case here is the GetLoginSessionVar():
function GetLoginSessionVar()
{
$retvar = md5($this->rand_key);
$retvar = 'usr_'.substr($retvar,0,10);
return $retvar;
}
It's a pity I can't attached the file I'm working on, but if you need any further code snippets let me know and I'll be sure to Edit this straight away!
But the "Session" (I think) is not starting or the Check Login is not
getting the data.
Is my thinking on calling the AutoLogin(&$formvars) the right idea?
Have I gone wrong with this AutoLogin function syntax?
It's not something wrong with the syntax, otherwise the code wouldn't even be compiled. Nevertheless I believe it's not the right idea.
You need to understand what's the problem before trying to fix it.
Debug the code. Use xdebug. If it's installed and active, you can use IDEs (e.g.: Visual Studio Code) to easily debug the code. Add breakpoints where you suspect there's something wrong.
If you don't want to use xdebug, you can add temporarily echoes or var_dumps to check if some areas of the code are processed and check some relevant values.
Also enable all errors reports and use a logger.
If the session is started after any output, there should be some warning.
Handle the errors and throw exceptions.
http://php.net/manual/en/function.error-log.php
http://php.net/manual/en/function.syslog.php
https://jtreminio.com/2012/07/xdebug-and-you-why-you-should-be-using-a-real-debugger/
session_start() works after output being sent
http://php.net/manual/en/function.error-reporting.php
You don't need to use the & in AutoLogin(&$formvars) if you're not changing the argument $formvars (you're just reading it).
You don't need to set session variables with all the user data. Create some structure (a class, an array, ...) with the user data outside those function and change those. AutoLogin should update that structure, something like this:
<?php
if (!$_SESSION) {
session_start();
}
$currentUser = array();
function getUserFromID($userID)
{
//TODO implement function
return $user;
}
function AutoLogin()
{
global $currentUser;
if(!empty($_SESSION['userID'])) {
return false;
}
$user = getUserFromID($_SESSION['userID']);
if (empty($user)) {
return false;
}
$currentUser = $user;
return true;
}
Maybe the session is not initialised before CheckLoginInDB is invoked (make var_dump($_SESSION); to check it). Use the $_SESSION only to save the user ID (or email) and read it to retrieve the user data.
After login after some random time when i refresh any page on website, sometimes it works perfectly, but sometimes it shows error like Trying to get propert on different lines of model and controller file.
For example, when i refresh the page error was shown in below function of model named user_model and controller named User.php:
User_model.php:
public function get_client_id($email)
{
$this->db->select('id');
$this->db->where('email', $email);
$query = $this->db->get('crm_accounts');
$result = $query->row();
return $result->id; //line 135
}
Users.php:
$email = $_SESSION['email'];
$id = $this->user_model->get_client_id($email); //line 145
Setting the session value after login:
$email = $this->input->post("email");
$password = $this->input->post("pass");
$result = $this->user_model->login($email, $password);
if ($result == TRUE)
{
$this->session->set_userdata('email',$email);
$this->session->set_userdata('logged_in',TRUE);
$data = $this->user_model->get_username($email);
$this->session->set_userdata('data', $data);
redirect('admin_view');
}
else
{
$this->load->view('all_field');
}
code for deleting the session after logout:
$logged_in = $this->session->userdata('logged_in');
$log = $this->session->userdata('email');
if($logged_in || (!empty($log)))
{
$array_item = array('email', 'logged_in');
$this->session->unset_userdata($array_item);
redirect('');
}
else
{
$this->load->view('error_page');
}
Here, i got error on like
Tring to get property of non-object on line 135 of user_model.php and in backtrace it found error on Users.php on line 145
I have noticed that when i get this type of error in model, i am getting data in that particular method using session variable $email in which the session data is stored. But i have put such condition in controller:
public function index()
{
if(!empty($_SESSION['email']))
{
$email = $_SESSION['email'];
$data = $this->user_model->get_username($email);
$this->session->set_userdata('data',$data);
redirect('clientview');
//echo "You are already logged in";
}
else
{
$this->load->view('signup');
}
}
So, if the value of session variable $email is not set than it should go on signup page.
So, i am not getting what is actually problem. Because sometimes it works perfectly and sometimes not. Once if i get such error, i have to clear my history and than i have to log in again.
In Codeigniter you have a specific way to get form or set values in the session.
If you want to check if the session exist you need to do
$this->session->userdata('email');
Which will retrieve the stored value.
And as you already do:
$this->session->set_userdata('email', $email);
To set a value in the session.
Additionally when the user is logging out yoi need to reset the stored value, ptherwise it will never be empty.
$this->session->set_userdata('email', '');
NOTE: What you are doing is of course not the best way to do such kind of stuff, as a login and logout system. I suppose you are just learning and you are doing this not for a production application.
If you do, please try to use ionAuth authentication library for Codeigniter, that you can find here:
http://benedmunds.com/ion_auth/
And follow some tutorial about it:
http://www.tutorials.kode-blog.com/codeigniter-authentication
Just keep in mind that user authentication is a serious security matter so be carefull.
I am using Joomla 2.5 and in the head of my site I have a module with the following code:
<?php
$user =JFactory::getUser()->guest;
if ($user->guest) {
echo 'Please sign up or sign in to view this'
}
else {
echo 'Here is the content';
}
?>
What I tried but didnt work is to add a variable $member in the first if statement. If the person isnt logged in to show him the echo but also set $member to == true.
Why I want to do this? I think it would make the site load faster if I check the status of $member than to go calling the Joomla API to determine if the user is logged in or not.
The calls to determine if a visitor is a member or not in every page are about 5-7. When I use the JFactory::getUser() function (all of the code above) 5-7 times it does slow down a bit the website. Thats why I thought of creating in the first call the $member == true correct me if I am wrong in thinking this would be better in site perfomance/speed wise.
I tried this:
<?php
$user =JFactory::getUser()->guest;
if ($user->guest) {
echo 'Please sign up or sign in to view this'
$member == true;
}
else {
echo 'Here is the content';
}
?>
I have the above code in the header module. But when I later in other modules in the same page or in the article if I use a php code it doesn't recognize the status of $member and always determines the user as not logged in.
What am I doing wrong? I'm guessing its something with variables scope, I checked my PHP book but couldn't find the error. Any help appreciated.
You are already calling $user->guest, so try changing:
$user = JFactory::getUser()->guest;
to this:
$user = JFactory::getUser();
As an alternative, you could also do use the following:
$user =& JFactory::getUser();
if($user->id=0){
echo 'Please sign up or sign in to view this'
$member == true;
}
else {
echo 'Here is the content';
}
You could do this in one line, Refactored code would be
$member = (JFactory::getUser()->id) ? true : false ;
i use tank auth as login handler in code igniter. when i use the forget password feature, i get a link send by mail http://xx.xx.xx/en//auth/reset_password/2/01b951fd2a02efa2d64f1fe70c2a4e3b. When i click this link it always says: "Your activation key is incorrect or expired. Please check your email again and follow the instructions."
i changed the segments so it gets the right segments but somehow it the goes wrong on if ($this->form_validation->run()). it Somehow wants the new_password and confirm_new_password as post data but from the link in the email no post data will ofcourse be sent.
Is this a bug in tank auth, is there a quickfix (does tank_auth forget a step, is something not configured right?)
reference code:
function reset_password()
{
$break =$this->uri->total_segments();
$new_pass_key= $this->uri->segment($break);
$user_id= $this->uri->segment($break-1);
$this->form_validation->set_rules('new_password', 'New Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']|alpha_dash');
$this->form_validation->set_rules('confirm_new_password', 'Confirm new Password', 'trim|required|xss_clean|matches[new_password]');
$data['errors'] = array();
if ($this->form_validation->run()) { //breaks here. For some reason wants to validate post data which
if (!is_null($data = $this->tank_auth->reset_password($user_id, $new_pass_key,$this->form_validation->set_value('new_password')))) { // success
$data['site_name'] = $this->config->item('website_name', 'tank_auth');
// Send email with new password
$this->_send_email('reset_password', $data['email'], $data);
$this->_show_message($this->lang->line('auth_message_new_password_activated').' '.anchor('/auth/login/', 'Login'));
} else { // fail
$this->_show_message($this->lang->line('auth_message_new_password_failed'));
}
} else {
// Try to activate user by password key (if not activated yet)
if ($this->config->item('email_activation', 'tank_auth')) {
$this->tank_auth->activate_user($user_id, $new_pass_key, FALSE);
}
if (!$this->tank_auth->can_reset_password($user_id, $new_pass_key)) {
$this->_show_message($this->lang->line('auth_message_new_password_failed'));
}
}
$this->load->view('auth/reset_password_form', $data);
}
Your new_pass_key and $user_id are wrong I guess.
It should work out of the box with this:
$user_id = $this->uri->segment(3);
$new_pass_key = $this->uri->segment(4);
EDIT:
$user_id = $this->uri->segment(4);
$new_pass_key = $this->uri->segment(5);
Why did you change that by the way?
I am building a social network via code igniter. Upon registration, the potential member get's stored in the db, and their status get's marked to pending. I then send them a confirmation email with a hashed token link. When they hit the link it marks their account as active and takes them to a welcome page that has a sign in.
When I go to the link it sets of an infinite loop and freezes my computer when I'm working on my MAMP. ( or I'm suspicious that it's an infinite loop )
Here is my pertinent code:
auth CONTROLLER that sends the email:
function varification_email()
{
$query = $this->db->query('SELECT * FROM users order by id desc LIMIT 1');
$token = sha1($user->email.$user->salt).dechex($user->id);
$domain = "clci.dev/index.php";
$link = "http://www.".$domain."/account/confirmation/?token=$token";
foreach ($query->result() as $user)
{
$this->load->library('email');
$this->email->from('noreply#cysticlife.org', 'CysticLife');
$this->email->to($user->email);
$this->email->subject('Welcome to CysticLife!');
$this->email->message("Thanks for signing up for CysticLife! To complete the registration process please go to the following web address:\n\n$link\n\n-Your friends at CysticLife\n\nPlease remember to add the cysticlife.org domain to your address book to ensure that you receive your CysticLife e-Notifications as requested.eh");
$this->email->send();
}
account CONTROLLER that the user is linked back to from the email:
public function confirmation() {
$data['main_content'] = 'account/confirmation';
$this->load->view('includes/templates/main_page_template', $data);
$this->load->library('encrypt');
$this->load->helper('url');
$this->load->library('session');
$this->load->model('user_model', 'um');
$login = $this->input->post('submit');
//IF THE SUBMIT BUTTON IS TRIGGERED THE POST DATA IS SENT TO THE VALIDATE FUNCTION IN THE MODEL VIA VARIABLES CREATED
if($login) {
$user = $this->um->validate(array('email' => $this->input->post('email')));
if( $user ) {
// CHECK THE USER'S PASSWORD AGAINST THE ONE FROM THE LOGIN FORM
if($user->password == $this->encrypt->sha1( $user->salt . $this->encrypt->sha1($this->input->post('password')))) {
$this->session->set_userdata('logged_in', TRUE);
$this->session->set_userdata(array(
'email' => $this->input->post('email')
));
$this->session->userdata('logged_in');
redirect('account/dashboard');
exit;
}
}
}
$this->index();
}
Thanks in advance
varification_email()
In varification_email(), $user is used before it is defined. I assume the real code doesn't have this issue.
Your method for selecting the user in the DB in prone to concurrency errors (wrong user returned).
confirmation()
I already had encountered browser hangs because of too large cookies, exceeding something like 4 kB. Have a look at that.
The problem might be in user_model->validate(). Comment out the following of the code and check if it works.