Flask - Redirect via javascript on successful json - javascript

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.

Related

nodejs redirect user with data

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});
}
});

Variables between index.html and app.js

I request a username using a prompt within my index.html. My code looks like this:
<script>
// YOU DO NOT NEED TO EDIT THIS CODE
if (!/(&|\?)username=/.test(window.location.search)) {
var newSearch = window.location.search;
if (newSearch !== '' & newSearch !== '?') {
newSearch += '&';
}
var username = prompt('What is your name?') || 'anonymous';
console.log("From Index.html:" , username);
newSearch += 'username=' + (username);
window.location.search = newSearch;
}
</script>
I need to access this username within my app.js. I am sending a POST request to a server that requires the username as a property. For example:
//POST the message to the server
handleSubmit: function() {
var query = window.location.search;
var username = query.slice(10, query.length);
var room = $('#roomSelect').find(':selected').text();
var msg = {
username: username,
text: $('#message').val(),
roomname: room
};
app.send(msg);
console.log(msg);
app.renderMessage(msg);
}
Essentially, I want to prompt the user for their username in the index.html, but how do I access this variable from the app.js? Do I send it back to that file somehow?
You can try it to store in session variable and then access it from anywhere
Hope this will help you
Thanks!!!

Python Register Account model

I'm sure this has been asked before, however I've been searching for hours and cannot find anything that works so apologies in advance. I'm in the early stages of learning to code with Python on an online course and I'm deviating away from it a little to make it my own.
When a user registers an account, I want to return an error if the username is already taken. Otherwise to create the account and redirect to the login page. However I'm not sure how to do define the if statement to return the correct console response as it only currently returns the user. I want this to return success / error and use ajax to catch this response.
The register model I have so far is:
class RegisterModel:
def __init__(self):
self.client = MongoClient()
self.db = self.client.codewizard
self.Users = self.db.users
def insert_user(self, data):
existing_user = self.Users.find_one({"username": data.username})
if existing_user:
pymsgbox.native.alert('Username already taken!', 'Title')
else:
hashed = bcrypt.hashpw(data.password.encode(), bcrypt.gensalt())
id = self.Users.insert({"username": data.username, "name": data.name, "password": hashed, "email": data.email})
print("uid is", id)
pymsgbox.native.alert('Account created, please login!', 'Title')
And the controller:
class PostRegistration:
def POST(self):
data = web.input()
reg_model = RegisterModel.RegisterModel()
reg_model.insert_user(data)
return data.username
and finally the javascript (not completed with if statement)
$(document).on("submit", "#register-form", function(e){
e.preventDefault();
var form = $('#register-form').serialize();
$.ajax({
url: '/postregistration',
type: 'POST',
data: form,
success: function(response){
console.log(response);
}
});
});
pymsgbox will be replaced by the Javascript when I can get it to work!
Figured it out:
Controller:
class PostRegistration:
def POST(self):
data = web.input()
reg_model = RegisterModel.RegisterModel()
register = reg_model.insert_user(data)
if register:
return register
and then returning "error" in the register model if statement.

Using cookies to check if anonymous user voted

I'm working on a webapp that uses Flask as the backend server. There are posts that I'm storing in an SQLAlchemy database, and I want the users to be able to upvote/downvote them without having to log in. I wrote a JavaScript function for upvoting/downvoting that increments the current vote count and then updates the count in the database using Ajax. I want to make sure that the same user doesn't vote on the same post twice; it doesn't have to be robust. I read that cookies could be used for that purpose, or a combination of cookies and IP. I'm having a hard time understanding how to get started: do I assign a cookie to a user in JS or in Flask? How do I check whether the user already voted? I'd appreaciate if someone could show me a simple example or direct me to a good resource. Thanks a lot.
Here's my Javascript part for upvoting:
$(document).ready(function() {
$('#{{ upbtnID }}').click(
function() {
var postID = "{{ answer.id }}";
var data = {
'id': "{{ answer.id }}"
};
var score = document.getElementById('{{ scoreID }}');
var scoreText = score.textContent;
var scoreToInt = parseInt(scoreText, 10);
var newScore = ++scoreToInt;
var scoreToStr = newScore.toString();
$(this).css('border-bottom-color', '#26EDEB');
score.textContent = scoreToStr;
$.ajax({
url: "/upvote",
data: JSON.stringify(data, null, '\t'),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function(response) {;
},
error: function(error) {
alert("Awww");
}
});
});
And the corresponding function in Flask:
# upvote a post
#app.route('/upvote', methods=["GET", "POST"])
def upvote():
if request.method =="POST":
thePostID = int(request.json["id"])
thePost = Answer.query.get(thePostID)
thePost.score += 1
db.session.commit()
data = thePost.score
return ('', 204)
Quoting from Flask snippets:
#app.route('/set_cookie')
def cookie_insertion():
redirect_to_index = redirect('/index')
response = current_app.make_response(redirect_to_index )
response.set_cookie('cookie_name',value='values')
return response
Link: http://flask.pocoo.org/snippets/30/

Maintain Angular Service through page change

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

Categories