Laravel AuthController not working when ajax request pass - php

I am adapting the out-of-the-box AuthController in Laravel 5.2 to suit my needs. I want to implement login form using AJAX. For that I write the code. But when I click on login button then show 302 error and redirect. I don't know what is my mistake.
My JS
function do_login()
{
frm_name = 'userlogin';
username = $('#userlogin input[id=email]').val();
password = $('#userlogin input[id=password]').val();
_token = $('#userlogin input[id=_token]').val();
if(username == '' || password == '') {
$('#flashMessage').attr('class','alert alert-danger');
$('#flashMessage').html('Please specify Username and Password');
} else {
var param = 'username='+ username+ '&password='+ password +'&_token='+ _token;
$.ajax({
type : "POST",
datatype : "json",
url: "auth/login",
data : param,
success : function(data) {
data = JSON.parse(data);
if (data.status == 0) {
$('#myModallogin').modal('hide');
window.location.href = data.redirect_url;
}
if (data.status == 1) {
$('#flashMessage').attr('class','alert alert-danger');
$('#flashMessage').html(data.message);
} else {
onError(data.Error,'#'+ frm_name);
}
}
});
}
}
$(document).ready(function(){
$('#member_login').click(function() {
do_login();
});
});
My route
Route::auth();
Route::post('auth/login', 'Auth\AuthController#userLogin');
My AuthController
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
//protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
public function userLogin() {
$post_data = Request::all();
pr($post_data);exit;
}
}
My route is working properly because when I debug the routes for example Route::post('auth/login', function(){ echo 'aaaaaaaaaa'; }); so it display the aaaaaa. But when I called the function then show 302 error and redirect the page. I don't know what is my mistake. Please suggest me.

Related

laravel login refresh page

My laravel project doesn`t working on the hosting.But everything works perfectly on the local server(
When i switch to mysite.com, the index page "login" and enter the data in login form, tpage just refreshed
At the same time, if I go to mysite.com/register, I will be able to register a new user and write this data to the Users table in my database
I try make routes for test
Route::get('/test', function(){
return User::All();
//this returned all users in DB(ill check connection with my DB)
});
Route::get('/test', function(){
$user = Auth::user();
print_r($user);
//this returned NULL
});
I understand the Auth::login function writes the authenticated user to a session and fills the memoer_token field into the database in the user table. In the table itself token is written, but in the session nothing is written.
But idk how to fix it, if it`s true
UPD:
I tried to step by step replace my project files with an earlier version (which works correctly).
I find were is my problem. In "resource" folder - file login.blade
In last version i changed standard input "email" to "username"
And now I write the field username
Judging from the above, the problem is that he is expecting a return email? Perhaps somewhere in the validation of data? And why then in the local version of the site everything works well?
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
protected $redirectTo = '/user';
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
// protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function redirectTo()
{
if (Auth::user()->role === User::IS_ADMIN && Auth::user()->user_verify === 1) {
return '/admin';
}elseif(Auth::user()->role === User::IS_USER && Auth::user()->user_verify === 1 || Auth::user()->role === User::IS_USER && Auth::user()->user_verify === 0){
return '/user';
}
}
}
Route::get('/', function () {
if(Auth::check()){
$user = Auth::user();
if($user->role == 1 && $user->user_verify == 1){
return redirect('/admin');
}
elseif($user->role == 0 && $user->user_verify == 1
|| $user->role == 0 && $user->user_verify == NULL
|| $user->role == 0 && $user->user_verify == 2){
return redirect('/user');
}
}else{
return view('auth.login');
}
});
I found a solution to this problem!
In the LoginController.php file, override the username method by which field to log in. A small email and name input example
public function username(): string
{
$login = request()->input('email');
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'name';
request()->merge([$field => $login]);
return $field;
}

On Axios request laravel auth attemp session part not working

am making a login screen using bootstrap model and when I request using axisos call to server everything working fine but when the response came and I refresh page laravel session part not working
here is my code in controller :
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('login');
}
//use AuthenticatesUsers;
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'phone' => 'required|numeric|',
'password' => 'required|min:6',
]);
if ($validator->fails()) {
// return redirect()->back()->with('errors',$validator->errors())->withInput($request->only('phone', 'remember'));
return response()->json(['success'=>false,'error'=>$validator->errors()], 403);
}
// Attempt to log the user in
if (Auth::guard('web')->attempt(['phone' => '+91'.$request->phone, 'password' => $request->password], $request->remember)) {
// if successful, then redirect to their intended location
return response()->json(['success'=>true,'message'=>'login successfully'], 200);
}
// if unsuccessful, then redirect back to the login with the form data
//dd('auth fail am here');
//return redirect()->back()->withErrors(['Invalid Phone Or Password'])->withInput($request->only('phone', 'remember'));
return response()->json(['success'=>false,'error'=>'Invalid Phone Or Password'], 401);
}
/**
* Where to redirect users after login.
*
* #var string
*/
// protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function logout()
{
Auth::guard('web')->logout();
return redirect('/login');
}
}
this is my axios request:
axios.post(process.env.MIX_BASEURL+'/login', vm.loginDetails)
.then(response => {
event.target.disabled = true;
console.log(response);
// console.log(response.config.method)
if (response.status == 200){
alert('login success')
vm.loginsuccess = true
$("#phone").addClass("is-valid");
$("#password").addClass("is-valid");
vm.successlogin=response.data.message
toastr["success"](vm.successlogin);
if(response.status===200){
let intended=response.data.intended;
alert(intended);
//return;
window.location.href = intended;
this.closeModal();
}
}
})
.catch(error => {
console.log('am here in error');
console.log(error.response);
var errors = error.response
console.log(error.response)
///IF EMPTY FIELDS FOUND///
if (errors.status === 403) {
//alert('empty fields Forbidden')
//alert(errors.data.error.phone[0])
if (errors.data) {
if (errors.data.error.phone) {
vm.errorsPhone = true
$("#phone").addClass("is-invalid");
vm.PhoneError = _.isArray(errors.data.error.phone) ? errors.data.error.phone[0] : errors.data.error.phone
//alert(vm.PhoneError)
toastr["error"](vm.PhoneError);
}
if (errors.data.error.password) {
vm.errorsPassword = true
$("#password").addClass("is-invalid");
vm.passwordError = _.isArray(errors.data.error.password) ? errors.data.error.password[0] : errors.data.error.password
//alert(vm.passwordError)
toastr["error"](vm.passwordError);
}
}
}
if (errors.status === 401) {
//alert('invalid login details')
vm.errorslogin = true
vm.loginerror=errors.data.error
//alert(vm.loginerror)
toastr["error"](vm.loginerror);
}
});
}
**what i have try :**when i click on login my data is gone auth attemp successfull i got 200 and my msg as i set in response then i call to location reload (my first try and fail) it reload page for new data but session data not coming in my blade template

profile is not showing when I login with facebook using satellizer with laravel

I know my question is not specific but I want to discuss my problem.
I want to do social login in angular with laravel so I am using satelizer social login. Login and logout is working fine but When I click on profile it's showing en error. I don't know where is the problem. Please help me out If anyone have a solution.
Error is
and my code is :-
angular Routes
$stateProvider.state('profile', {
url: '/profile',
templateUrl: 'partials/profile.html',
controller: 'ProfileCtrl',
resolve: {
loginRequired: loginRequired
}
});
Profile Controller
angular.module('MyApp')
.controller('ProfileCtrl', function($scope, $auth, toastr, Account) {
$scope.getProfile = function() {
Account.getProfile()
.then(function(response) {
$scope.user = response.data;
})
.catch(function(response) {
toastr.error(response.data.message, response.status);
});
};
$scope.getProfile();
Account Service
angular.module('MyApp')
.factory('Account', function($http) {
return {
getProfile: function() {
return $http.get('/satellizer/examples/server/php/public/api/me');
},
updateProfile: function(profileData) {
return $http.put('/satellizer/examples/server/php/public/api/me', profileData);
}
};
});
Laravel Routes
// API Routes.
Route::get('api/me', ['middleware' => 'auth', 'uses' => 'UserController#getUser']);
Laravel COntroller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Config;
use Firebase\JWT\JWT;
use App\User;
class UserController extends Controller {
/**
* Generate JSON Web Token.
*/
protected function createToken($user)
{
$payload = [
'sub' => $user->id,
'iat' => time(),
'exp' => time() + (2 * 7 * 24 * 60 * 60)
];
return JWT::encode($payload, Config::get('app.token_secret'));
}
/**
* Get signed in user's profile.
*/
public function getUser(Request $request)
{
$user = User::find($request['user']['sub']);
return $user;
}

Laravel white screen when using Redirect Class

I am currently getting a white screen of death when I am trying to redirect my users using the Laravel Redirect class after handling data. If I use the native php-function header("location ...") the application responds correctly and sends the user on its merry way, but using Laravel's Redirect class the site crashes with a white screen of death. I have tried both the Redirect::action and Redirect::to functions, but they are both resulting in the same irritating white screen of death. The laravel.log shows nothing...
Does anyone have any ideas?
Here is the code for the data handler controller class:
<?php
class ManagerLayoutDataController extends BaseController
{
public function route($action, $moduleID) {
if(method_exists('ManagerLayoutDataController',$action)) {
$this->$action($moduleID);
}
// Invalid action (method not found)
else {
die('Action routing error');
//return Redirect::to('/');
}
}
public function updateHeaderBg($moduleID) {
$image = Input::file('img');
$user = Auth::user();
$siteID = $user->getSiteID();
$layoutDataMessage = null;
// Validate file upload (NOT FILE CHARACTERISTICS)
if(Input::hasFile('img') && $image->isValid() && isset($siteID) && $siteID !== "") {
$res = ManagerFileUpload::uploadImage($siteID, $image);
if($res->success) {
$fileName = $res->fileName;
$dbViewModule = ViewModuleRepository::getModule($moduleID);
if($dbViewModule->type === DBViewModule::MODULE_TYPE_HEADER) {
$headerModule = new HeaderModule($dbViewModule);
$headerModule->updateBgImage($fileName);
$layoutDataMessage = new LayoutDataMessage(LayoutDataMessage::STATUS_SUCCESS,"");
}
}
else {
$layoutDataMessage = new LayoutDataMessage(LayoutDataMessage::STATUS_FAIL,$res->message);
}
}
else {
$layoutDataMessage = new LayoutDataMessage(LayoutDataMessage::STATUS_FAIL, "Bilden kunde inte laddas upp.");
}
if($layoutDataMessage != null) {
return Redirect::action('ManagerLayoutController#main')->with('message',$layoutDataMessage);
//return Redirect::to('manager/layout/');
//header('location: */manager/layout');
}
else {
return Redirect::action('ManagerLayoutController#main')->with('message',LayoutDataMessage(LayoutDataMessage::STATUS_FAIL, "Bilden kunde inte laddas upp."));
//return Redirect::to('manager/layout/');
//header('location: */manager/layout');
}
}
}
The Main Controller
<?php
class ManagerLayoutController extends BaseController
{
public function main() {
$user = Auth::user();
$siteID = $user->getSiteID();
$moduleComposition = ViewModuleCompositionRepository::getCurrentInWorkModuleComposition($siteID);
$dbViewModules = ViewModuleRepository::getModulesFromComposition($moduleComposition->id);
$viewModules = array();
foreach($dbViewModules as $dbViewModule) {
switch($dbViewModule->getType()) {
case DBViewModule::MODULE_TYPE_HEADER:
$viewModules[] = new HeaderModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_TEXT_SECTION:
$viewModules[] = new TextSectionModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_KEY_METRICS:
$viewModules[] = new KeyMetricsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_SLIDESHOW:
$viewModules[] = new SlideShowModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_VACANCIES:
$viewModules[] = new VacanciesModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_EMAIL_SUBSCRIPTION:
$viewModules[] = new EmailSubscriptionsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_CO_WORKERS:
$viewModules[] = new CoworkersModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_NEWS_SECTION:
$viewModules[] = new NewsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_INSTAGRAM_FEED:
$viewModules[] = new KeyMetricsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_SOCIAL_MEDIA:
$viewModules[] = new KeyMetricsModule($dbViewModule);
break;
}
}
$data = array(
'siteID' => $siteID,
'viewModules' => $viewModules
);
return View::make('dashboard.pages.manager.layout_main',$data);
}
}
filters.php
<?php
/*
|--------------------------------------------------------------------------
| Application & Route Filters
|--------------------------------------------------------------------------
|
| Below you will find the "before" and "after" events for the application
| which may be used to do any work before or after a request into your
| application. Here you may also register your custom route filters.
|
*/
App::before(function($request)
{
//
});
App::after(function($request, $response)
{
//
});
/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Route::filter('auth.basic', function()
{
return Auth::basic();
});
/*
|--------------------------------------------------------------------------
| Guest Filter
|--------------------------------------------------------------------------
|
| The "guest" filter is the counterpart of the authentication filters as
| it simply checks that the current user is not logged in. A redirect
| response will be issued if they are, which you may freely change.
|
*/
Route::filter('guest', function()
{
if (Auth::check()) return Redirect::to('/');
});
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
/** Admin pages */
Entrust::routeNeedsRole( 'admin*', 'Admin', Redirect::to('/login'));
/** Manage pages */
Entrust::routeNeedsRole( 'manager*', array('Super Manager','Manager'), Redirect::to('/login'), false );
/**
* Check view module ownership before editing data
*/
Route::filter('viewmodule.ownership', function($route) {
$user = Auth::user();
$siteID = $user->getSiteID();
$moduleID = $route->getParameter('moduleID');
// Check that the module with $moduleID belongs to $siteID
if(ViewModuleRepository::moduleBelongToSite($moduleID, $siteID)) {
}
// Unauthorized access
else {
die('Filter error');
//Redirect::to('/');
}
});
routes.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', 'FrontController#main');
Route::get('/manager', 'ManagerHomeController#home');
Route::get('/manager/statistics', 'ManagerStatisticsController#main');
Route::get('/manager/resume-manager', 'ManagerResumeController#main');
Route::get('/manager/resume-manager/pending', 'ManagerResumeController#resumesPending');
Route::get('/manager/resume-manager/approved', 'ManagerResumeController#resumesApproved');
Route::get('/manager/resume-manager/rejected', 'ManagerResumeController#resumesRejected');
Route::get('/manager/layout', 'ManagerLayoutController#main');
Route::get('/manager/layout-old', 'OLDManagerLayoutController#main');
Route::post('/manager/layout/data/{action}/{moduleID}/', array('before'=>'viewmodule.ownership', 'uses' => 'ManagerLayoutDataController#route'));
Route::get('/manager/setup', 'ManagerSetupController#setup');
Route::get('/admin', 'AdminHomeController#home');
Route::get('/login', 'UsersController#login');
Route::get('/test', 'TestController#testMail');
// Confide routes
Route::get('users/create', 'UsersController#create');
Route::post('users', 'UsersController#store');
Route::get('users/login', 'UsersController#login');
Route::post('users/login', 'UsersController#doLogin');
Route::get('users/confirm/{code}', 'UsersController#confirm');
Route::get('users/forgot_password', 'UsersController#forgotPassword');
Route::post('users/forgot_password', 'UsersController#doForgotPassword');
Route::get('users/reset_password/{token}', 'UsersController#resetPassword');
Route::post('users/reset_password', 'UsersController#doResetPassword');
Route::get('users/logout', 'UsersController#logout');
Try to add
ini_set('display_errors', 1);
It should at least tell you what is the actual error.
This is only for development mode, remove it when you go into production
Look if there is a "return" before the Redirect. For example:
// Unauthorized access
else {
die('Filter error');
//Redirect::to('/');
}
Here should be return Redirect::to('/');

Laravel 4 redirect issue with login page

I am using laravel 4 and here is my AdminController file :
class AdminController extends BaseController {
protected $layout = "admin.layout";
public function __construct() {
// security for the forms and access
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth.admin' , array('except' =>array('getIndex','postSignin')));
// using this one to display user value if login and is admin
if (Auth::check() && Auth::user()->isAdmin()){
$this->user = Auth::getUser();
View::share('user', $this->user);
}
}
// main admin page
public function getIndex(){
$this->layout->content = View::make('admin.login');
}
// get the dashboard page
public function getDashboard() {
$this->layout->content = View::make('admin.dashboard');
}
// missing pages all redirect to dashboard if user is logged in.
public function missingMethod($parameters = array()){
if (Auth::check() && Auth::user()->isAdmin())
$this->getDashboard();
else
$this->getIndex();
}
Here is my filters.php file :
Route::filter('auth.admin', function()
{
if(!Auth::check() && !(Auth::user()->isAdmin())){
return Redirect::guest('admin');
}
});
in my routes.php file I am doing this:
Route::controller('admin', 'AdminController');
here is what I want if you could help me :_
1) . I want to clean up my code where there is not that much checking for if user is logged and isAdmin.
2). right now if you are logged in and you go to "admin/" , it will show you the login page ? how could I fix it in an effective way.
3). also if you are not logged in and you go to "admin/dashboard" it will show you dashboard content ? how to fix
Thank you in advance for all your help :)
You can use route groups and use a single filter to validate them
Check the docs
http://laravel.com/docs/routing#route-groups
Add this in your routes.php file:
Route::group(array('before' => 'auth.admin'), function() {
Route::controller('admin', 'AdminController');
})
Declare filter in filters.php file:
Route::filter('auth.admin', function(){
// Assumed you have a '/login' url
if (Auth::guest() || (Auth::check() && !Auth::user()->isAdmin())) {
return Redirect::guest('login');
}
});
Also make sure you have the user()->isAdmin() method in your User model that you are using and it checks whether the user is an admin or not and returns a Boolean value, TRUE if the user is an admin otherwise FALSE.

Categories