Same Url but different controller after logged in to the application - url

I want to make simple application using laravel5.2 in which there will come sign in form on base url when i log in to the application there need to give a different view i.e. Client dashboard at same url. How can i do that Please help me. Thanks In Advance !

You could do something like this for root / URL:
Route::get('/', function(){
if (!Auth::check()) {
return View::make('login'); // login view if not authenticated
// or call controller for login
}
else{
return View::make('dashboard'); // dashboard view if authenticated
// or call controller for dashboard
}
});

This is very simple. You have to just make a function in WelcomeController or in other controller. And do check if user is already login or not and redirect to proper view page accordingly.
For example :
In your routes.php file write route like this
$router->get('/',array(
'as' => 'home',
'uses' => 'WelcomeController#welcome'
));
And in your controller ,in case of this example : WelcomeController make a function named welcome and do some auth check like this
public function welcome()
{
if(Auth::check()){
//get some data for user dashboard
return view('dashboard');
}
return view('login');
}
PS: for good practice, use dependency injection. In this case inject Guard
class instead of using Auth facade.

Related

Laravel 5 Redirecting to login page after authentication instead of Dashboard

I have this problem, my application should redirect users to admin area whose routes are protected (have middle auth). When I login it redirects to login page again but when place the dashboard route outside the route group, it behaves well. What may be the problem? This is my code:
Code for protected route (does not work) after login
Route::group(['middleware'=>'auth'], function(){
Route::get('backend/dashboard', array('as'=>'dashboard', 'uses'=>'BackendDashboardController#getDashboard'));
});
Code for dashboard route placed outside the route group (Works well after login)
Route::get('backend/dashboard', array('as'=>'dashboard', 'uses'=>'BackendDashboardController#getDashboard'));
Auth controller - Post login function
protected function postLogin() {
$request = Input::all();
$user = array(
'email' => $request['email'],
'password' => $request['password']
);
if ($this->auth->attempt($user)) {
return redirect(route('dashboard'));
}else{
return redirect(route('login'));
}
}
I really want to protect my admin routes and place all of them under auth middleware. Kindly avice
It only redirects, if you are not authorize/loggedin, otherwise it works fine.
and I think you are missing something in Route::group() you also need to mention the prefix eg
Route::group(['prefix'=>'backend', 'middleware'=>'auth'], function(){
Route::get('dashboard', array('as'=>'dashboard', 'uses'=>'BackendDashboardController#getDashboard'));
});
Edited
Also try to update your attempt method, then try it, eg:
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('dashboard');
}

Hide the ID in the URL

In Grails the URL like this
http://localhost:8080/MyApp/show/2
is there a way to hide or to encrypt the id part
/2
i need to do this to prevent users to access others data , for instance my ID is 3 , i could access other user's data by typing
/show/4
You can encode the url. If you replace the 2 with %32, the browser will still interpret it as the character 2. Here is a complete list of characters.
You can send POST request instead of GET - this is an easy way of hiding such a request parameters f.e. in server log files.
Or you can play with GRAILS codecs.
I would not hide the ID from the url. Why? because this would only mask the problem.
Consider having a class defined as :
class Post {
String title
String content
User user //you need this to keep track of the posts owner
//You could use your own custom class or the one used in spring security
...
}
If you use Spring Security Core, you would use a fucntion similar to:
def springSecurityService
#Secured(['ROLE_USER'])
def myFunction(Long id){
def postInstance = Post.read(id)
if(postInstance){
if (postInstance.user.id ==(long)springSecurityService.principal.id){
// springSecurityService?.principal?.id retrieves the id of the user in session
//... redirect to details of whatever you need
}else{
//... redirect because it is not the owner of the post
}
}
else{
//... Redirect or something
}
}
If you are using a simple session you would need to have a function like
def myFunction(Long id){
def postInstance = Post.read(id)
long userId = session["user_id"]
if(postInstance && userId > 0){
if (postInstance.user.id ==userId){
//... redirect to details of whatever you need
}else{
//... redirect because it is not the owner of the post
}
}
else{
//... Redirect or something
}
}
The logic is very similar. Still in my humble opinion you should use the spring Security plugin.

Create a general rule for urls in Laravel

I want to redirect users back to the login page if they attempt to access certain pages on my site. I want to create a general rule so that I do not have to implement it on every page for every url separately.
For example if user try to access /profile , I want them to redirect back to login page if they are not logged in. I tried doing this using group routes by putting an if condition but that did not work. Moreover I am not an expert in laravel. This is what I tried.
Route::group(['prefix' => '/users'], function () {
if(Auth::user()){
Route::get('/','FacebookControllers\FacebookPagesController#listUsers');
Route::get('{id}/profile', 'FacebookControllers\FacebookPagesController#userProfile');
}
else {
return redirect('/');
}
});
Check out laravel's Auth middleware.
Documentation here: laravel.com/docs/5.1/routing#route-groups
Example (taken from the docs):
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});

ZfcUser Redirect Roles to different Pages after Login

I'm using the ZfcUser and BjyAuthorize in my Project. If a user logged in, he will be redirected to my default route.
But i want to change it, so if a User with role A will redirected to Page A and user with role B will redirected to page B.
Any idea, how to realize this?
I have actually done this and created the merge request in GitHub. It's actually a very small change that needs to be done in zfc-user/src/ZfcUser/Controlelr/UserController.php. Within authenticateAction() you need to replace this:
return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
For this:
$route = $this->getOptions()->getLoginRedirectRoute();
if(is_callable($route)) {
$route = $route($this->zfcUserAuthentication()->getIdentity());
}
return $this->redirect()->toRoute($route);
And in your config/autoload/module.zfcuser.global.php file you'll be able to use a callback for the login_redirect_route:
'login_redirect_route' => function(\ZfcUser\Entity\UserInterface $user) {
if($user->getUsername()=='Admin') {
return 'admin';
}
return 'user';
}
As I have to check several things depending on the role I've create a simple module than once the users is logged (default route after loggin) and depending on the role (avaliable through bjyautorize) redirects the application to the correc url.
Maybe it's not an elegant way but you don't have to modify zfcUser code.
You can setup redirect after login in config file.
'login_redirect_route' => '/your-url',
your-url accessible from all type of user and then create switch case to match your role and redirect page to role specific page.
$roles = $this->serviceLocator->get('BjyAuthorize\Provider\Identity\ProviderInterface')->getIdentityRoles();
switch ($roles){
case "admin":
$this->redirect()->toRoute('user_admin');
case "user":
$this->redirect()->toUri('user.html');
}
Suppose you have an 'admin' role in bjyauthorize that you want to redirect to another route.
In your loginAction replace the code:
if ($this->zfcUserAuthentication()->getAuthService()->hasIdentity()) {
return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
}
with this code:
if ($this->zfcUserAuthentication()->getAuthService()->hasIdentity()) {
$roles = $this->serviceLocator->get('BjyAuthorize\Provider\Identity\ProviderInterface')->getIdentityRoles();
if (in_array('admin',$roles))
{
return $this->redirect()->toRoute('admin_route');
} else {
return $this->redirect()->toRoute('user_route');
}
}

Zend Framework 2 - Hide login link when logged in and vice versa for logout

I'm pretty new to ZF2 and I'm trying to find a simple way to allow the login link to be hidden within the view a user has been logged in, and show it again when the user logs out. I have taken a look at ZF2's ACL examples, but I am still a little confused and I am unsure if this is actually what is needed to achieve such a simple thing.
If somebody could share some knowledge on how this is done, I would be eternally greatful. Thank you
The standard Identity view helper that can help you with this. This will work out of the box if you add your authentication service to the service manager, for instance in your module's config/module.config.php like this:
/* Some configuration omitted */
return array(
'service_manager' => array(
'Zend\Authentication\AuthenticationService' => function($sm) {
$authService = new \Zend\Authentication\AuthenticationService();
$authService->setStorage(new \Zend\Authentication\Storage\Session('user', 'details'));
return $authService;
},
),
);
Then you can do like this in your view script:
if ($this->identity() == null) {
// User is not logged in; show login link here
}
else {
// User is logged in; show profile link here or do nothing
}

Resources