Redirect to the same page but with a message in it - html

I am making a login page in JSP. I have an index.jsp page where exist the form and some javascript scriplets. Connectivity to oracle database and checking for username and password in database is done in check1.jsp file
My issue is after entering username and password, when I press login button, I have linked the form to check1.jsp, if username and password matches and exist, it redirects to welcome.jsp , but if username doesnot exist or password is not matched I have to get back to index.jsp showing a small message below box that username doesn't exist OR Password is not matched, currently I am just redirecting to index.jsp.
How should I show that appropriate small message below login box on that same index.jsp page??

You can use session object here:
In check1.jsp :
if (loginSuccess) {
//redirect to welcome.jsp
}
else {
session.setAttribute("error", "Username or Password is incorrect");
//redirect to index.jsp
}
In index.jsp:
String msg = session.getAttribute("error");
if (msg != null) {
%><p style="color:red"><%= msg %></p><%
}
Also there is other more simpler ways exists with EL and JSTL, but its just for an starting tip.

You should not redirect to index.jsp, but forward to index.jsp in this case. Store the message in some request attribute, forward to the index.jsp, and display the message if it's present in the request attribute.
You should use an MVC framework, in order to always make your URLs point to actions (controllers) implemented in Java, make these actions call the business ogic (here, log the user in) and have those actions forward or redirect to the appropriate view (index.jsp or welcome.jsp).

Related

Entering wrong username and password still django authenticate it as correct

I am trying to create a login page in Django when the login details are filled in correctly it redirect to a certain page the problem I am facing is that when I enter wrong username or password Django authenticate them as correct and redirect it to another page my login code is as follows
def loginpage(request):
if request.method=='POST':
use=request.POST.get('username')
pas=request.POST.get('password')
user=authenticate(request,username=use,password=pas)
if user is not NONE:
login(request,user)
return redirect('data')
else:
messages.info(request,'Username or Password is incorrect')
return render(request,'login.html')
Even after entering the username that doesn't even exist in the database Django authenticate as right and doesn't show the error that I am expecting
You have uppercase NONE instead of None. You must have accidentally imported NONE from pickle or some other library, and that's why it's validating instead of raising an error. Check your imports at the top of the file and change to if user is not None.

Html - single page - staying logged in

I have an Html page with a load of javascript that changes between views.
Some views require the person to be logged in, and consequently prompt for it.
How can I note the person has successfully logged in, using the javascript, that will not be a security issue, but will mean the person does not have to repeatedly log in for each view. I do not want to keep on going back to the server each time.
Edit:::
To explain more. Here are the problems I see.
Lets say I have the following in my javascript:
var isLoggedIn = true;
var userEmail = "myemail#mysite.com";
Anyone can hack my code to change these values and then get another person's info. That is not good. So instead of isLoggedIn do I need something like a hashed password stored in the javascript:
var userHashedPassword = "shfasjfhajshfalshfla";
But every where I read, they say you should not keep any password stuff in memory for any length of time.
So what variables do I keep and where? The user will be constantly flicking between non-user specific divs and user-based divs, and I do not want them to have to constantly log in each time.
****Edit 2:*****
This is what I am presently doing, but am not happy with.
There is a page/div with 3 radio buttons. Vacant games (does not require user information), My Game (requires knowledge of user and must be signed in), My Old Games (also requires logged in status).
When first going on the page it defaults on vacant games, and gets the info from the server, which does not require login.
In two variables in the javascript I have
var g_Email = "";
var g_PasswordEncrypted = "";
Note these are both 0 length strings.
If the user wants to view their games, they click the My Games radio button. The code checks to see if the g_Email and PasswordEncrypted are 0 length strings, if they are it goes to a div where they need to login.
When the user submits their loging info, it goes to the server, checks their details, and sends back an ok message, and all the info (My Games) that the user was requesting.
So if the login was a success, then
g_Email = "myemail#mysite.com";
g_PasswordEncrypted = "this is and encrypted version of the password";
If there is any failure in login, these two are instead set to "".
Then when the user navigates to any page that requires login, it checks to see if these two strings are filled. If they are, it will not go to a login page when you request information like My Games.
Instead it just sends the info in these strings to the server, along with the My Games request. The server still checks these Email and encrypted password are valid before sending back the info, but at the client side, the user has not had to repeatedly input this info each time.
If there is any failure in the server request, it just sends back an error message (I am using ajax) in the callback function, which knows to set the g_Email and g_PasswordEncrypted to "" if there is anything wrong. (In the latter case, the client side knows it has to re-request the login details because these two strings are "").
The thing I do not like is I am keeping the Encryted password on the person's client machine. If they walk away from their machine, someone can open up the debugger in something like chrome and extract these details, and then hack it into their machine some time later.
If javascript loads content for each view from the server then it is for server to know if a current session belongs to logged user or not. In case the user is not logged, the server responses with prompt to login, otherwise it sends content of the view.
If javascript bulds content for the views deriving it from the data that was already received from the server then it should use some variable keeping state of the user (logged/not_logged). And depending on that value javascript will either show a prompt to login or display required content of the view.

Auth and fatfree framework

I have been playing with Auth of fatfree using two routes login and logout. The first time I used login in a url the dialogue box came up asking for username and password. After typing in a username which exists in the table field 'user_name' and password in field 'user-pass' I got true for $result so web page displayed it works. Interestingly I have not got code new Session(); anywhere yet when i then went to url /logout echo $f3->get('SESSION.pass'); was correctly displayed suggesting Auth starts a session.
In my /logout route after echo $f3->get('SESSION.pass');
I have $f3->clear('SESSION');.
Yet if I then flip back between /login url and logout url, the dialogue box no longer shows and logout still displays '1234' which is SESSION.pass. I would have thought that after going to /logout url the session would clear, so after going back to /login url i though it would bring up the login dialogue box to login.
In a nutshell my question is "how do you logout of Auth"? The documentation doesn't seem to mention it.
$f3->route('GET /login',
function($f3)
{
$db = new \DB\SQL('mysql:host=localhost;port=3306; dbname=accra_names2','root','victoria');
$user = new DB\SQL\Mapper($db, 'users');
$auth = new \Auth($user, array('id'=>'user_name', 'pw'=>'user_pass'));
$result = $auth->basic(); // a network login prompt will display to authenticate the user
$f3->set('SESSION.pass','1234');
if($result)
//result true
{
echo "it works";
}
}
);
$f3->route('GET /logout',
function($f3)
{
echo "you want to log out ";
echo $f3->get('SESSION.pass');
$f3->clear('SESSION');
}
);
Actually your question is "how to logout from HTTP basic auth".
There are several topics and answers about it here on SO, like this one How to log out user from web site using BASIC authentication?
So if you want full control about the login/logoff mechanisms you go probably better with own html forms instead of the browsers basic login box.

Users keep getting disconnected

So i get users getting disconnected with no reason (or better i don't know the reason).
On the login page i make a session:
Session.Add("UserProfile", username);
On the landing page
string userNames = Session["UserProfile"] as string;
if(userNames == null){
Response.Redirect("~/default.cshtml");
}
On the Webconfig i've tried this
<sessionState cookieless="UseCookies" timeout="240"> </sessionState>
<httpRuntime maxRequestLength="252400" executionTimeout="1200" />
<authentication mode="Forms"> <forms timeout="525600" slidingExpiration="true" /></authentication>
And the thing is... On the landing page i got a list where users can choose an id, enter on it and each have id have a form that the user can edit.
But very often when the user submit the form, he's redirected to the login page.
Any thoughts ?
You have specified a forms authentication timeout value but you aren't actually using Forms Authentication so that won't have any effect. Sessions can be ended by App Pool recycling on the web server so it is perfectly possible for users to lose their session and therefore fail your landing page test. That will result in them being redirected to the home page.

Retaining HTTP POST data when a request is interrupted by a login page

Say a user is browsing a website, and then performs some action which changes the database (let's say they add a comment). When the request to actually add the comment comes in, however, we find we need to force them to login before they can continue.
Assume the login page asks for a username and password, and redirects the user back to the URL they were going to when the login was required. That redirect works find for a URL with only GET parameters, but if the request originally contained some HTTP POST data, that is now lost.
Can anyone recommend a way to handle this scenario when HTTP POST data is involved?
Obviously, if necessary, the login page could dynamically generate a form with all the POST parameters to pass them along (though that seems messy), but even then, I don't know of any way for the login page to redirect the user on to their intended page while keeping the POST data in the request.
Edit : One extra constraint I should have made clear - Imagine we don't know if a login will be required until the user submits their comment. For example, their cookie might have expired between when they loaded the form and actually submitted the comment.
This is one good place where Ajax techniques might be helpful. When the user clicks the submit button, show the login dialog on client side and validate with the server before you actually submit the page.
Another way I can think of is showing or hiding the login controls in a DIV tag dynamically in the main page itself.
You might want to investigate why Django removed this feature before implementing it yourself. It doesn't seem like a Django specific problem, but rather yet another cross site forgery attack.
2 choices:
Write out the messy form from the login page, and JavaScript form.submit() it to the page.
Have the login page itself POST to the requesting page (with the previous values), and have that page's controller perform the login verification. Roll this into whatever logic you already have for detecting the not logged in user (frameworks vary on how they do this). In pseudo-MVC:
CommentController {
void AddComment() {
if (!Request.User.IsAuthenticated && !AuthenticateUser()) {
return;
}
// add comment to database
}
bool AuthenticateUser() {
if (Request.Form["username"] == "") {
// show login page
foreach (Key key in Request.Form) {
// copy form values
ViewData.Form.Add("hidden", key, Request.Form[key]);
}
ViewData.Form.Action = Request.Url;
ShowLoginView();
return false;
} else {
// validate login
return TryLogin(Request.Form["username"], Request.Form["password"]);
}
}
}
Just store all the necessary data from the POST in the session until after the login process is completed. Or have some sort of temp table in the db to store in and then retrieve it. Obviously this is pseudo-code but:
if ( !loggedIn ) {
StorePostInSession();
ShowLoginForm();
}
if ( postIsStored ) {
RetrievePostFromSession();
}
Or something along those lines.
Collect the data on the page they submitted it, and store it in your backend (database?) while they go off through the login sequence, hide a transaction id or similar on the page with the login form. When they're done, return them to the page they asked for by looking it up using the transaction id on the backend, and dump all the data they posted into the form for previewing again, or just run whatever code that page would run.
Note that many systems, eg blogs, get around this by having login fields in the same form as the one for posting comments, if the user needs to be logged in to comment and isn't yet.
I know it says language-agnostic, but why not take advantage of the conventions provided by the server-side language you are using? If it were Java, the data could persist by setting a Request attribute. You would use a controller to process the form, detect the login, and then forward through. If the attributes are set, then just prepopulate the form with that data?
Edit: You could also use a Session as pointed out, but I'm pretty sure if you use a forward in Java back to the login page, that the Request attribute will persist.