Laravel 4 Authentication not working with Subdomains - php

In my L4 App i use subdomains for my routing to different stuff.
accounts.domain.com = where alle the Authentication stuff happens
dashboard.domain.com = The main frontpage for authenticated users
community.domain.com = Community stuff for authenticated users.
If someone visits community.domain.com/forum and is not autenticated he should be send to accounts.domain.com, login and then get redirected back to the Forum.
But now i have 2 problems.
1 and major problem: afer the login the user is only autenticated for the domain: accounts.domain.com
for all other domains he gets redirected to the login.
If a user is autenticated and trys to access dashboard.domain.com he gets redirected to the login page.
and the 2. problem is the redirect after the login.
Atm i just have a static redirect after the login, doesn't matter where the user was coming from. How can i change it so he get redirected back to the page he tried to visited as unauthenticated user before?
My routes file:
Route::get('login', function()
{
return Redirect::action('AccountsController#getLogin');
});
Route::group(array('domain' => 'accounts.domain.com'), function()
{
Route::get('/', function()
{
return Redirect::action('AccountsController#getLogin');
});
Route::get('users/sing_in', array('as' => 'login', 'uses' => 'AccountsController#getLogin'));
Route::post('users/sing_in', array('as' => 'login', 'uses' => 'AccountsController#doLogin'));
Route::get('users/sing_out', array('as' => 'logout', 'uses' => 'AccountsController#doLogout'));
Route::group(array('before' => 'auth'), function() {
Route::get('users/profile', array('as' => 'profile', 'uses' => 'AccountsController#getProfile'));
});
});
Route::group(array('domain' => 'dashboard.domain.com'), function()
{
Route::group(array('before' => 'auth'), function() {
Route::get('/', array('as' => 'dashhome', 'uses' => 'DashboardController#getIndex')); //If someone tries to access this, he get redirected to the login page, even if he just authenticated himself
});
});
And my Login Controller:
public function getLogin()
{
if (Auth::check()) {
return Redirect::action('AccountsController#getProfile');
} else {
return View::make('login.index');
}
}
public function doLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required|min:3'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::route('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($userdata)) {
return Redirect::action('AccountsController#getProfile');
} else {
return Redirect::route('login')->withErros('Wrong E-mail address or Password');
}
}
}
public function doLogout()
{
Auth::logout(); // log the user out of our application
return Redirect::route('login'); // redirect the user to the login screen
}
Thanks for any help.

Set the domain in app/config/session.php to .domain.com, so a session gets shared between subdomains.
To redirect the user, you can return Redirect::back() or Redirect::route(<wherever the user should land>).

Related

Same route url use to multiple middlewares in laravel

I have two two middlewares. One is admin and another is teacher. In admin, will access all the created url and teacher will get only 2 or 3 url.
Here is my route
Route::group(['middleware' => ['adminAuth']], function () {
Route::get('dashboard', array('as' =>'Teacher Dashboard', 'uses' => 'UserController#dashBoard'));
Route::get('users/profile/edit/{id}', array('as' => 'User Profile Update', 'uses' => 'UserController#userProfile'));
Route::post('users/profile/update/{id}', array('as' => 'User Profile Update', 'uses' => 'UserController#updateUserProfile'));
Route::get('student/leave/application', array('as' => 'Student Leave Application', 'uses' =>'LeaveApplicationController#studentLeaveApplicationList'));
Route::get('leave/application/student/create', array('as' => 'Student Leave Application', 'uses' =>'LeaveApplicationController#studentLeaveApplicationCreate'));
Route::post('leave/student/application/store', array('as' => 'Student Leave Application', 'uses' =>'LeaveApplicationController#studentLeaveApplicationStore'));
Route::get('leave/student/application/categories', array('as' => 'Student Leave Application Categories', 'uses' => 'LeaveApplicationController#studentLeaveCategories'));
});
Route::group(['middleware' => ['teacherAuth']], function () {
Route::get('teacher/dashboard', array('as' =>'Teacher Dashboard', 'uses' => 'UserController#teacherDashBoard'));
Route::get('users/profile/edit/{id}', array('as' => 'User Profile Update', 'uses' => 'UserController#userProfile'));
Route::post('users/profile/update/{id}', array('as' => 'User Profile Update', 'uses' => 'UserController#updateUserProfile'));
});
I want to update each user profile from both middleware. it is working fine when i use profile update url for anyone middleware but when i use profile update url in both middleware then it not wokring just redirect to another url
Here is my middlewares logic
For Admin,Middleware/AdminAuth.php
public function handle($request, Closure $next)
{
$role = User::getUserById(Auth::id());
if(!(\Auth::check()) || ($role->role_name != "admin"))
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
} else {
\Session::flash('errormessage','Invalid Request');
\Session::put('pre_login_url',\URL::current());
return redirect()->guest('/auth/login');
}
}
return $next($request);
}
For Teacher, Middleware/TeacherAuth.php
public function handle($request, Closure $next)
{
$role = User::getUserById(Auth::id());
if(!(\Auth::check()) || ($role->role_name != "teacher"))
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
} else {
\Session::flash('errormessage','Invalid Request');
\Session::put('pre_login_url',\URL::current());
return redirect()->guest('/auth/login');
}
}
return $next($request);
}
Here is my Kernel.php
'adminAuth'=>\App\Http\Middleware\AdminAuth::class,
'teacherAuth'=>\App\Http\Middleware\TeacherAuth::class,
Laravel uses pattern matching for routes and it settles for the first one found. Middlewares don't change route paths so laravel will only recognise the first users/profile/update/{id} route.
You either change the route path so they're not exactly the same, or you go and separate the logic in your controller method. For example, in your UserController::updateUserProfile() method, you can create private methods updateTeacher(), updateAdmin(). So your logic can look like this:
if($role->role_name == "teacher")
{
return $this->updateTeacher();
} else if($role->role_name == "admin")
{
return $this->updateAdmin();
}
Which means you won't need those 2 middlewares. Just apply auth middleware on the route

Laravel 5.2 login with external validation does not persist

to login I'm using laravel with an external validation of user credentials, after redirection data stored in Auth::user() doesn't persist and Auth::check() = false, but the session data saved correctly. After the login if I enter to the dashboard I 'm redirected to the login.
Routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/test', [
'as' => 'test',
function () {
echo "Session------>";
var_dump(\Illuminate\Support\Facades\Session::get('user'));//Returns user data
echo "User------>";
var_dump(\Illuminate\Support\Facades\Auth::user());// Returns null
echo "\ncheck user.------->";
var_dump(\Illuminate\Support\Facades\Auth::check());//Returns false
}
]);
});
//Login
Route::group(['middleware' =>[ 'web']], function () {
Route::get('/login', ['as' => 'login', 'uses' => 'AuthController#login']);
Route::post('/login', ['as' => 'login', 'uses' => 'AuthController#loginpost']);
Route::get('/logout', ['as' => 'logout', 'uses' => 'AuthController#logout']);
});
Route::group(['middleware' => ['auth', 'web']], function () {
Route::get('/', ['as' => 'home', 'uses' => 'DashboardController#index']);
//Dashboard
Route::get("/dashboard", ['as' => 'dashboard', 'uses' => 'DashboardController#index']);
}
AuthController.php
class AuthController extends Controller
{
public function login()
{
return view('auth/login');
}
public function loginpost(LoginRequest $request)
{
$credentials = $request->only('username', 'password');
$loginRequest = new LoginUserRequest($credentials['username'], md5($credentials['password']));
$userRepo = new MongoUserRepository();
$service = new GetUserByCredentialsService($userRepo, $loginRequest);
$authUser = $service->handle(new UserObjectPresenter());
var_dump($authUser);
if (isset($authUser)) {
$us = new User();
$us->id = $authUser->id;
$us->email = $authUser->email;
$us->fullname = $authUser->fullname;
Auth::login($us);
$user = Auth::user();
Session::put('user', $user);
Session::save();
echo "----saved user------";
var_dump(Auth::user()); //Returns correct user data
echo "Auth::check()->";
var_dump(Auth::check()); //Returns true
return redirect()->route('test');
} else {
return redirect()->route('login')->withInput()->withErrors(['Invalid email or password.']);
}
}
}
$service->handle(new UserObjectPresenter()); returns null or user data if login is correct.
Use Auth::attempt after login we you actually starting your session, otherwise Auth::check always returns false,
use following code
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($userdata)) {
return view('dashboard');
}
You aren't passing an 'existing' user record to Auth::login. It has no id so it won't be able to be pulled back up on the next request.
Save that user record or use an existing one to pass to Auth::login

Auth not working in other module laravel 4 creolab

hi i create a project in hmvc architecture with creolab module in laravel 4 here
let say i divided my project into 3 module like example there
--module--
auth
shop
content
the scenario here user must login in auth modul first
after that they be able to access 2 module left (Shop & content)
when i try to auth protecting route in module shop or content like this example
Authenticating Group */
Route::group(array('before' => 'auth'), function() {
Route::get('shop', array(
'as' => 'shop',
'uses' => 'App\Modules\Shop\Controllers\ShopController#getShop'
));
});
i can't access it although i already success login in modul Auth
i already confirm it i success login with return string like this
i think the problem is here
in my module account, my accountController contain script like this
public function postLogin() {
$validator = Validator::make(Input::all(), array(
'username' => 'required',
'password' => 'required'
));
if($validator->fails()) {
return Redirect::route('login.post')
->withErrors($validator);
} else {
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
));
if($auth) {
return "login success";
// return Redirect::intended('shop');
}
else {
return Redirect::route('login')
->with('global', 'Email or Password Not Match');
}
}
}
when i return simple string (disable redirect) i got login successin screen that indicate i already success login, but when i active redirect to another module, i got push back to login page
i check auth state with this simple script in login page like this
#if (Auth::check())
{{ login }}
#else
{{ "not login "}}
#endif
and got not login text
can someone help me?
#update
public function postLogin() {
$validator = Validator::make(Input::all(), array(
'username' => 'required',
'password' => 'required'
));
if($validator->fails()) {
return Redirect::route('login.post')
->withErrors($validator);
} else {
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
));
if($auth) {
return Redirect::intended('shop');
}
else {
return Redirect::route('login')
->with('global', 'Email or Password Not Match');
}
}
}
#2nd Update
route in shop module
<?php
/* Authenticating Group */
Route::group(array('before' => 'auth'), function() {
Route::get('shop', array(
'as' => 'shop',
'uses' => 'App\Modules\Shop\Controllers\ShopController#getShop'
));
Route::post('shop', array(
'as' => 'shop.post',
'uses' => 'App\Modules\Shop\Controllers\ShopController#postShop'
));
Route::post('shop-delete', array(
'as' => 'shop.delete',
'uses' => 'App\Modules\Shop\Controllers\ShopController#postShopDelete'
));
});
#update my authentication filters.php
/*
|--------------------------------------------------------------------------
| 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');
}
}
});
Try this if it works.
if(Auth::attempt(['usernae' => Input::get('username'), 'password' => Input::get('password')]))
{
return 'login success';
}else{
return 'login failed';
}

laravel route on logged in not triggering

I'm trying to route the index page to a different location if logged in however even though my authentication system works, it's not redirecting to where I expected i.e. getLogged, instead it always redirects to getIndex whether I am logged in or not.
Route::filter('auth', function()
{
if (!Sentry::check()) return Redirect::to('/');
});
Route::group(array('before' => 'auth'), function() {
Route::get('/', array('uses' => 'MyController#getLogged'));
});
Route::get('/', array('before' => 'detectLang', 'uses' => 'MyController#getIndex'));
I tested to make sure my auth works by changing
Route::group(array('before' => 'auth'), function() {
Route::get('/', array('uses' => 'MyController#getLogged'));
});
to
Route::group(array('before' => 'auth'), function() {
Route::get('/dash', array('uses' => 'MyController#getLogged'));
});
and that properly behaves that I can only access /dash when I am logged in so why is my index route not working?
You're declaring the same route twice, it won't work. To achieve this functionality, instead of adding a auth filter, add a guest one that, instead of checking if the user is not connected, will check if it is. Something like this:
Route::filter('guest', function () {
if (Sentry::check()) return Redirect::route('logged');
});
Then, setup your routes, something along these lines:
Route::get('/', array(
'as' => 'home',
'uses' => 'MyController#getIndex',
'before' => 'guest'
));
Route::get('/logged', array(
'as' => 'logged',
'uses' => 'MyController#getLogged',
'before' => 'auth|detectLang'
));
Note: The as key gives a name to your route, so you can use it on Redirect::route or URL::route methods.

How to redirect an unauthorized user to the login page in Laravel?

I'm new to Laravel ( version 3 ), i do not know how to set Route and filters in Laravel so that any unauthorized user that is trying to access any url redirects to the login page (NOT the 404 error), in another word the default home page for unauthorized users is going to be the login page and for the authorized users it's going to be the dashboard.
If you are using laravel Auth class you can create an authorized route group. All routes that are defined there will be redirected if the user isn't logged in. Your router file will look something like this:
Route::get('/', array('as' => 'intro', 'uses' => 'intro#index'));
Route::get( 'login', array('as' => 'login', 'uses' => 'user#login'));
Route::get( 'logout', array('as' => 'logout', 'uses' => 'user#logout'));
// PROTECTED
Route::group(array('before' => 'auth'), function()
{
Route::get('dashboard', array('as' => 'dashboard', 'uses' => 'user#dashboard'));
});
// AUTH FILTER
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::to('login');
});
Just put a before filter in the declaration of the route like this
Route::get('edit_profile', array('before' => 'auth', function()
{
return View::make('profile.edit');
}));
The Auth filter exists by default in Laravel.

Categories