spring security User details - jsf-2

My application has been developed using jsf2 , primefaces and spring
I want to add user details bar on the above of page
This bar will contain String hello User,
This bar appears only when user logged in
My problem is when access the application again , I see the bar while Logging process isn't performed
Any suggestions ?
The code of set bar visible is :
public String login() {
boolean success = authenticationService.login(mail, password);
if (success) {
signedIn = true;
User user = (User) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
String name = user.getUsername(); // get logged in username
System.out.println(">>>>>>>>> login "+name);
setName(name);
return "facultyRating"; // return to
// application
// but being
// logged now
} else {
signedIn = false;
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Login or password incorrect."));
return "/pages/securityLogin.xhtml/loginPage.xhtml";
}
this method exists in bean where Jsf2 page "that Contains user info bar" read from it
Thanks

Assuming that the login method is part of a session scoped managed bean, you could use the signedIn property to determine whether or not to show the menu bar using the rendered attribute of the component.
Something like the following:
<h:form id="menuForm">
<p:menubar rendered="#{authMBean.signedIn}">...</p:menubar>
</h:form>
The login method should also update the form where the user bar is placed in order to show it on login success.
org.primefaces.context.RequestContext.getCurrentInstance().update(":menuForm");

It has been solved by making the info bar in separate secured page "Will appear only after Logging in "

Related

Browser back button is showing previous page after logout in Grails

I am using grails-2.4.5 version and spring-security-core-2.0-RC5. I have set a default target URI in config.groovy page. When user login then they can access to that page, when logout no access, should display only login page.
My problem is, when user logout login page is displayed, but if browser back button is hit then the default target page is displayed although he can't access any action. But it odd. My config is given below:
in config.groovy >>
grails.plugin.springsecurity.successHandler.defaultTargetUrl = '/dashboard/index'
grails.plugin.springsecurity.logout.postOnly = false
my url mapping class >>
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?(.$format)?"{
constraints {
// apply constraints here
}
}
"/"(controller:"login", action: "auth")
"500"(view:'/error')
}
}
my default target uri method >>
class DashboardController {
def index() {
}
}
There are many possible ways to stop,
Browser back button is showing previous page after logout
With JavaScript, you can clear location history or disable back button.
<script>
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
};
</script>
Demo
Here you will get many possible options
Hope this will helps you.

Prevent loading page

I have a controller create and return content where it triggers an alert.
The problem it load an empty page. How can I prevent it to load an empty page and stays in the current view and do nothing just pop the alert.
What I really wanted here is before the user can create new data, it will validate first if the diseaseID is already existing for specific assessmentID, and when the result is null, it will just pop an alert and do nothing. But here I'm just trying make alert() work properly.
Controller:
public ActionResult CreateDisease(int? diseaseID,int? assessmentID, DiseaseList diseaselist)
{
diseaselist.DiseaseID = diseaseID;
diseaselist.AssessmentID = assessmentID;
db.DiseaseLists.Add(diseaselist);
db.SaveChanges();
return Content("<script language='javascript' type='text/javascript'>alert('Item already exist');</script>");
}
You dont need to return the script as content from the controller, just return the values as json that will tell you that the item already exist and based on that true or false value show an alert from the client side js.
your controller code will look something like this
diseaseModel.DiseaseID = diseaseID;
diseaseModel.AssessmentID = assessmentID;
diseaseModel.AlreadyExist = true;
return Json(diseaseModel);

MVC 5 Session not presisted when going to another View

Session variable lost after a controller calls another View to render.
public ActionResult Index(Customer model, string cancel, string effective)
{
if(!string.IsNullOrEmpty(cancel))
{
//update database
Session["variable2"] = new Info(){ Text = "Do not processed"};
return View("Cancelation"); //error stated occurs when calling another view
}
if(!string.IsNullOrEmpty(effective)
{
//do data base update
Session["variable1"] = new Info(){ Text = "Processed"};
return View(model); //All good here
}
{
I have a MVC controller that when post back to it I set a Session variable "variable1", then I do return View(model). In this case all is good I can access the new Session variable1 everywhere.
But when I post back to the same controller again, I check the button clicked and then I set another Session variable, "variable2" this time I do return View("Cancelation").
This last variable2 is lost and does not show on HttpContext.Current.Session["variable2"] anywhere in the application.
Can someone help to understand why?
What I found was that because I was using SQL Server as Session store, I had to use Serialize() attribute on the object, then it worked.

Dynamically load layout based on condition in MVC4

I have a _Layout.cshtml page which will render every time when a view is loaded. I have a session variable which stores the current user. While loading a view I need to check whether that session is out. If session out I need to render another view to prompt the user to login again.
I have written this code in the _Layout.cshtml
#if( #Session["UserId"]!=null)
{/* Header,RenderBoady(),footer etc of layout goes here */}
else
{/*call another view here*/}
I dont know what have to write on else part.
Most likely, you need redirect user rather than vary layout. I suggest to use filters for this task and may think of 2 solutions.
First, utilize built-in [Authorize] attribute to reduce amount of custom logic.
Second, use custom AuthorizeFilter, which may looks like one below:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
Controller controller = filterContext.Controller as Controller;
if (IsSessionExpired(filterContext))
{
filterContext.Result = new RedirectResult(<where to redirect>);
}
}
private bool IsSessionExpired(AuthorizationContext filterContext)
{
<logic>
}
}
Pick any you like and register as global filter or mark specific contollers/actions.
Use asp.net mvc authorze filter attribute for user authentication,
Enable forms authentication in web.config
Use _ViewStart.cshtml and perform this check in that file. Based on status set the layout page for logged in user and logged out users
#{
if( #Session["UserId"]!=null)
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
else
{
Layout = "~/Views/Shared/_LayoutPartial.cshtml";
}
}

How do I disallow a viewcontroller from progressing to the next view in my app?

I have a multi-view application and in my storyboard I have graphically defined a view (view1: log in username/password view for instance) that will segue to another view (view2: welcome view for instance) with a button click. In view1, when the user enters the user name and password information and clicks on the "Log in" button, it will go through some logics to check the validity of the username and password, and will proceed to the welcome view if successful. However, how do I refrain the view switching if the username or password is invalid and I want the user to stay in the current view1 that will now have a popup notifying the invalid username or password?
Thanks.
Kenny
If for example the segue was called login then something like the following will accomplish it (iOS 6 + only).
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
if([[segue identifier] isEqualToString:#"login"]){
//my logic code here populating logged_in with a boolean value showing if logged in or not
if(logged_in) {
return YES;
} else {
return NO;
}
}
// Make sure all other segue's can still work.
return YES;
}
You should test if the user name is valid or not, and go from there.
if(usernameIsValid == TRUE){//Here you want to do your "logics to check the validity"
//Switch Views
}
else{
//Show A UIAlertview letting user know credentials are invalid.
}

Resources