Redirect automatically in a view - grails

I'm using Grails 2.3.3. Is there a better way to redirect to another controller/action from a view automatically if specific conditions exist otherwise continue to display the view - rather than doing this in the action itself?
What I am trying to do is prior to a view being displayed I want to check that I am logged in and if not to redirect automatically to the login page without any user intervention.
If I can do it within the view it's easy to add this login check code into the _header.gsp to effect all the pages. This would be much quicker than having to code up each action in each for each view of interest.

Yes, you can do with the help of Grails custom taglib by spitting a javascript code which will redirect page to different URL if you are not logged in. But this will reduce the user experience for those who will be using your product since you are first rendering to this page and then using Javascript, you are redirecting them back to login screen (if not logged in).
I would recommend you another three solutions:
Use the Grails's filters to protect your actions for authenticated users,
You can use custom Java annotations to protect action automatically by writing some bit of code,
To skip all the above two solutions, you can make use of a widely used Grails plugin for authentication named spring security core plugin, which provides the best & easy authentication mechanism and uses the core Spring Java library behind the scene which is in turn a huge and awesome thing to integrate.

as easy as to define a simple JS-based redirect in your GSP, or even better in shared template:
<sec:ifNotLoggedIn>
<g:javascript>
document.observe( 'dom:loaded', function(){
document.location = '${createLink( controller:'login', action:'doLogin' )}';
} );
</g:javascript>
</sec:ifNotLoggedIn>

Related

Claims-Based Authorization with Angular.JS and WIF

We have an application built with ASP.NET MVC 5.
For that application, we've built several URL-related HTML helpers that act like this:
Imagine there is an anchor that leads to certain URL, i.e. /Customer/Edit/5. We have a helper that will in the background ask ClaimsAuthorizationManager (which is part of Windows Identity Foundation API) whether the current user can perform action Edit on resource Customer. If yes, HTML markup for anchor tag will be rendered. Otherwise, nothing will be rendered.
With these helpers, we've been able to have dynamic website based on background policies that define URL's user can access based on specific claims.
Now we need to push the same logic to AngularJS based SPA.
So again, goal is to skip rendering of URL-related HTML if user is not allowed to access that particular URL.
I've not been able to find any good resources on how to perform this kind of authorization with AngularJS.
Is there a proper way to do this or should I go with some custom logic?
Are there any good references that I can read on?
Angular works great in RESTful applications. In your case, you could set up your app to fetch your claims as JSON and set your angular template to render accordingly.
But you can also use MVC's helper methods on partial views and use those partials as templates for your angular application. So when your angular app fetches the html template at foo/bar/baz (via route or ng-include or directive template or whatever), your html template will come back with the MVC partial view instead of a static html file. It's a little dirty, but it works in a pinch.

Angular.js and WebAPI CRUD examples

I have a asp.net mvc4 web application which for example allows me to manage members and member resources to the site.
On the member's home page there are several different sections of details about their profile. I want to use angular.js and webapi(entityframework) to allow them to edit their address details in place and save them without a page postback. I imagine the best place to start is to have a partialview which displays these address details as part of the main page view.
Are there any examples of such a setup?
You can definitely do this. First, for switching the details based on which section the user selects you have two options:
1) Create a module and setup routes. The routes will allow you to have a base HTML page with an area where you can switch partial HTML 'views' in and out based on the URL that you are clicking on in the application. The AngularJS site has a tutorial where they do something similar. Pay notice to the ng-view explanation.
2) You can create custom directives and fetch an external HTML partial page. In the directive you 'compile' the HTML partial which allows you to use any directives that are on that page (ng-click, ng-class, etc) and then render it where the div is declared in the original page. This is a bit more advanced, so look at the ng-view example first.
For sending the data back to the mvc application, all you need to do in angular is declare a resource with the url back to the mvc app where you post the data and then send it some data. Something like this:
$resource('api/updateUserData',
{userName: userNameVar, userEmail: userEmailVar},
function(data){
//callback code where you do something with the returned data if any
}
);
There is a nice github project called angular-app that has a basic CRUD setup, shows you how to layout the angular app itself, how to use tests, how best to structure the angular files, etc. This may also be a bit more than you need for this small project, but it can at least give you some ideas on how to move forward if your app grows.

Advice on a web application architecture using Web Forms or MVC

I would like some opinions on the following approach to architecting a web application.
A user will navigate to a login page. After logging in, the user will be sent to what I will call a primary page. The idea is to have the primary page contain some common material at the top of the page along with a menu. Below the menu taking up the majority of the page is an IFrame. Each of the menu items, when selected, would load the appropriate page into the IFrame. Here is the main point. The user can navigate through the application using the various menu selections and carry out whatever those selections allow while the primary page remains loaded during the entire session, that is, until the user logs out or closes the browser. This approach does not follow what appears to be the more common paradigm where the browser completely replaces web pages with other web pages as the user navigates through the site. No page stays loaded during the entire session. Is leaving the primary page loaded during the entire session a good idea?
If not, what are the main concerns? Also, can you site any references to a different approach to accomplish the same application-like behavior?
If okay, is there any advantage to using MCV over Web Forms to obtain this behavior?
majority of the page is an IFrame
Iframes are bad. They always have been bad, they always will be. There a dirty hack.
Don't use iframes.
SPA
If you have a good reason not to use actual pages and redirects you can try one of those single page applications that seem to be popular.
I will however remind you that if you rely javascript you basically can't do SEO.
Progressive enhancement
As an aside read up on Progressive Enhancement. You should be doing that.
Partial views
If you like having a large portion of your website static then you can always load partial views over ajax and render them on the client.
Of course because your doing progressive enhancement your doing full page redirects and loads aswell. The partial view rendering on the client is just bells and whistles.
.NET
As for using C# frameworks I would personally recommend Nancy.
If you want to use ASP (god knows why) I guess you can use ASP.NET MVC, sure it's far from optimum but at least it's not ASP.NET webforms
I don't think it's the absolute evil, but your solution does not actually follow the "normal" behaviour of an HTML site, and browsing may be less intuitive.
Users will have problems for bookmarks or using back button, for example.
You will not be able to adapt the menu accoring to the current displayed content (or will have a hell of synchro problems!), for example showing wich section you are in.
The common solution for web is to use a layout, or two-step view pattern (see http://framework.zend.com/manual/en/zend.layout.introduction.html)
I don't know well webforms, but MVC is known as the standard de facto for most web applications and frameworks. It's nice because of the splitting of the roles and the organization it enforces.

HTML Submit button vs AJAX based Post (ASP.NET MVC)

I'm after some design advice.
I'm working on an application with a fellow developer. I'm from the Webforms world and he's done a lot with jQuery and AJAX stuff. We're collaborating on a new ASP.MVC 1.0 app.
He's done some pretty amazing stuff that I'm just getting my head around, and used some 3rd party tools etc. for datagrids etc.
but...
He rarely uses Submit buttons whereas I use them most of the time. He uses a button but then attaches Javascript to it that calls an MVC action which returns a JSON object. He then parses the object to update the datagrid. I'm not sure how he deals with server-side validation - I think he adds a message property to the JSON object. A sample scenario would be to "Save" a new record that then gets added to the gridview.
The user doesn't see a postback as such, so he uses jQuery to disable the UI whilst the controller action is running.
TBH, it looks pretty cool.
However, the way I'd do it would be to use a Submit button to postback, let the ModelBinder populate a typed model class, parse that in my controller Action method, update the model (and apply any validation against the model), update it with the new record, then send it back to be rendered by the View. Unlike him, I don't return a JSON object, I let the View (and datagrid) bind to the new model data.
Both solutions "work" but we're obviously taking the application down different paths so one of us has to re-work our code... and we don't mind whose has to be done.
What I'd prefer though is that we adopt the "industry-standard" way of doing this. I'm unsure as to whether my WebForms background is influencing the fact that his way just "doesn't feel right", in that a "submit" is meant to submit data to the server.
Any advice at all please - many thanks.
The thing you need to take into consideration is how the application will work if javascript is not available. You should strive to ensure that the basic functionality works without it. This is called progressive enhancement or unobtrusive javascript and is considered a best practice.
http://en.wikipedia.org/wiki/Progressive_enhancement
The way you should do it is to use a form with a real submit button and then hijack that form to use ajax if the User Agent supports it. This is usually pretty trivial to do using the jquery forms plugin. In your action method, you can check to see if the incoming request is an ajax request by checking the Request.IsAjaxRequest property. This is set by MVC automatically on requests that have the X-Requested-With header set to XMLHttpRequest. Then you would return a full view or just some json based on that.
Here's a short screencast demonstrating this: http://www.youtube.com/watch?v=YQsFR1rkgMU&feature=player_embedded
Both solutions are viable, though using submit buttons will make your application more accessible (i.e. JavaScript will not be required in order to use it).
You could also do the both - start with a page that has all the necessary logic using postbacks, and "upgrade" it with nice AJAX-y requests and animations. This way, users with JavaScript will get the eye candy, and the page will gracefully degrade when when a user without JavaScript visits the page, falling back to the postback mechanism.

Custom Authentication asp.net MVC

At what point should I be checking for my cookie in my mvc app? Basically what I wish to do for each request is check to see if there is a cookie and if so show their name on the screen somewhere if not and the page requires the user to be logged in redirect them to a login page.
I DON'T want to use FormsAuthentication as I wish to create and use my own IPrinciple object I 'm just not sure whether I should be setting these in a base controller class or creating my own Authorize attribute and doing the checks in there.
My initial thoughts are that I should be doing this in the base controller class as this is similar to the base page in webforms where I override oninit.
Do not attempt to do authentication in a base controller class. In a situation where an action result is cached, your action will not run at all, and no controller will ever be instantiated. Therefore, authentication done inside the controller is broken by design.
The correct way to customize authentication, for many reasons, is to create a custom authentication provider. I've explained the reasons why and given links to simple examples of how to do this in the post linked above.
In short, using this method:
Has the right level of modularity
Works with caching
Works with regular ASP.NET, as well as with MVC

Resources