CodeIgniter 404 Bad request error - codeigniter

I'm working with codeIgniter. I am making a login form which checks the members details with the database.
However when I click to login I get this error message:
The requested URL /waitronmain/login.php/login/validate_credentials was not found on this server.
However this is my login.php file and as you can see validate_credentials() does exist.
class Login extends CI_Controller{
function index()
{
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
function validate_credentials()
{
//load model to query db
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query){ //if credentials validated
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this ->session->set_userdata($data);
redirect('site/members_area');
}
else{ //if not validated load login form again.
$this->index();
}
}
}
Any idea what's going wrong? I should be going on to the 'members_area' page as I know the details I am entering are correct.
Any help would be much appreciated.

what is this??
/waitronmain/login.php/login/validate_credentials
login.php should be not in url i think you should do:
/waitronmain/login/validate_credentials
(assuming you removed index.php from urls and you are inside the waitronmain/ root )

Related

Laravel Ajax login, redirect to previous url after success

Suppose I have a page A where auth middleware is being used. Because of no login it gets redirected to login page.
On login page I have custom ajax login system. On succesful login I want to redirect to page A with same url so that action can be completed.
My code for login is like this:
public function postLogin(Request $request)
{
$auth = false;
$errors = [];
$inputs = $request->all();
$validator = $this->validator($inputs);
if ($validator->fails()) {
return response()->json([
'auth' => false,
'intended' => URL::previous(),
'errors' => $validator->errors()
]);
}
$user = User::where('email', $request->get('email'))->first();
if ($user && $user->is_active == 0) {
$errors[] = "This account has been deactivated";
} else if ($user && $user->confirm_token != null) {
$errors[] = "Please verify your email in order to login";
} else {
$credentials = ['email' => $request->get('email'), 'password' => $request->get('password'), 'is_active' => 1];
if (Auth::attempt($credentials, $request->has('remember'))) {
$auth = true;
} else {
$errors[] = "Email/Password combination not correct";
}
}
if ($request->ajax()) {
return response()->json([
'auth' => $auth,
'intended' => URL::previous(),
'errors' => $errors
]);
}
return redirect()->intended(URL::route('dashboard'));
}
I am trying to get previous url through url()->previous() but it returns login page url. Can someone guide me in this please. Any improvements/help will be appreciated.
I am using Laravel 5.4
I have a very similar problem here: Ajax Auth redirect on Laravel 5.6
As #aimme (https://stackoverflow.com/users/1409707/aimme) pointed out, Ajax calls are stateless, so basically you can't interact with backend.
His suggestion and my suggestion is to pass in the URL the intended page to redirect to, or maybe in your case you could to it via post parameters, e.g.:
return response()->json([
'auth' => false,
'intended' => $request->intended,
'errors' => $validator->errors()
]);
There is no need to do anything special for AJAX calls.
Redirect the same way you normally would on the back-end after a form submission.
return redirect()->route('dashboard');
On the front-end you just need to be sure that you use the redirected URL to change the window.location. This will cause the browser to refresh and go to the new page.
axios.post(url, formData).then(response => {
window.location = response.request.responseURL;
});
This code snippet is for the popular Axios library but the same thing can be done with jQuery or vanilla JavaScript.
It might help you
Instead of these return redirect()->intended(URL::route('dashboard'));
use
return redirect('dashboard');
Laravel 5.4 + support . not know for lower version
return redirect()->back();
This will redirect to previous page from where you came .
Ajax part
<script type="text/javascript">
var url = "<?php echo url()->previous(); ?>";
location.href = url;
</script>
OR simply javascript function
history.go(-1);
Check for above and working fine for me please check for your code .
If I understand your problem correctly, the problem is that you're confusing the previous URL for the intended URL when you're trying to provide a URL to redirect to in your JSON response. The previous URL actually refers to the HTTP Referrer, not the intended URL, which is set in the session by Laravel's auth middleware.
The HTTP referrer is the page that initiates a request. If you are currently on page /foo and you click a link to a page /bar, the HTTP Referrer on /bar will be /foo. The same thing happens when you initiate an AJAX request, the page you're on will be the referrer of the end point you're hitting. In your case your login page is initiating the request to your login handler, via AJAX.
When you try to visit a page protected by Laravel's auth middleare, it is at that point Laravel sets a value for the intended URL in the session, before redirecting you to the login page. Laravel stores the intended URL in the session as url.intended (As you will be able to see in Illuminate\Routing\Redirector::intended, which is what redirect()->intended() calls). So all you need to do is grab that from the session.
if ($request->ajax()) {
return response()->json([
'auth' => $auth,
'intended' => session()->pull('url.intended') ?: URL::route('dashboard'),
'errors' => $errors
]);
}
return redirect()->intended(URL::route('dashboard'));
Note: Using ->pull will remove the item from the session after it has been retrieved.
An easier way to do this would be just to grab the target URL from an intended RedirectResponse:
$redirect = redirect()->intended(URL::route('dashboard'))
if ($request->ajax()) {
return response()->json([
'auth' => $auth,
'intended' => $redirect->getTargetUrl(),
'errors' => $errors
]);
}
return $redirect;
I solved it by making a hidden field in form containing url()->previous() value because no other way I was getting previous page i.e Page A url. I tried almost all above answers.
URL::previous();
this method will help you get previous URL. and you can redirect user to there using jQuery somelike this:
window.location.href = url; // <- you can try your url here.
Good Luck !!
First of all when you got a request in backend save the redirect()->intended();
intended() checks if the session index url.intended exists and
redirects to it by default or else redirect to $default='/' which can
be overwritten.
then pass this URL when request success, example:
function testAjax(handleData) {
$.ajax({
url:"getvalue.php",
success:function(data) {
window.location.href = data.url;
}
});
}

Codeigniter 3 login check function not showing correct flashdata messages

I am creating a login check function. But my two flash data messages are not setting correct.
If user has logged on and then if the session expires it should set this
flash data message Your session token has expired!
And if the user has not logged on and tries to access a controller with out logging on
then it should set this flashdata message You need to login to
access this site!
For some reason it is always showing the second flashdata message.
Question: How am I able to use the two flashdata messages properly.
Controller: Login.php
Function: check
public function check() {
$uri_route = basename($this->router->directory) .'/'. $this->router->fetch_class();
$route = isset($uri_route) ? $uri_route : '';
$ignore = array(
'common/login',
'common/forgotten',
'common/reset'
);
if (!in_array($route, $ignore)) {
// $this->user->is_logged() returns the user id
if ($this->user->is_logged()) {
// $this->session->userdata('is_logged') returns true or false
if (!$this->session->userdata('is_logged')) {
// Redirects if the user is logged on and session has expired!
$this->session->set_flashdata('warning', 'Your session token has expired!');
redirect('admin/common/login');
}
} else {
$this->session->set_flashdata('warning', 'You need to login to access this site!');
redirect('admin/common/login');
}
}
I run function via codeigniter hook that way I do not have to add it on every controller.
$hook['pre_controller'] = array(
'class' => 'Login',
'function' => 'check',
'filename' => 'Login.php',
'filepath' => 'modules/admin/controllers/common'
);
What are you trying to check via the uri() is actually a very bad way of checking, also you should include login checks as a construct function not single.. here is what your function should look like:
function __construct()
{
parent::__construct();
if (!$this->session->userdata('logged_in')) {
// Allow some methods?
$allowed = array(
'some_method_in_this_controller',
'other_method_in_this_controller',
);
if (!in_array($this->router->fetch_method(), $allowed)
{
redirect('login');
}
}
}

Redirects an authenticated user back to the originally requested URL or the default URL in laravel

I am new at laravel and I want to achieve the following results, let's say a guest gets to the result page after searching for a term and then decides to login, how can I get the user to login and keep the same result page in laravel
I have the following code
in the filters.php I have the following:
Route::filter('guest', function()
{
if (Auth::check()) return Redirect::to('/');
});
then in the user controller I have the following
the show login function
public function login()
{
return View::make('users.login');
}
the handle login function
public function handleLogin()
{
$data = Input::only(['email', 'password']);
if(Auth::attempt(['email' => $data['email'], 'password' => $data['password']])){
return Redirect::to('/profile');
}
return Redirect::route('login')->withInput();
}
right now the default page after login goes to the profile page but I want the user to go back to wherever he was before login.
any help? thanks
I think that's what you looking for
return Redirect::back();
In Laravel 4, you can use Redirect::guest and Redirect::intended to achieve your target easily.
Redirect::guest put the current URL into the session before redirect to the target URL.
Redirect::intended check whether there is any URL saved in the session, redirect to that URL or a default location if it does not exist.
In action, your code can be:
if(Auth::attempt(['email' => $data['email'], 'password' => $data['password']])){
return Redirect::guest('/profile');
}
and after log in
if (Auth::check()) return Redirect::intended();

How to redirect user depending on user type at time of login (codeigniter)

I'm facing problem while redirecting my user according to its type. how can do it here's my code please suggest how to do it.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->model('user','',TRUE);
//This method will have the credentials validation
$this->load->library('form_validation');
$this->load->library('session');
$this->form_validation->set_rules('username', 'Username','trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password'
'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
validation_errors();
$this->load->view('error');
}
else
{
//Go to private area
basically here I want to redirect if user is admin then redirect to admin page else redirect to home. How can I do this ???
redirect('home', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
}
?>
The way I do this is by joining the user with a roles table. Each user is assigned to a role (such as salesperson, accounting manager, etc.). Each role has an optional home page to redirect to after login. If it's not set, it redirects to a default page.
Okay, well you say you have a login function so here are the basics. What Mike is saying is right and how I do it, but if you only have two types of users a roles solution is probably overkill. Personally I use the roles to populate a user menu, all users get the same menu, the options change depending on what portions of the site they're allowed to see.
For a basic admin/user though that's really not necessary. What you need to do is just redirect based on usergroup after login, so something similar to this.
$this->db->where(username, $username);
$this->db->where(password, $password);
$query = $this->db->get(users);
if($query->num_results() ==1)
{
$result = $query->result_array();
switch ($result['usergroup']) {
case '1':
redirect 'home';
break;
case '2':
redirect 'admin';
break;
default:
redirect 'home';
break;
}
}
As I said this is a basic solution that you can use for a few different roles, if you want to do anything more complicated investigate creating roles.
You'll also want to save the usergroup to the session and check it on admin pages, if the user isn't an admin redirect them away from the page.

Codeigniter: Controller function name shows in url, how change to view file name?

wondering if anyone can guide me to what ive done wrong (or need to do) and think the problem is in my routes file. When the user is displayed the login form and for example they get their username wrong after submit the url displays as this: http://localhost:8888/codeigniter/login/login_validation. When the are successful and log into the admin area (which pulls news articles from the db) this url is still shown. I am wondering if there is a way to make it to http://localhost:8888/codeigniter/news. I have looked in my routes folder and i tried to use 'wildcards' and was unsuccessful. Here is my code for reference, any other info or files needed let me know! Thanks.
CONTROLLER:
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('login');
}
//Validate login area
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required|xss_clean|callback_password_check');
if($this->form_validation->run() == FALSE) {
//Field validation failed. User redirected to login page
$this->index();
}else{
$this->load->model('user_model');
$query = $this->user_model->login_details();
// if the user's credentials validated...
if($query) {
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('news');
}else{
$data['error'] ="Invalid Username or Password";
$this->load->view('login',$data);
}
}
}
function logout() {
$this->session->sess_destroy();
$this->index();
}
}
login_details function from user_model.php
function login_details() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('login');
if($query->num_rows == 1){
return true;
}
}
If you're logging into any kind of system, you're going to need to store a session using CodeIgniter's Session class. Provided controllers/news.php exists, you can set the session and immediately just perform a redirect with redirect('news');. No need to $this->load->view() because this logic will be in news.php's index anyway and you'd be duplicating code.
I'm not sure what $this->user_model->login_details() is returning, but I'm assuming false or null because you say CodeIgniter is sending you back to the login view. Head into the login_details() function and make sure things are working properly (you might want to post it too). Also, post your routes.php file for us if you made changes just in case.
On a side note: Space is a valid password character, don't trim it or folks with leading or trailing space's in their passwords won't be able to get in ;)

Resources