django encountered with ConnectionResetError: [WinError 10054] - javascript

I am new to django and would like to write a simple log in web page
frontend: html, css, javascript(using bootstrap and jquery)
After filling the username and password and clicking the sign in button, it is supposed to jump to the home page.
Here is my code:
html:
<form id="sign-form" role="form">
{% csrf_token %}
<div class="form-group">
<label for="name" class="sr-only"> username </label>
<input id="name" type="text" class="form-control" placeholder="Username...">
</div>
<div class="form-group">
<label for="password" class="sr-only"> password </label>
<input id="password" type="password" class="form-control" placeholder="Password...">
</div>
<div class="form-group">
<button class="btn btn-block" id="sign-in-button"> Sign in </button>
</div>
<div class="form-group">
<button class="btn btn-block" id="sign-up-button"> Sign up </button>
</div>
</form>
js:
$("#sign-in-button").click(function () {
var name=$("#name").val();
var word=$("#password").val();
$.post("/login/",
{
'username': name,
'password': word
},
function (result) {
alert(result);
}
);
});
urls:
urlpatterns = [
path('admin/', admin.site.urls),
path(r'landing/', views.landing_page),
path(r'login/', views.login),
path(r'homepage/', views.home_page),
]
views:
def landing_page(request):
return render(request, "landingPage.html")
def login(request):
print("here log in")
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = auth.authenticate(username=username, password=password)
print(username+" out")
if user is not None:
auth.login(request, user)
print(username)
return render(request, "homePage.html", {'username': username})
return render(request, "homePage.html")
return render(request, "homePage.html")
But I encountered this problem(please have a look at the pictures):
The remote host forced the closure of an existing connection
The remote host forced the closure of an existing connection
The remote host forced the closure of an existing connection

Related

Issue about python flask login page

My codes are running and insert the user information in the database(MySQL) but the login cannot work. These codes are bellow.
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<link href="https://fonts.googleapis.com/css2?family=Jost:wght#500&display=swap" rel="stylesheet">
</head>
<body>
<div class="main">
<input type="checkbox" id="chk" aria-hidden="true">
<div class="signup">
<form method="post">
<label for="chk" aria-hidden="false">Sign up</label>
<input type="text" name="txt" placeholder="User name" required="">
<input type="text" name="email" placeholder="Email" required="">
<input type="password" name="pswd" placeholder="Password" required="">
<button id="button-1" onclikc="main_page()" href="/ ">Sign up</button>
</form>
</div>
<div class="login">
<form method="get">
<label for="chk" aria-hidden="true">Login</label>
<input type="email" name="email_1" placeholder="Email" required="">
<input type="password" name="pswd_1" placeholder="Password" required="">
<button id="button-2" onclick="login()">Login</button>
</form>
</div>
</div>
</body>
</html>
MYSQL CODES
CREATE TABLE user_table (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(55) NOT NULL,
email VARCHAR(55) NOT NULL,
userpass VARCHAR(122) NOT NULL);
from flask
import Flask, render_template, request, redirect, session, flash, url_for, escape
from functools
import wraps
from flask_mysqldb
import MySQL
import MySQLdb.cursors
from sympy
import re
app = Flask(__name__, template_folder = "template")
app.config['MYSQL_HOST'] = ''
app.config['MYSQL_USER'] = 'user'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'db'
mysql = MySQL(app)
def register():
if request.method == "POST":
details = request.form
username = details['txt']
password = details['pswd']
email = details['email']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO user_info(username, email, userpass) VALUES (%s, %s, %s)", (username, email, password))
mysql.connection.commit()
cur.close()
return render_template("index.html")
#app.route('/', methods = ["GET", "POST"])
def mainpage():
return register()
#app.route("/", methods = ["POST"])
#app.route("/home", methods = ["GET"])
def login():
if request.method == "POST":
email = request.form["email_1"]
pwd = request.form["pswd_1"]
cur = mysql.connection.cursor()
cur.execute("select * from user_info where email=%s and userpass=%s", (email, pwd))
data = cur.fetchone()
if data:
session['logged_in'] = True
session['username'] = data["username"]
else :
msg = "invalid login"
flash("yanlış bilgi!!", "error_message")
return render_template('home.html', status = True)
def is_logged_in(f):
#wraps(f)
def wrap( * argws, ** kwargs):
if 'logged_in' in session:
return f( * argws, ** kwargs)
else :
return redirect(url_for('login'))
#app.route("/logout")
def logout():
session.clear()
flash('You are now logged out', 'success')
return redirect(url_for('login'))
if __name__ == '__main__':
app.secret_key = "secret_key"
app.run(debug = True)
Can you help me to find the error or How can i connect the another screen in after clicking to the login button. Additionally I cant fix the problems about that data duplication and any message that visualization on the html screen.
Thank you :)

How to loging to django with login form? With or without Ajax

Problem:
If user is loggedin, I want to show greet user else show the form
and when the valid data is submitted, log in the user and
show greet message.
I am trying to pass the data on submit and update the user status to login. I tried with and without ajax but with both ways I could not figure out solution. Could you please help me why its failing? And how I can solve this?
HTML Form:
{% if user.is_authenticated %}
<h5 class="title billing-title ls-10 pt-1 pb-3 mb-0">
Welcome {{ user.username }}!
</h5>
{% else%}
<div class="login-toggle">
Returning customer? <a href="#"
class="show-login font-weight-bold text-uppercase text-dark">Login</a>
</div>
<form class="login-content" name="ajaxLogin" method="POST" action="{% url 'ecommerce:ajaxlogin' %}">
{% csrf_token %}
<p>If you have shopped with us before, please enter your details below.
If you are a new customer, please proceed to the Billing section.</p>
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label>Username or email *</label>
<input type="text" class="form-control form-control-md" name="username" id="id_email"
required>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label>Password *</label>
<input type="password" class="form-control form-control-md" name="password" id="id_password"
required>
</div>
</div>
</div>
<div class="form-group checkbox">
<input type="checkbox" class="custom-checkbox" id="remember" name="remember">
<label for="remember" class="mb-0 lh-2">Remember me</label>
Lost your password?
</div>
<button class="btn btn-rounded btn-login" type="submit" >Login</button>
</form>
{% endif%}
Views.py :
def ajaxlogin(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(user=username, password=password)
if User.is_active and not None :
login(request)
else:
pass
return render('./ecommerce/checkout.html')
AJAX:
$(document).ready(function(){
$('.login-content').on('submit', function(event){
event.preventDefault();
var action_url = $(this).attr('action')
$.ajax({
url: action_url,
type:"POST",
data: $('.login-content').serialize(),
headers: { "X-CSRFToken": $.cookie("csrftoken") },
success: function (data) {
console.log("login Successful");
},
});
});
});
Django authenticate takes keyword arguments username and password for the default case with request as optional parameter.
In your views.py you pass user as parameter in authenticate change it to username.
The default authentication returns None if user is in-active so you don't have to check for is_active if you are using default authentication.
Change your views.py as
def ajaxlogin(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None :
login(request, user)
else:
pass
return render('./ecommerce/checkout.html')
Also set contentType as application/x-www-form-urlencoded or leave it at the default by omitting the contentType key.

Node.js Sails html data using "POST" method can not pass to controller

I am new to MVC.
When I want to pass the form data from ejs file to controller, it does not work.
Create.ejs file
<!--create.ejs-->
<h2 class="col-sm-offset-1">Person Create form</h2>
<form action="/person/create" method="POST" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2">Name: </label>
<div class="col-sm-8">
<input class="form-control" name="Person[name]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Age: </label>
<div class="col-sm-8">
<input class="form-control" name="Person[age]" type="number"
min="0" max="120">
</div>
</div>
<button class="btn btn-default col-sm-offset-2" type="submit" value="ADD">Submit</button>
PersonController.js
module.exports = {
create: function(req, res) {
if (req.method == "POST") {
Person.create(req.body.Person).exec( function(err, model) {
return res.send("Successfully Created!");
});
} else {
return res.view('person/create');
}
},
The result is that it cant get inside the (req.method == "POST") condition.
Give me 404 error.
A 404 is a not found result.
When POSTing ensure you are targeting your Controller functions try:
'POST /person/create': 'person/PersonController.create',
Though why do you have a subfolder named person when you are using a controller?
Using Actions
In Sails v1.0 you would separate your controller functions into more manageable actions. A sub folder api/controllers/person makes more sense now.
Your routes.js file would read 'POST /person/create': {action: 'person/create'},
For simplicity I have removed req.body.Person as an array...
<form action="/person/create" method="POST" class="form-horizontal">
<input type="hidden" name="_csrf" value="<%= _csrf %>" />
<div class="form-group">
<label class="control-label col-sm-2">Full Name: </label>
<div class="col-sm-8">
<input class="form-control" name="fullName" placeholder="John Johnson" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Age: </label>
<div class="col-sm-8">
<input class="form-control" name="age" type="number" min="0" max="120">
</div>
</div>
<button class="btn btn-default col-sm-offset-2" type="submit" value="ADD">Submit</button>
</form>
then your async function would be like...
module.exports = {
friendlyName: 'Create Person.',
description: 'Creating a new person.',
exits: {
success: {
description: 'Person Created successfully.',
viewTemplatePath: 'person/review',
}
},
fn: async function (inputs, exits) {
if (!this.req.me) throw {redirect: '/'};
let params = this.req.allParams();
let person = await Person.create(params).fetch();
return exits.success({person:person});
}
}
Like #Tejashwi suggested you need to change your route to a POST.
'POST /api/v1/create': { action: 'create/person-create-form' },

Sending data to a modal without redirecting in nodejs

I am using passport and flash to manage authentication. I want to send flash messages back to the UI per the documentation. In my scenario in the UI I am using a modal so doing a
res.render('login.ejs', { message: req.flash('loginMessage') });
won't work because you can only render on a page refresh. Therefore how can I send flash dataor any other kind of data to my page when fails to log in for some reason. Regardless of flash data in particular I cannot figure out how to render data to a modal with express.
routes.js
below the res.render never happens on a authentication failure.
//Home Page ===================================
app.get('/', function(req, res) {
res.render('login.ejs', { message: req.flash('loginMessage') });
});
//Login Modal =================================
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile',
failureFlash : true
}));
index.ejs (where my modal is)
<div id="openModal" class="modalDialog">
<div>
X
<h2 id="logintitle">Log In</h2>
<% if (message.length>0) { %>
<div class="alert alert-danger">
<%= message %>
</div>
<% } %>
<form class="form-horizontal" action="/login" method="post" id="loginform">
<div class="form-group inner-addon left-addon">
<label class="sr-only" for="login_email">Email</label>
<i class="glyphicon glyphicon-user"></i>
<input type="email" class="form-control" name="email" placeholder="Email Address" />
</div>
<div class="form-group inner-addon left-addon">
<label class="sr-only" for="login_pass">Password</label>
<i class="glyphicon glyphicon-star-empty"></i>
<input type="password" class="form-control" name="password" placeholder="Password" />
</div>
<div id="forgotpass">
Forgot Password?
</div>
<div class="form-group">
<button type="submit" class="btn form-login-button">Log In</button>
</div>
</form>
<div class="strike">
<span>Log in with</span>
</div>
<div id="test" class="test">
<span class="fa fa-facebook"></span> Facebook
<span class="fa fa-google-plus"></span> Google
</div>
</div>
</div>
My understanding is I need to use javascript/ajax to prevent the post for being the redirect but I cannot figure out how to get the flash data to this point:
index.ejs (javascript)
$(function () {
$("#loginform").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function () {
},
success: function (data) {
}
});
});
});
EDIT added some code from passport.js
function passport_login(req, email, password, done) {
//doing some validate and found bad password
return done(null, false, req.flash('loginMessage', 'Invalid Password'));
})
So after quite a bit of digging I have found the solution. The key was in recognizing jquery not express is the answer, letting the client handle the redirects and posts/gets. I have only include updates for a local login strategy but they would apply for your signup/social other social profiles as well.
Changes to passport.js (minor)
function passport_login(req, email, password, done) {
//doing some validate and found bad password
return done(null, false, 'Bad Password');
})
Changes to my route (the part I struggled with)
The key things to note here is I am deciding what data I sent through res.send. I could send anything, in this case info is what comes from passport.js ('Bad Password'). If i am happy and able to log in I send a simple little valid:true json.
//Login Modal =================================
app.get('/localLogin', function(req, res, next) {
passport.authenticate('local-login', function(err, user, info) {
if (err) { return next(err); }
//if there is no user in the response send the info back to modal
if (!user) {
return res.send(info);
}
//user was able to login, send true and redirect
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.send({ valid: true });
});
})(req, res, next);
});
Changes to my index.js
Added a div on top the my modal to display messages, remove old <%= message > piece and delete the action and method from the form jQuery will do that for us. (included full modal code to be transparent)
<div id="openModal" class="modalDialog">
<div>
X
<h2 id="logintitle">Log In</h2>
<div id="loginPopup"></div>
<form class="form-horizontal" id="loginform">
<div class="form-group inner-addon left-addon">
<label class="sr-only" for="login_email">Email</label>
<i class="glyphicon glyphicon-user"></i>
<input type="email" class="form-control" name="email" placeholder="Email Address" />
</div>
<div class="form-group inner-addon left-addon">
<label class="sr-only" for="login_pass">Password</label>
<i class="glyphicon glyphicon-star-empty"></i>
<input type="password" class="form-control" name="password" placeholder="Password" />
</div>
<div id="forgotpass">
Forgot Password?
</div>
<div class="form-group">
<button type="submit" class="btn form-login-button">Log In</button>
</div>
</form>
<div class="strike">
<span>Log in with</span>
</div>
<div id="test" class="test">
<span class="fa fa-facebook"></span> Facebook
<span class="fa fa-google-plus"></span> Google
</div>
</div>
</div>
Then I added the following Jquery code the last piece to the puzzle:
$(function(){
$('#loginform').on('submit', function(e) {
e.preventDefault();
var data = $(this).serialize();
$.get('/localLogin', data, function(result) {
if(result.valid == true)
{
window.location.href = '/profile';
}
else
{
$('#loginPopup').html(result);
}
});
});
});
Hope this helps someone, the information for a full end to end solution on how to do this is sparse.

Django JQuery AJAX submit form POST request refreshes the page

I have a login form for which I want the client to send AJAX POST request as below with error handling. In case of validation/authentication errors, I don't the page to be reloaded or refreshed to the url corresponding to POST request Handler(/users/login/) with the JSON string received from login view's response. I tried using event.preventDefault() as suggested by many answer on SO but could not make it work. Any clue as to what is going wrong here? I don't think this to be a Django issue. I know that the onsubmit is triggerred because the window redirects to the POST handler URL /users/login/ with the expected JSON string response - {"error": ["Entered mobile number is not registered"]}
JQuery code
$("#loginform").on('submit', function(event) {
event.preventDefault();
alert("Was preventDefault() called: " + event.isDefaultPrevented());
console.log("form submitted!");
var url = "/users/login/";
$.ajax({
type: "POST",
url:url,
data: $("#loginform").serialize(),
success: function(data)
{
console.log(data);
var result = JSON.stringify(data);
if(result.indexOf('errors')!=-1 ){
console.log(data);
if(data.errors[0] == "Mobile number and password don't match")
{
$('.login-error').text("Mobile number and password don't match");
}
else if(data.errors[0] == "Entered mobile number is not registered")
{
$('.login-error').text("Entered mobile number is not registered");
}
}
else
{
window.open("/users/profile/");
}
//var result = JSON.stringify(data);
// console.log(result);
}
})
});
View Handler
def login(request):
if request.method == 'POST':
mobile_number = request.POST.get('mobile_number', '')
password = request.POST.get('password', '')
data = {}
user_queryset = User.objects.filter(mobile_number=mobile_number)
if len(user_queryset) == 0:
data['error'] = []
data['error'].append("Entered mobile number is not registered")
# return JsonResponse(data)
elif len(user_queryset) == 1:
email = user_queryset[0].email
user = auth.authenticate(email=email, password=password)
if user is not None:
auth.login(request, user)
else:
data['error'] = []
data['error'].append("Mobile number and password don't match")
return JsonResponse(data)
HTML code
<div class="container-fluid bg-primary" id="login">
<div class="row">
<div class="col-lg-3 text-center">
</div>
<div class="col-lg-6 text-center">
<h1> </h1><h3> </h3>
<h2 class="section-heading">Login to your profile</h2>
<hr>
</div>
<div class="col-lg-3 text-center">
</div>
<h2> </h2>
<h2> </h2>
<h2> </h2>
</div>
<div class="col-md-4 col-md-offset-4 ">
<form id='loginform' action='/users/login/' method='post' accept-charset='UTF-8'>
{% csrf_token %}
<fieldset >
<div class="form-group">
<input type="text" name="mobile_number" id="mobile_number" tabindex="1" class="form-control" placeholder="Mobile Number" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Enter Password">
</div>
</fieldset>
<button type="submit" class="btn btn-primary btn-xl btn-block">LOG IN</button><br><br>
<span class="login-error"></span>
<h1> </h1><h1> </h1>
</form>
</div>
</div>
In addition to event.preventDefault();, it might be a good idea to also call event.stopPropagation() in this case.
Use : 'event.preventDefault()' or 'return false' after the ajax call.

Categories

Resources