The client will log in by sending a POST request to my server. My server will check this. If it works, I want to send the welcome page to the client but insert some data into it via a templating engine. I have everything but the redirect part figured out. This is what I have (I am using handlebars as a templating engine):
app.post("/loginAttempt",function(req, res)
{
var username = req.body.username;
var password = req.body.password;
//if credentials are incorrect, data is false
//otherwise, data is a html file as a string
var data = await checkCredentials(username,password);
if(data === false)
{
res.send("fail");
}
else
{
//not a real function, just using this to simplify code for this post
var temp = compileWithHandlebars("./front-end/welcome.html",{myData: data});
res.send(temp);
}
});
The problem with this is it sends a html file as a string instead of redirecting. This means the user sees no change in url, so they cannot hit the back button to go back to the login page.
I am guessing the temp is a string!
app.post("/loginAttempt",function(req, res)
{
var username = req.body.username;
var password = req.body.password;
//if credentials are incorrect, data is false
//otherwise, data is a html file as a string
var data = await checkCredentials(username,password);
if(data === false)
{
res.status(404).send("fail"); //<==
}
else
{
//not a real function, just using this to simplify code for this post
//var temp = compileWithHandlebars("./front-end/welcome.html",{myData: data});
res.redirect("./front-end/welcome.html",{data:myData});
}
});
Related
I made an ajax request to the server for checking whether a particular username exists in the database. Here is the code for that..
$("input[placeholder='Username']").focusout(function() {
var username = $("input[placeholder='Username']").val();
if(username.length <3 || username.length>20) {
$("#username_taken").html("Username must be between 3-20 characters!");
usernameFlag = true;
}
else if(username != null) {
$.ajax({
type: "POST",
url: "/data/validate_username",
data: username,
success: function(isValid) {
if(!isValid) {
$("#username_taken").html("The username has already been taken!");
usernameFlag = true;
}
},
error: function() {
$("#username_taken").html("Could not verify username from server!");
}
});
}
});
In the server side I have written a RestController to handle this request and provide the data on whether the user exists or not.
// necessary imports done...
#RequestMapping("/data")
#RestController
public class UserAccountRest {
#Autowired
private UserAccountService userAccountService;
#PostMapping("/validate_username")
public boolean validateUsername(String username) {
return !userAccountService.accountExists(new UserAccount(username));
}
}
Normally spring auto populates the parameters like username, if it was a form submit. But here status 500 Internal Server Error occurs, and in the console it says that the id must not be null. This means that the username is not populated.
I could probably use HttpRequest object in the parameter and get the username from it. But is there any way to configure so that the username is directly populated?
The data sent needs to have key/value pairs.
When you get the value of an <input> you only have 1/2 of the pair. Your variable username only contains the value part
Change
data: username,
To
data: {username : username}
Have you tried doing
public boolean validateUsername(#RequestBody String username) {
return !userAccountService.accountExists(new UserAccount(username));
}
You are probably posting a JSON value which should be a key value pair.
I am using an ajax function to verify user login and i am returning json on errors . i wanted to redirect to a particular url on successive login, but the i can only send json data from my function (eliminating the possibility of using url_for or redirect ) . so How do i dynamically get the root url so i can send it via json and then redirect via javascript.
heres my route`
def logincheck():
uname = request.form['username']
pwd = request.form['password']
if uname and pwd:
this = userlogin.query.filter_by(username = uname).first()
if this:
if this.password == pwd:
session['myid'] = this.uid
return jsonify(success = ?)
else:
return jsonify(p_error = 'Incorrect Password')
else:
return jsonify(u_error = 'Incorrect Username')
Thanks.
To get base url in javascript ,
var base_url = window.location.origin;
output : "http://yoururl.com"
var host = window.location.host;
output : yoururl.com
To redirect url in javascript ,
// redirect to another page
`window.location = "http://www.yoururl.com"`;
// it has similar behavior as an HTTP redirect
window.location.replace("http://yoururl.com");
// it has similar behavior as clicking on a link
window.location.href = "http://yoururl.com";
Hope this will help you.
I'm learning the basics of Node.js + MongoDB and some other related tools, but I'm stuck in a simple login screen I made, the goal is, once the right credentials are given, to redirect to index.html which only has a text "welcome!". I've taken a look at different places (official API, tutorials, this page, etc.) but can't see my error yet.
This is my server:
var http = require('http');
var hostname = 'localhost';
var port = 3000;
var mongojs = require("mongojs");
var express = require("express");
const HOME_URL = "/";
const LOGIN_URL = "/login";
const LOGIN_ACTION_URL = "/doLogin";
const INDEX_URL = "/index";
var app = express();
var db = mongojs("gus:1234#127.0.0.1:27017/awesomeapp");
app.set("views", __dirname + "/public/views");
app.engine('html', require('ejs').renderFile);
app.get(HOME_URL, function(request, response) {
response.redirect(LOGIN_URL);
});
app.get(LOGIN_URL, function(request, response) {
response.render("login.html");
});
app.get(INDEX_URL, function(request, response) {
response.render("index.html");
});
app.get(LOGIN_ACTION_URL, function(request, response) {
db.users.find({
user: request.query.user,
pass: request.query.pass
}, function(err, doc) {
if(err) {
console.log(JSON.stringify(err));
response.end("An error ocurred");
return;
}
if(doc.length == 0) {
console.log("invalid_credentials");
response.end("invalid_credentials");
return;
}
console.log("user found: " + JSON.stringify(doc));
// This is my problem:
response.redirect(INDEX_URL);
});
});
app.listen(port);
and this is done in the login view:
$.ajax({
url: "/doLogin",
type: "GET",
data: {
user: $("#user").val().trim(),
pass: $("#pass").val()
}
}).done(function(data, textStatus, jqXHR) {
if(data == "invalid_credentials") {
$("#alert-wrong-credentials").show(100);
} else if(data == "ok") {
$("#alert-wrong-credentials").hide();
}
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
I can successfully return the error string "invalid_credentials" when trying non-existing credentials, and I can see the user data when I enter the right ones:
user found: [{"_id":"58af514cb63980d2e8a51fed","user":"gus","pass":"123"}]
but I'm unable to redirect to the index.html page.
You should handle redirect on the client side once the login is complete. Redirect would work if you're actually visiting the LOGIN_ACTION_URL.
if(data == "invalid_credentials") {
$("#alert-wrong-credentials").show(100);
} else if(data == "ok") {
// Redirect
window.location.href = "index_url";
}
Also, there is a similar question here Node.js Page Redirect on AJAX login? With a function call after redirect? .
Ajax calls don't affect the current browser page. You send a request to a server. You get a response. If you want the current browser page to change, then you have to write Javascript that looks at the ajax response and then changes the current browser page by setting:
window.location = someURL;
So, doing a res.redirect() in response to an ajax call will just return a 302 status to the ajax call. That's it. If you want the ajax call to use that as an indicator to change the current browser page, then you have to write code to look for the 302 response and grab the right header from the response and then change window.location. There is no automated way to do that from an Ajax call.
When the browser is requesting a web page for a URL and it gets a 302 when loading a web page, then it will follow the redirect at that point. But, not for Ajax calls. An ajax call just gets you the response, whatever it is and it's up to your code that processes the response to actually do something with it.
I am creating a web portal using Angular on the front end and Java Servlets in the back end. The page starts with a login page, It takes the input and sends it to the servlet. The server validates and responds with a JSON object which has the username and his permissions. I set the values to a Service which is injected into the Controller. Then I use $windows.location to change the web page to the home page which is the dashboard. Now I want to use this Service in the controller of the homepage. But I am not able to maintain the $scope due to the page change.
So I thought of redirecting to the home page in the backend using response.redirect() . But I don't know how to get the user details in the homepage after redirection. Like how do I pass the User object to the Home.java servlet
This is my LoginCtrl.js
if (isValid) {
$http({
method : 'POST',
url : 'login',
data : JSON.stringify($scope.user),
headers : {
'Content-Type' : 'application/json'
}
}).success(function(data) {
if (!("failure" == data)) {
console.log(data);
var user = {};
user.name = data.name;
user.permissions = data.permissions;
MyService.setUser(user); // set the values for user
$window.location.href = 'main.jsp';
} else {
$scope.information = "Invalid username/password!"
}
}).error(function(data) {
console.log(data);
});
This is my Login.java servlet
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject obj = (JsonObject) parser.parse(request.getReader());
String username = "";
String password = "";
if (obj.get("name") != null & obj.get("password") != null) {
username = obj.get("name").getAsString();
password = obj.get("password").getAsString();
}
System.out.println("Username :" + username);
System.out.println("Password :" + password);
// Passing username and password to Context and validate.
// If authentication successful, set user object with details and return
// it
// User user = (User) Context.Authorized(username,password)
// for testing
User user = new User();
user.setName(username);
user.setPermission("crwd");
user.setAuthorized(true);
response.setContentType("text/html");
if (user.getAthorized()) {
String responseJSON = gson.toJson(user);
response.getWriter().write(responseJSON);
} else {
response.getWriter().write("failure");
}
}
Please tell me if my requirement can be achieved in Angular or if it can be done using Java, then how ?
If you redirect to another page, there will be completely different Angular application, and you will lose service state.
You can make single page application and use $routeProvider and ng-view for both login page and homepage navbar.
Or your app can consist of different pages, but then in every page you must call server to get user info
Trying to figure out why this code doesn't work. When I console.log the userinfo, it comes back as ["", ""]. So, it's not collecting the username or password.
According to the documentation,
GET /users
returns a list of users.
{"users": ["alex", "bill", "charlie"]}
200 - Successful
GET /users/:name
Display a user.
200 - Successful
404 - User not found
What's going on?
/**
* Click event handler for submit button, return username and password
*/
function getInfo(){
var user = document.getElementById("username").value;
var username = user;
var pass = document.getElementById("password").value;
var password = pass;
return [username, password];
}
document.getElementById("submit").addEventListener("click", getInfo, false);
var userinfo = getInfo();
var username = userinfo[0];
var password = userinfo[1];
console.log(userinfo);
/**
* Get request for user's information, return user data, save as user.
* Check for matching password - if true open userprofile.html
* If false, show notice from index.html, reset user to empty
*/
function showGetResult( username )
{
var result = {};
var scriptUrl = "http://localhost:4567/main.rb";
$.ajax({
url: scriptUrl,
type: 'get/users[username]',
dataType: 'json',
async: false,
success: function(data) {
result.append(data);
}
});
return result;
}
var user = showGetResult(username);
console.log(user);
function passwordCheck(user, password)
{
if (user[2] === password){
window.open = "http://localhost:4567/userprofile/userprofile.html";
}
else {
document.getElementById("notice").style.display = "block";
user = {};
}
}
passwordCheck(user, password);
console.log("still working");
When you’re dealing with the DOM it’s important to execute your code only after the page is fully loaded. If you don’t, there’s a good chance the DOM won’t be created by the time your code executes. That's why you keep getting empty results or sometimes error. To overcome this, you need to ensure your script executes only when the page load is completed.
window.onload = init;
var username = "", password = "";
function init() {
document.getElementById("submit").addEventListener("click", getInfo, false);
}
function getInfo(){
username = document.getElementById("username").value;
password = document.getElementById("password").value;
}
I noticed you invoke the function getInfo() manually in your code. I don't know why you are doing that. By using the above code, your function will be invoked only when the submit button is clicked.