How to set up session in vuejs django after successful login? - javascript

If login is successful i need to redirect to a login success page and I need to include a session in that.. How can it be possible. I am using html with vue js for front end and back end is django.
This is my vue js script for login.
<script>
logBox = new Vue({
el: "#logBox",
data: {
email : '',
password: '',
response: {
authentication : '',
}
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['email'] = this.email;
data['password'] = this.password;
$.ajax({
url: '/login/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if(e.status){
alert("Login Success");
// Redirect the user
window.location.href = "/loginsuccess/";
}
else {
vm.response = e;
alert("failed to login!");
}
}
});
return false;
}
},
});
</script>
So, how can I include session in login successpage.. This is the first time I am doing a work.. Please help me ..

If you are not doing a SPA, you can use the usual way of store sessions, put the session token in a cookie (the server is the responsible of doing when a successful login request happens). The next time the user do a request the cookie will send automatically to the server.
If you are doing a SPA, you can store the session token in the localStorage. In this case, you should configure the ajax calls to set a header with the token or any other way you prefer to send the token to the server.

Related

localStorage won't store data

I have a demo of a simple Login and Logout application with access token. If the user haven't login yet and they try to access other page, which mean access token is null, they will be direct back to Login page. I use sessionStorage to store user token and it work fine. When I try using localStorage, my application won't work anymore. It still login in but for an instance moment, it direct me back to the Login page like my token isn't saved at all. It still generate new token after successfully login so I guess it having something to do with localStorage.
Edit: I just checked back and they both storage my token but I can't parse it to other pages with localStorage.
My Login Page Code:
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
userName: $('#txtFullname').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
// Khi đăng nhập thành công, lưu token vào sessionStorage
success: function (response) {
//sessionStorage.setItem("accessToken", response.access_token);
localStorage.setItem("accessToken", response.access_token);
window.location.href = "User.html";
//$('#divErrorText').text(JSON.stringify(response));
//$('#divError').show('fade');
},
// Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
Other page base code:
if (localStorage.getItem('accessToken') == null) {
window.location.href = "Login.html";
}
Are you sure that response.access_token does not come null?
You can check it from the development tools in Chrome (Windows: Ctrl + Shift + i or macOs: command + option + i)> Application > Storage > Local Storage:
As you can see the value can be set null.
I hope it helps.
localStorage supports only string values. Chances are response.access_token might not be a string value. So try this instead:
localStorage.setItem("accessToken", JSON.stringify(response.access_token));
And While retrieving,
JSON.parse(localStorage.getItem("accessToken"))
Try to save object in localstorage use following method (as shown in https://stackoverflow.com/a/2010948)
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
And in your code we can do it like this
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
userName: $('#txtFullname').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
// Khi đăng nhập thành công, lưu token vào sessionStorage
success: function (response) {
var obj= { 'accessToken': response.access_token};
localStorage.setItem(JSON.stringify(obj));
window.location.href = "User.html";
},
// Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});

session data getting stored every time

Below is the API that basically stores data in session if not already present then returns an empty JSON, otherwise sends the session data stored corresponding to that mail:
app.use('/session', function(req, res) {
if (req.body.email in req.session) {
console.log("user data already available");
res.send(req.session[req.body.email]);
} else {
req.session[req.body.email] = {};
req.session[req.body.email]["email"] = req.body.email;
req.session[req.body.email]["gender"] = req.body.gender;
req.session[req.body.email]["dbname"] = req.body.dbname;
console.log("user session stored");
res.send({});
}
});
Below is the ajax call that I am making from my application. It is a cross domain call and I have set the response header accordingly.
$.ajax({
url: 'url/session',
type: "POST",
crossOrigin: true,
data: {
"email": "email",
"gender": "all",
"dbname": "dbname"
},
success: function(data) {
console.log("inside session api call success");
console.log(data)
}
});
});
Now the problem is that if I hit the API using postman, it works fine but when I use that in my application, it overwrites the session every time and returns empty json. What am I doing wrong?
edit : Figured out that each time ajax call is happening, past session data gets deleted for all emails ids.session value gets reset but still unable to figure out why this is happening.

not going through the django view through ajax post data

I am doing the login throgh ajax. jquery function is working fine but its not going to the ajax url. So django view is not getting executed.
Ajax.html
$(function()
{
localStorage['domain'] = "http://122.172.64.142";
var domain = localStorage['domain'];
$('#fac1').on('click', function () {
var username = $("#username").val();
var password = $("#pwd").val();
data = {
name: username,
password: password
};
alert(domain);
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});
return false;
});
});
My django views.py
#csrf_exempt
def login_android(request):
print "i am in view"
if request.method == "POST":
print "you are in method"
username = request.POST['name']
password = request.POST['password']
login_api(request,username,password)
#return HttpResponseRedirect('/home/')
messages.success(request, 'You Loged In Successfully')
response = json.dumps(username)
return HttpResponse(response, mimetype="application/json")
When i click on login button i am getting alert but its not getting entered to view. Url is correct.
I would first recommend using Chrome with the developer tools console open.
You could change you alerts for console.log().
When your trying window.location = 'file:///android_asset/www/posts.html';
You are trying to access a local resource. If I post that in my Chrome developer tools I get back
Not allowed to load local resource: file:///android_asset/www/posts.html
If you would use window.location.replace("a url to your view"); this will work like a HTTP redirect.
for more information redirect page
and you should be able to see your view.
I was made a silly mistake. I provided a wrong domain address on this page. Now it worked.
localStorage['domain'] = "http://122.172.64.142";
This address was wrong. Thats why it was not able to enter in to the view.
You forgot dataType ajax param
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
dataType : 'json', //dataType param IS MISSING
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});

Cakephp Ajax Login is loggin in even with wrong data

I have a simple html form to login outside my cake structure, I send the login data via jquery to my login function:
public function login() {
if ($this->request->is('ajax')) {
$this->request->data['Appuser']['password'] = Security::hash($this->request->data['password']);
$this->request->data['Appuser']['name'] = $this->request->data['name'];
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl(array('action' => 'returnUserData')));
}else{
$this->response->body(json_encode('Login failed!'));
}
}elseif($this->request->is('post')){
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}else{
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
The very strange thing is:
the login via post from /view/users/login.ctp form works perfectly!
When I try to login from "outside" via ajax, I am always logged in even with wrong access details and get the data from function 'returnUserData'
$('#login').click(function() {
$.ajax({
type: "POST",
url: '/api/login',
data: {
name: $("#username").val(),
password: $("#password").val()
},
success: function(data)
{
alert(data);
}
});
});
When I set a debug(); after if ($this->request->is('ajax')) I can see it, so the script seems to go into the right if section. But I don't get it, why the $this->Auth->login always return true...?

how to call web service rest based using ajax + jquery

I am calling web service on this url .
here is my code .
http://jsfiddle.net/LsKbJ/8/
$(document).ready(function () {
//event handler for submit button
$("#btnSubmit").click(function () {
//collect userName and password entered by users
var userName = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(userName, password);
});
});
//authenticate function to make ajax call
function authenticate(userName, password) {
$.ajax({
//the url where you want to sent the userName and password to
url: "",
type: "POST",
// dataType: 'jsonp',
async: false,
crossDomain: true,
contentType: 'application/json',
//json object to sent to the authentication url
data: JSON.stringify({
Ticket: 'Some ticket',
Data: {
Password: "1",
Username:"aa"
}
}),
success: function (t) {
alert(t+"df")
},
error:function(data){
alert(data+"dfdfd")
}
})
}
Response
**
**
It mean that I first call this method then call login method ?
Perhaps the message means that during development, while you are writing and testing the code, use the URL:
http://isuite.c-entron.de/CentronServiceAppleDemoIndia/REST/GetNewAuthentifikationTicket
rather than:
http://isuite.c-entron.de/CentronService/REST/Login
Because you don't need the application id for the development method. You can see from the error message that you are missing the application (gu)id
The guid '61136208-742B-44E4-B00D-C32ED26775A3' is no valid application guid
Your javascript needs to be updated to use new url http://isuite.c-entron.de/CentronServiceAppleDemoIndia/GetNewAuthentifikationTicket as per the backend sode team.
Also, even if you do this, your will not be able to get reply correctly since service requires cross domain configuration entries in web.config. You have to use this reference:http://encosia.com/using-cors-to-access-asp-net-services-across-domains/ and configure server's web.config in a way so that you can call it from cross domain.

Categories

Resources