Cookies works in Postman , but not in browser - django

I created a login API using Django rest framework and then used session auth.
When i sent request via Postman , i get csrftoken and sessionid cookies.
and i was able to access content on backend.
OK fine.
But when i built small login form html and called that API for logging in. It worked.
I see COOKIES IN RESPONSE BUT COOKIES ARE NOT SET IN CHROME BROWSER.
Under Storage section in dev tools cookies are empty.
when i tried to access content(other views/apis) , i was not able to..
I think its because of Cookies are not being stored in browser..
Been on this like 5 days. Please can Someone explain about cookies not being saved.?
View.py
class Login(APIView):
authentication_classes = [SessionAuthentication,]
def post(self, request, format=None):
username = request.POST.get("username", "")
print(request.session)
password = request.POST.get("password", "")
user = authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
print(user)
return Response('Yes')
else :
return Response('No')
class List(APIView):
authentication_classes = [SessionAuthentication,]
permission_classes = [IsAuthenticated,]
def get(self, request, format=None):
return Response("Ark")
My Axios Request for login :
let s = this;
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Authorization", "Basic cjox");
myHeaders.append("Access-Control-Allow-Credentials","*");
var urlencoded = new URLSearchParams();
var requestOptions = {
method: 'POST',
credentials: 'same-origin',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
axios.post("http://127.0.0.1:8000/api/login/",urlencoded,{headers:myHeaders},{withCredentials: true})
.then(res=>{
console.log(res.headers);
})
My other request :
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Access-Control-Allow-Credentials","*");
var urlencoded = new URLSearchParams();
var requestOptions = {
method: 'GET',
credentials: 'same-origin',
headers: myHeaders,
redirect: 'follow'
};
axios.get("http://127.0.0.1:8000/api/d/",{headers:myHeaders},{withCredentials: true});

Related

How to fix upload file from angular 7 to django rest

I'have rest api devlopped with djago and application front devlopped with agular7 and i try to upload image to my rest api when i try to send it with form data the form data is empty in the api.
for angular i try to send form data with file.
Angular:
getPredictionImage(file): Observable<any> {
const HttpUploadOptions = {
headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data'})
}
const f = new FormData();
f.append('image', file, file.name);
console.log(f);
return this.http.post(this.urlapiimage, file, HttpUploadOptions);
}
Django:
def post(self, request, format=None):
print("heloooo")
print(request.data)
serializer = MammographySerializer(data=request.data)
print(serializer)
if serializer.is_valid():
result='hi'
serializer.save()
return Response(result,status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
the request.data is empty
it worked for me may be this help u to find your solution
Angular :
upload(file): Observable<any> {
let csrftoken = getCookie('csrftoken');
let headers = new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'X-CSRFToken': csrftoken,
});
const formdata = new FormData();
formdata.append("image", file); //i did not use 3rd argument file.name
let options = {
headers: headers, withCredentials :true }
return this.http.post(this.urlapiimage , formdata, options )
}
Django:
def post(self, request, format=None):
if 'file' not in request.data:
raise ParseError("Empty content ")
photo = request.data["file"]
serializer = MammographySerializer(photo = photo) // use this instead data =request.data
if serializer.is_valid():
result='hi'
serializer.save()
return Response(result,status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
after trying this , than also u r getting error , read about DRF parser ( https://www.django-rest-framework.org/api-guide/parsers/)
"important point if u r using chrome and if r using http://127.0.0.1:8000/ for django server and localhost:4200/ for angular than because of CORS(different ports) chrome does not allow . use this 127.0.0.1:4200/ for angular server instead of localhost:4200/ and if u don't want to do this use firefox instead of chrome it allows CORS

Django AJAX login without re-direct

Yes, there is a similar question without resolution to the actual question.
My users may be trying out the app and then decide to register for an account to save. Once registered I need to log them in without redirecting or reloading the page. I've got the registration working and logging them in is no problem, but what do I return to the client in order for the logged in session to be active in the browser? I'm not looking to add any other frameworks or libraries to the stack, please.
Django View (some omitted)
class CheckAuthTokenAjaxView(FormView):
form_class = AuthTokenForm
def post(self, *args, **kwargs):
form = self.form_class(self.request.POST)
u = get_user_model().objects.filter(email=email).first()
u.email_confirmed = True
u.save()
login(self.request, u)
# What should I be sending back?
return JsonResponse({"success": True}, status=200)
JS
Doc.Register.checkAuthTokenForm = function(event) {
event.preventDefault();
var form = document.getElementById('authtoken-form');
var data = new FormData(form);
d3.json('/users/ajax/checkAuthToken/', {
method: 'post',
body: data,
headers: {
// "Content-type": "charset=UTF-8",
"X-CSRFToken": Doc.CSRF,
}
})
.then(result => {
if (result.hasOwnProperty('errors')) {
// ...
} else {
// WHAT DO I DO HERE?
}
});
}

Django + Axios: File download not working in Firefox

I am using Axios to send my Django backend information, which in turns creates a file and sends it back to the front end. The code I have below works great in Safari and Chrome. However, the file does not download in firefox. BTW, no errors show up in the firefox console, or in Django.
Axios
axios({
method:'post',
url:'/api/downloadDoc',
responseType:'blob',
data: params,
})
.then(response => {
let blob = new Blob([response.data], {type: 'application/force-download'})
let link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = "YourPaper.docx"
link.click()
})
.catch(e => {
console.log(e)
})
Django View Sending File
def downloadPaper(request):
if request.method == "POST":
#Recieve info through post and create document
#variable path is path to newly created document
wrapper = FileWrapper(open(path, 'rb'))
response = HttpResponse(wrapper, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename=' + 'yourpaper.docx'
response['Content-Length'] = os.path.getsize(path)
return response
return HttpResponse(status=405)
I am hoping someone knows what could be causing firefox to not download.
Thanks!
fetch("/api/admin/plugin/download/" + id , {
method: 'GET',
headers: new Headers({
"Authorization": this.token,
"Allow-Control-Allow-Origin": "*",
"Content-Type" : "application/octet-stream"
}),
}).then(response => {
response.blob().then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
// must add <a> to body, then it works
document.body.appendChild(a);
a.style.display = 'none';
a.href = url;
a.download = decodeURI(response.headers.get("filename"));
a.click();
document.body.removeChild(a);
});
})

Anonymus user Django + Angular 2

i am using django + angular 2
i am using rest_framework_jwt with a url like this
url(r'^api/api-token-auth/', obtain_jwt_token),
url(r'^api/settings/?$', views.SettingsValues.as_view()),
My view is
class SettingsValues(generics.ListAPIView):
serializer_class = SettingsSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def get_queryset(self):
queryset = Settings.objects.all()
queryset = queryset.filter(user=self.request.user.id)
print self.request.user
return queryset
My service is:
getSettings() : Promise <SettingsValues> {
return this.http.get('/api/settings', { headers: this.headers })
.toPromise()
.then(response => response.json() as SettingsValues);
}
My login is working fine, but i cannot return the settings from django..
The print inside def get_queryset shows AnonymousUser.
Any idea what i am doing wrong ?
EDIT
private headers = new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json',
});
After obtaining the token from server, you have to save it and send in the header of subsequent api calls. Something like this:
getSettings() : Promise <SettingsValues> {
this.headers.append('Authorization', 'JWT ' + token);
return this.http.get('/api/settings', { headers: this.headers })
.toPromise()
.then(response => response.json() as SettingsValues);
}
In Angular 1.x.x, i can add this to cache Authorization Header for all subsequent api calls.
$http.defaults.headers.common.Authorization = 'JWT ' + token`;
In Angular 2, I am not sure how to cache it for all but take a look at this answer

Get Django sessions on Node.js

I'm trying to add Node.js to my web application in Django to have real time.
I'm doing the functionality of "like" as in facebook, when users click "like" AJAX will post the ID of song to domain.com:3000 (Node.js server).
I have the user ID on a session variable, but i don't know how to access to this session variable from Node.js.
Here is my code:
Node.js
var express = require('express');
var app = express();
app.use(express.static('./public'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.get('/', function(req, res){
res.send("ID user: " + req.session.user_id);
});
app.listen(3000);
console.log("Working under 3000")
Django
def auth(request):
if request.is_ajax() and request.method == 'POST':
email = request.POST.get('username', '')
password = request.POST.get('password', '')
autenti = JayapalBackend()
auth = autenti.authenticate(email, password)
if auth is not None:
id_usuario = Usuario.objects.get(email=email).getId()
request.session['user_id'] = id_usuario
return HttpResponse('1')
else:
return HttpResponse("-1")
else:
return HttpResponse("-1")
Thanks
EDITED:
I get this error:
TypeError: Cannot read property 'user_id' of undefined