stopping infinite loop - php

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.

Related

MethodNotAllowedHttpException generated using return back()->withInput() in Laravel 5.4

I've searched the forums and have seen many similar issues but none that seem to address my concern. I believe this is different because:
Form validation is not being used at this point
The form method does not seem to be related (just 1 post action)
The routes are not wrapped in web middleware
Here's what the application is supposed to be doing:
A user (with or without Authentication) views a public page with form (display_event)
The user selects a specific ticket for ordering and is directed to a 2nd form (register_step1)
The user then fills out demographic info for as many tickets as are being ordered
The processing step, if the email address used is of a valid user (in DB) should return to the form in step 2 & 3, populate the fields and flash a message. Otherwise it would perform the save() actions required. (register_step2)
The relevant routes from web.php are here:
Route::get('/events/{event}', 'EventController#show')->name('display_event');
Route::post('/register/{event}', 'RegistrationController#showRegForm')->name('register_step1');
Route::post('/register/{event}/create', 'RegistrationController#store')->name('register_step2');
The relevant portions of the RegistrationController.php are here:
public function showRegForm (Request $request, $id) {
// Registering for an event from /event/{id}
$ticket = Ticket::find(request()->input('ticketID'));
$quantity = request()->input('quantity');
$discount_code = request()->input('discount_code');
$event = Event::find($ticket->eventID);
return view('v1.public_pages.register', compact('ticket', 'event', 'quantity', 'discount_code'));
}
And:
public function store (Request $request) {
$event = Event::find(request()->input('eventID'));
if(Auth::check()) {
$this->currentPerson = Person::find(auth()->user()->id);
}
// set up a bunch of easy-reference variables from request()->input()
$email = Email::where('emailADDR', $checkEmail)->first();
if(!Auth::check() && $email === null) {
// Not logged in and email is not in database; must create
$person = new Person;
// add person demographics from form
} elseif(!Auth::check() && $email !== null) {
// Not logged in and email is in the database;
// Should force a login -- return to form with input saved.
flash("You have an account that we've created for you.
Please attempt to login and we'll send you a password to your email address.", 'warning');
return back()->withInput();
} elseif(Auth::check() && ($email->personID == $this->currentPerson->personID)) {
// the email entered belongs to the person logged in; ergo in DB
$person = $this->currentPerson;
// add person demographics from form
} elseif(Auth::check() && ($email->personID != $this->currentPerson->personID)) {
// someone logged in is registering for someone else in the DB
$person = Person::find($email->personID);
// add person demographics from form
} else {
// someone logged in is registering for someone else NOT in the DB
$person = new Person;
// add person demographics from form
}
// do more stuff...
$reg = new Registration; (set up a registration record)
}
I took the advice indicated in #apokryfos's comment and changed the form parsing-then-display script from a POST to a get.
redirect()->back() is, apparently, always a method=get and that was the cause of the MethodNotAllowedHttpException. In my ~2 weeks using Laravel, I hadn't yet come across that fact.

Sometimes Trying to get property of non-object

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.

Codeigniter Auth system based on device

I am kind of newbie around here so hope i am doing fine what am i doing.
I started working with Codeignter recently and trying to build a secured login to restrict access from three devices only.
On login
I am trying to add a never-expiring "device_id" cookie upon successful authentication. That cookie would be a a unique string and store it into database
And if the user has aleady three devices stored to be rejected.
If the user has available devices slots, this to be recorded and added to its stack.
Basicly i want to allow access if the user has avail slots or the cookie arleady exists.
Have any ideea where should i start or there is a Codeigniter library ?
The code from my control that alows and valides login is:
function login()
{
if ($this->session->userdata('logged_in'))
{
$logged_in_user = $this->session->userdata('logged_in');
if ($logged_in_user['is_admin'])
{
redirect('admin');
}
else
{
redirect(base_url());
}
}
// set form validation rules
$this->form_validation->set_error_delimiters($this->config->item('error_delimeter_left'), $this->config->item('error_delimeter_right'));
$this->form_validation->set_rules('username', lang('users input username_email'), 'required|trim');
$this->form_validation->set_rules('password', lang('users input password'), 'required|trim|callback__check_login');
if ($this->form_validation->run() == TRUE)
{
if ($this->session->userdata('redirect'))
{
$redirect = $this->session->userdata('redirect');
$this->session->unset_userdata('redirect');
redirect($redirect);
}
else
{
$logged_in_user = $this->session->userdata('logged_in');
if ($logged_in_user['is_admin'])
{
redirect('admin');
}
else
{
redirect(base_url());
}
}
}
// setup page header data
$this->add_css_theme( 'login.css' );
$this->set_title( lang('users title login') );
$data = $this->includes;
// load views
$data['content'] = $this->load->view('user/login', NULL, TRUE);
$this->load->view($this->template, $data);
}
it's not a good idea to write your system ....you can not secure your auth system from session hijacking (when session_id not change in long period) , dos attack , ddos attack , etc very easliy .... it's better to use early written system like auth_ion ....
you can find authentication library for code igniter in :
https://github.com/bcit-ci/CodeIgniter/wiki/Contributions#libraries
i preffer ion_auth in that list ...

How to redirect user to a different controller on refreshing the page

I am working on codeigniter. I am implementing signin functionality and when user signs in i call this controller
function validate_credentials()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query==1)
{
$data = array
(
'username'=>$this->input->post('username'),
'is_logged_in' => true
);
$email=$data['username'];
$this->session->set_userdata('email_of_user',$email);
$this->load->model('search_peoplee');
$data['userid']= $this->search_peoplee->get_userid_from_email($email);
foreach ($data['userid'] as $row)
{
$one=$row->userid;
}
$data['result']=$this->membership_model->friend_notify($one);
$data['count']=$this->search_peoplee->get_friends_count($one);
$this->load->model('search_peoplee');
$data['values']= $this->search_peoplee->get_notifications($one);
$data['count_notify']=$this->search_peoplee->get_notifications_count($one);
$this->session->set_userdata('lookatit','no');
$this->load->view('home_screen',$data);
}
elseif($query==2)
{
$data['main_content']='email_not_found';
$this->load->view('includes/template',$data);
}
else
{
$this->error_index();
}
}
this validates the credentials and stores a session, this controller calls a model "$this->membership_model->validate();" which picks the value form view and check that if user exists, the problem is when i retype the address it takes me to the login page and says sign in again as the model reads empty values. How to avoid this. help!!!
after you have authenticated, how about setting a session variable.
so,
$this->session->set_userdata('authenticated',TRUE);
then in the controller, first check if the user is authenticated and do a redirect, otherwise go to the validate_credentials method ??

codeigniter redirect fails only when i include "refresh"

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller
{
public function __construct()
{
parent::__construct();
//Model for fetching users in database
$this->load->model('user', '', TRUE);
}
public function index()
{
//Load method to help verify form credentials
$this->load->library('form_validation');
//-----------------------------------------------
//Verify Existance of values in login form fields
//-----------------------------------------------
//Validate existance of username field value
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
//Validate existance of password field value, and if exists then call 'check_database' func
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
//If the form validation is false (i.e. Missing form fields)
if($this->form_validation->run() == FALSE){
//Redirect back to login page
$this->load->view('general-Login');
}
//Login Success, goto main-page
else{
//Go to main page
redirect('Main', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//Check the username and password against database
$result = $this->user->login($username, $password);
//If there is a result
if($result){
//will be used for session information
$sess_array = array();
foreach ($result as $row){
$sess_array= array(
'id' => $row->id,
'username' => $row->username
);
//Session set as logged in
$this->session->set_userdata('logged_in', $sess_array);
}
return true;
}
//No existance of user or, incorrect password
else{
//Send Message of incorrect username or password
$this->form_validation->set_message('check_database', 'Invalid Username or Password');
return false;
}
}
}
So i have a verifylogin controller that handles the form data from my login page. Database access works great and everything works perfectly until i get to the redirect feature. I try to redirect with refresh and it just gives me a page that says "undefined". Now it will suddenly work when i remove the 'refresh' and just leave the controller name, but i'm trying to figure out why this 'refresh' won't work.
I've disabled my .htaccess
I've tried setting my $config['uri_protocol'] to REQUEST_URI, AUTO, and PATH_INFO
and had no luck.
Also, this is my first submission online to anything like a forum so please....be gentle.
First off, welcome to Stack Overflow.
Secondly, if redirect() without the "refresh" works, I would run with it and figure it out later.
For a deeper explanation, "refresh" attempts to do a meta-like refresh to the page similar to:
<meta http-equiv="refresh" content="0;URL='http://example.com/'">
(Note: It doesn't do that within your view, but rather sends the browser a similar snippet in the response)
What browser are you using? What version? Hopefully it's something up-to-date, because that could make a difference in how the refresh works.
I had similar problem. E.g. on my localhost refresh do not work and on the hosting provider settings it works. Maybe something in Apache/PHP configuration. Go without refresh, it is OK. I do not think it has something to do with a browser. I was using the same browser when that happened.

Categories