POST request from Django to authenticate an application with Django - django

Ok, so this seems bad (and it probably is, but i have enough doubts at the moment that I want to try it).
I have a Django bases website with a jwplayer flash app embedded on one of the pages. The user has to login to get at that page. The jwplayer just plays an icecast stream.
What I would like/need to do is have it so that only authenticated users can get to the icecast server. At the moment if they grab the url from the webpage, they can get to it fairly trivially.
Icecast can authenticate via POST which I've setup in a django view.
So what I want is for the flashplayer to send the username and password of the user that is logged in, to icecast, which will then authenticate with the same username and password.
My problem is that django doesnt store the actual password, just a hash (a good thing) so I'm beginning to think that I cant really send the user and password to icecast for it to authenticate with.
My other thoughts were to just send the username, and check if that person has already authenticated.
But this would allow someone to listen if someone was already logged in.
Could I do something with a session variable or something?
Django guru's help me! Im open to all and any ideas.
Cheers
Mark.

Why not just have your flash player look for the Django session cookie and then validate against the web server that the user is logged in?
Add something like this to your urls:
(r'^loggedin/', logged_in_user),
Add a view something like this (not tested):
from django.http import HttpResponseForbidden
def logged_in_user(request):
if request.user.is_authenticated():
return HttpResponseForbidden()
else:
response = HttpResponse(mimetype='text/plain')
response.write('ok')
return response
Then just do a get on the /loggedin/ and check the return code, if it's 200 they are logged in if 401 they are not (assuming you are passing in the session cookies)

Related

Can a user barge into django server as another user and perform operatn if he changes info in the frontend if we are using session authentication?

Hey guys I am confused and was thinking about this problem for sometime now, I am storing the current user's username in the session storage, and I have another page in which I use the stored username for an api call, it can be any requests.
Eg. a post can be deleted by its author only, suppose, the url is api/<slug>/delete and in the frontend I have enabled the delete button only for the corresponding user, what if he edits the front end page and changes it to his username or what if I use the stored username to check that condition?
And if he sends a delete request successfully from the frontend, does the django server able to determine that the user in the current session is not the real owner and has tweaked it in the frontend?
Ps. This might be a foolish question, but I am a beginner and quite confused.
Thanks.
Naturally, we would need some code to answer your question.
Will the following delete some other user's data?
A user passes a username from the client to the server
SomeModel.objects.filter(username=username).delete()
Will the above delete the user data whose username is what has been passed from the client? Yes.
You need to always verify and validate data and permissions on the server, and also you should consider using CRUD operations on the current authenticated user (since you are working with sessions), so you don't have to send the current user' username from client, if they are logged in, that can be validated with their session.
I'd advise you to read a little more on Authentication, sessions, ect. authentication in Django
Also, I see you are using A RESTful API, so I would strongly recommend using DRF

Django Sessions: Correct way to get logged in user data from server?

I have my API set up using SessionAuthentication. Once a user logs in, I redirect them to their profile page in React. Once they are redirected to their profile page, I want to make a REST call to retrieve their profile data and insert it in the proper location on the page. I see a couple ways I can do this:
When a user logs in, put their User ID into the Response object (DRF) and then store that in the client somewhere (Redux store, session storage, or local storage). Then when they are redirected to the login page, make a REST call to /users/users_id.
With Django sessions the logged in user is automatically tied to each request. So do I even need to follow Rest here? I can make a call to /users, and if the user is authenticated, return their data.
I would appreciate any help with this. Thank you.
With SessionAuthentication, after a successful login, the browser saves a sessionId cookie for that domain (or ip:port) automatically. Sending a request will send that cookie from the same domain no matter with Django or React, and authenticate the user, making your request.user a user.
You can check for the cookie when you inspect the page -> Application -> Cookies -> Your domain -> sessionId
Basically, you can login via Django and it will login you with React as well. No need to store anything manually. Just use the same domain for both.

Django-allauth, JWT, Oauth

I have an AngularJS Single Page Application that uses a Django backend API based on the Django Rest Framework. The API is protected via django-rest-framework-jwt. I would like to use django-allauth for account management and authentication on the server side.
I am just missing one single piece in the flow: How does my Oauth-Token from the client get transferred into a JWT-token? Basically, I would like to do as described here http://blog.wizer.fr/2013/11/angularjs-facebook-with-a-django-rest-api/ based on python-social-auth.
So my question is, how do I implement the ObtainAuthToken class from the link with django-allauth?
There are usually two login flows with social login: client-side ("Javascript SDK") and server-side. If your server needs to be authorised, it's usually a lot easier to go through the server-side flow. And that's also what all-auth does I think (and you didn't mention you use a frontend library like the blogpost you mentioned does).
Now the challenge is to provide the token from the server to the frontend. You would probably load the token in the HTML of the initialisation of the SPA, and then from Angular save the token client side (cookie, localStorage, etc.) so the session isn't lost on a refresh.
If you don't want the user to leave your app, you can open your /accounts/login/ or /accounts/signup/ url in a new window. In that new window they authorise your app, and your server receives the token upon return. There, you will have to generate a JWT token manually, and render that into the template so that javascript can access it. With js in that popup window, you can then communicate with your app that opened the popup and pass it the token – see this SO answer for an example – so it can save it.
Django-allauth provides signals that let you hook into the social login process. In your case, I would recommend subscribing to the allauth.socialaccount.signals.pre_social_login signal. The code will look something like this:
from allauth.socialaccount.signals import pre_social_login
#receiver(pre_social_login)
def create_jwt_token(sender, request, sociallogin, **kwargs):
# dig into the sociallogin object to find the new access token.
We used hello.js for O-Auth at the company I worked at.
You provide a shim on the Python end and get the refresh token and whatever other data needed once the user connects their social account.
We redirect them via Django to the page they attempted to access from their OAuth provider's page.
Each user still has their own email account which is needed for the JWT, but you could assume that whatever email is in the scope of their social account is their email then use django's functionality to create new users: User.objects.create(email=emailStringFromOauthData) etc.

How do I implement form based login with mysql in a RESTful web service?

I am developing hybrid mobile Application using phonegap(jquery mobile framework) and jersey rest java webservice.
How to do login and logout using mysql and rest webservice and maintain session of perticular user on every page like traditional webapplication(get username on every page).
i am totally stuck.can anyone provide sample example or any solution.
you can do in below way.
create session table contains column [id, token, userid, loggedintime]
on login call a rest like /rest/user/login?username=uname&password=pwd
which return a token to user. maintain that token at client side. you may use cookie or sessionstorage whichever supported by mobile device.
now create one Filter with path /* so each request pass through it, and in filter check that the users token is valid or not, if not than redirect to login. you can explicitly pass that token to server in queryparam or pathparam.
on logout delete entry from session table, and redirect user to login page again.
there are many way to do this thing but this is a simpler way.
It's simple, you store the username and password in your client and send them with every request. (On the server side you can have an (username, password) -> (identity, permissions) in-memory cache which can make things faster.) You need a secure connection: HTTPS. Without that you won't do REST auth.
Login is simple you show a prompt to the user, in which she can give the username and password, so you can store them in the memory of the client. By logout you can simply close the client (by browsers navigate away), or remove the username and password from the memory of it. (It is not secure to permanently store the username and password without proper encryption on the client side.)

which could be a good way to design an authentication mechanism to restrict the access to the backend to only registered users?

I'm making a mobile app that allows a registered user to
make a list of favourite email addresses.
I pretend to make the authentication process through openId,
so the user can login to the system using its gmail account.
The registered users of the system can insert many email
addresses to a database.
Then I have many controller methods.
One of them is getUsersByName(admin_email), which receives the email
of a registered user and returns a list of email adress inserted
by that user.
Now, the problem is that I don't want everyone can access
to getUsersByName(admin_email) and retrieve the response
related to every registered user.
What options do I have so only the user that inserted the email
addresses can access to the list related to it.
For instance, if a registered user calls getUsersByName(admin_email),
the server responses with the right list, but if someone not
registered makes an http request to getUsersByName(admin_email), the
server responses with a JSON error object.
My backend is in django and I want to make the client in Android.
I hope I have been clear enough.
Thanks in advance!
The easiest way to achieve what you're looking for is this and I'm going to assume Django 1.6 and that you're using a functional view and not a Class based View.
#login_required
def getUsersByName(request):
user_email = request.user.email
all_users_emails = UserEmail.objects.filter(added_by=user_email)
return render_to_response(...)
What this does is that this view is now protected by the decorator #login_required from being accessed if you're not logged in, i.e. you have to be registered and logged in, in order to view your added emails.
It will also redirect to your login view if an unregistered users tries to gain access to the view.
Furthermore by doing it like this, your users will never be able to send in others email addresses in order to gain access to them.
For Class based views you can take two approaches, both explained here