I am developing a laravel web application of business directory.
here is my scenario.
http://localhost/genie-works/devojp/customer // user searching with keyword of business and
Showing results in http://localhost/genie-works/devojp/customer/search-result?keyword=apple&searchcity=1 this page.
here listing too many business data with post an enquiry feature.
when clicking on the post an enquiry button page goes to http://localhost/genie-works/devojp/customer/post-enquiry/{bisinjessid}/
the post enquiry page checking a middle-ware as authentication.
when user not logged in the middleware redirect to login page http://localhost/genie-works/devojp/customer and showing the login form
after entering login details its needs to redirect to http://localhost/genie-works/devojp/customer/post-enquiry/{bisinjessid}/ this page.
but i tried the function Redirect::back its redirecting to customers page (http://localhost/genie-works/devojp/customer)
How can i solve this issue by redirecting to my last page....
Thanks
Middleware..
public function handle($request, Closure $next)
{
if (!Auth::check()) {
return redirect()->intended(route('cust_index'))->with('activelogin','Succesfully LoggedOut !!!');
}
return $next($request);
}
Controller..
public function custdologin(){
$userdata=array(
'username'=>Input::get('email'), // getting data from form
'password'=>Input::get('password') // getting data from form
);
if(Auth::attempt($userdata)){
switch (Auth::user()->user_type) {
case '2':
return Redirect::to(route('myaccount'));
break;
case '3':
return back();
break;
default:
Auth::logout();
return Redirect::to(route('business_login'))->with('message','Check Your Entries!!');
break;
}
}
else
return Redirect::to(route('business_login'))->with('message','Check Your Entries!!');
}
In your middleware where you are using redirect, use the following:
return redirect()->intended('put a default url'); // i.e: '/dashboard'
This will redirect the user to the intended url (s)he wanted to go without being logged in. Check more here (in Manual Authentication code snippet)
Related
I have an application that has two authentications i.e user and admin.
I want to redirect the user to a specific page if they are already login. Like if the user is already logged in then the URL http://example.com/log should take the user to URL http://example.com/dashboard.
Similarly, if an admin is already logged in then, URL http://example.com/admin/login
should redirect them to URL http://example.com/admin/dashboard.
The problem is I can change the handle method to redirect to only one page in RedirectIfAuthenticated page. Any idea on how to check if request is from admin or user in that page.
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
return $next($request);
}
if you create 2 guards for authentication like user and admin then simply check by below
if (!Auth::guard('user')->user()) {
return redirect('/dashboard');
}
if (!Auth::guard('admin')->user()) {
return redirect('/admin/dashboard');
}
My aurelia application has two roots, an app-login and the app root. When users try to access the application and are not logged in, they are sent to the app-login route, which only has 1 route configured, login.
If an unauthenticated user tries to access the app as though they were logged in, (e.g. localhost:3000/#/needsAuthenticationRoute), I want the user to be taken to the login page, however, upon successfully logging in, have them be redirect to the page they were initially trying to access.
I try to handle the issue as follows:
config.mapUnknownRoutes((instruction) => {
let redirectUrl = 'login';
console.log(instruction);
if(instruction.fragment !== '/') {
let redirect = instruction.fragment;
if(instruction.queryString) {
redirect = redirect + '?' + instruction.queryString;
}
redirectUrl = router.generate('login', {redirect});
}
return {redirect: redirectUrl };
});
So from the app-login route, if they try to access needsAuthenticationRoute, they would be redirected back to the login page with a redirect parameter (the user would be sent to localhost:3000/#/login?redirect=%2FneedsAuthenticationRoute in this case).
However, when the user tries to access a route with a query string (e.g. needsAuthenticationRoute?param=value), I would want the user to be redirected to localhost:3000/#/login?redirect=%2FneedsAuthenticationRoute%3Fparam%3Dvalue. However, the redirect keeps around the query parameter and I am left with a route that looks like
localhost:3000/#/login?redirect=%2FneedsAuthenticationRoute%3Fparam%3Dvalue?param=value.
Does anybody know how to clear query the query params when specifying a redirect instruction? Or have an alternative solution to what I am proposing?
I have recently just implemented the exact functionality you describe (I also have a blog post in draft about this topic too - when I get round to publishing it...)
I have a bunch of routes, some that have query strings, some which don't. If the user isn't logged in i want to redirect them to the login page, then after successful login I want to redirect them to where they were going before.
Also, I wanted to keep the "?returnUrl=" query string out of the url, it works, but just felt a bit messy to me - considering that this is all client side routing, i knew i could store it somewhere and "hide" it/
So firstly, we need to stash the route they were going to before login, this is done in a defined AuthorizeStep Aurelia AuthorizeStep
#inject(MyApi)
class AuthorizeStep implements PipelineStep {
constructor(private api: MyApi) { }
public run(navigationInstruction: NavigationInstruction, next: Next): Promise<any> {
if (navigationInstruction.getAllInstructions().some(i => i.config.settings.roles.indexOf("Client") !== -1)) {
if (!this.api.LoggedIn && navigationInstruction.config.name !== "login") {
this.api.RouteFragment = navigationInstruction.fragment;
return next.cancel(new Redirect("login"));
}
}
return next();
}
}
Finally, the login page needs to be made aware that after logging in, the user might be going somewhere. So after a successful login we check to see if anything has been stashed in the RouteFragment
if (loginResult.Success) {
if (this.api.RouteFragment && this.api.RouteFragment.length > 0) {
// Navigate to where the user was trying to go before Logging In
this.router.navigate(this.api.RouteFragment);
} else {
this.router.navigate("/dashboard");
}
}
I am experimenting with Grails 3 Interceptors. Given the following interceptor:
class AuthInterceptor {
AuthInterceptor() {
matchAll().includes(controller:"account")
}
// Intercept anything under /account.
boolean before() {
User user = SimpleSecurityUtils.getCurrentUser()
if(user != SimpleSecurityUtils.anonymous) {
// Only get here if the user is currently authenticated. Redirect them to where they want to go.
true
} else {
redirect(controller: auth, action: signin)
true ??
}
}
boolean after() { true }
void afterView() {
// no-op
}
}
matchAll().includes(...) doesn't actually exist on the Matcher object. So how do I actually say "only intercept requests to the AccountController"?
If you follow the auth logic, if the user is currently anonymous (not logged in), I want to redirect them to the AuthController#signin action, which will present them with a login screen. It doesn't appear that the redirect(...) closure is available to interceptors...so how do I perform this redirect safely? Furthermore, how do I "save off" the URL we are currently intercepting so that, after successful login, the user can yet again be redirected to the originally-requested URL?
I say safely above because I've had issues with Grails CannotRedirectExceptions being thrown if too many redirects keep getting tossed around, and those errors are usually assuaged by returning after performing a redirect per this previous answer.
For #1, match( controller: "account" ) should do the trick. Don't know the answer to #2.
I have a asp.net mvc web api app with ember and simplemembershipprovider. I am using the ember template and with it, ember app is created upon user successfully logged in in the home controller.
public ActionResult Index(string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return View("App");
}
ViewBag.ReturnUrl = returnUrl;
return View();
}
Sometimes user would click a link in an email with an id when visiting the site, if the url includes an id, upon successful login, I want to redirect user to a detail page base on the provided id in the url. An example would be http://siteURL.com/#/product/1412 . I am having a hard time figuring out how to do this. Since this is a client side ember route, MVC does not differentiate between this route and http://siteURL.com so it just ignores the redirect request. Here is what I have tried.
assign the url in the login controller - nothing happens after json data is returned, stays in the login page and never hit the HomeController even though user is not authenticated.
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
returnUrl = "http://siteURL.com/#/product/1412";
return Json(new { success = true, redirect = returnUrl });
use response redirect. Same as #1
Response.Redirect(returnUrl);
Assigned url in home controller, same as above.
if (User.Identity.IsAuthenticated)
{
returnUrl = "http://siteURL.com/#/product/1412";
return View("App");
}
ViewBag.ReturnUrl = returnUrl;
return View();
Most browsers don't even send the # up to the server, so you won't have it to redirect. Here's a few options
Don't use the hash, not every browser supports it, http://emberjs.com/guides/routing/specifying-the-location-api/
Give them a fake address that redirects, http://siteURL.com/Redirect/product/1412
inject that url into some js on the page that redirects on load
I have a problem creating authentication part for my application.
Below is the simplified version of my controllers.
The idea is that the MY_controller checks if session with user data exists.
If it doesn’t, then redirects to the index page where you have to log in.
MY_controller.php
class MY_Controller extends Controller {
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->library('session');
if($this->session->userdata('user') == FALSE) {
redirect('index');
} else {
redirect('search');
}
}
}
order.php - main controller
class Orders extends MY_Controller {
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->library('session');
}
function index()
{
// Here would be the code that validates information input by user.
// If validation is successful, it creates user session.
$this->load->view('header.html', $data); // load header
$this->load->view('index_view', $data); // load body
$this->load->view('footer.html', $data); // load footer
}
function search()
{
//different page
}
what is happening is that the browser is telling me that “The page isn’t redirecting properly. Firefox has detected that the server is redirecting the request for this address in a way that will never complete.”
It seems like the redirect() is being looped. I looked at a few other examples of user auth and they were build using similar technique.
When a user is already logged in, it appears you want to redirect them to /search/. The redirect occurs, and the constructor is called again, which recognizes that the user is already logged in, so it redirects them to /search/... you get the idea.
I would start by separating your login logic into it's own controller that doesn't extend from MY_Controller.
Also, note that when not logged in your controller redirects to 'index'. If the Index controller is also based on My_Controller, then it will redirect back to itself (until the user logs in and then Dolph Mathews' answer comes true).
You need to provide a 'safe zone' with no checking/redirecting that provides users with a login form (and note that your login controller/method has to have open access too!)
I tend to pop a gateway method into My_Controller, which is called only by private controllers/methods as required (in the constructor of completely private controllers). I'm sure there must be a better way though, perhaps like a gateway function in your My_Controller (as yours is done) but that filters for the URI path (e.g. allows index; index/login; index/logout etc)