Integrating Flask Security and Flask Rest-JSONAPI - flask

i try to build a REST API with Flask-JSONAPI and Flask Security.
I use Auth Token for authentication and #login_required to secure my API Endpints. (Authentication)
But now I want to ensure that only the owner of objects (Creator) can (C)RUD the data. Right now every user can see every object that is created. (Autorisation)
I want to use Resource Manager here but did't find a proper example for Flask Security in Resource Managers.
For Example the user (person) can only see the computer objects associated with the same user id.
Do I have to use the Auth Token for that?
Is there a simple way to get the id of the user logged in, doing the request?

from flask_security import current user
That represents a user instance of the currently logged in user. This user can be anonymous in cases where no user is logged in, but if a user is logged in then the object will represent an object of the User class.

Related

Django rest framework jwt token permission

Now I made some API with Django rest-framework. And I used JWT for token authentication.
At this moment, I have some questions about token permission.
How can I detect token permission in Django?
For example, There is user A and user B.
When user A wrote article "test", article "test" can only be edited or deleted by user A.
But how can I detect permission about article "test"?
The token will be changed every time when user login. So detect by token is not the correct way.
I searching Google few hours, if there is any solution about this. Is there any way to determine user permission by token?
Thanks in advance!
JWT authentication allows you to identify the user who have previously signed up to your Django app, thanks to the token attached to every request they send to your server.
Then, a permission (that you define and shape as you wish) allows you to let or not let user access / edit a given resource / page.
More practically, what you want to achieve can be set up as follows (assuming you use class based views):
class MyApiEndpoint(ApiView):
authentication_classes = (JSONWebTokenAuthentication,)
permission_classes = (IsOwner,)
where:
JSONWebTokenAuthentication is the authentication class provided by djangorestframework-jwt.
IsOwner is a Permission class you need to write to check if the current user is owner of the resource hosted by the given view / API endpoint. (More on this here).

Python-social-auth: do not reassociate existing users

I'm using python-social-auth to allow users to login via SAML; everything's working correctly, except for the fact that if a logged-in user opens the SAML login page and logs in again as a different user, they'll get an association with both of the SAML users, rather than switch login.
I understand the purpose behind this (since it's what you can normally do to associate the user with different auth services) but in this case I need to enforce a single association (ie. if you're logged in with a given SAML IdP, you cannot add another association for the same user with the same provider).
Is there any python-social-auth solution for this, or should I cobble together something (for instance, preventing logged-in users from accessing the login page)?
There's no standard way to do it in python-social-auth, there are a few alternatives:
Override the login page and if there's a user authenticated, then log them out first, or show an error, whatever fits your projects.
Add a pipeline function and set it in the top that will act if user is not None, you can raise an error, logout the user, etc.
Override the backend and extend the auth_allowed method in it return False if there's a valid user instance at self.strategy.request.user. This will halt the auth flow and AuthForbidden will be raised.

Using Firebase Auth with Django

I want to use firebase authentication for my django webapp. To achieve this, I think would I need to write a custom auth backend - is that right? I don't see any libraries that already do this - django-allauth looks like it comes pretty close as an alternative but I am interested in the phone number verification provided by firebase.
I'm also confused about what happens to the User model and functions like request.user or user.is_authenticated. Right now I use the authenticate and login functions - how does django know that a user is logged in via firebase? Would I still be creating a User model for every user?
Thanks
You can use Firebase Auth with any framework. You don't necessarily need to use custom auth. Typically, you would sign in the user on the client, get the ID token by calling firebase.auth().currentUser.getIdToken() and then pass the ID token to your server, verify it and parse its payload identifying the user ID and its other claims by using the Firebase Admin SDKs and then you can issue a session cookie identifying the user associated with that ID token.
On signout, you would clear that session cookie.
If you also need to persist that user on the backend after setting the session cookie, you can also use the Firebase Admin SDK to lookup a user identified by the user ID or just use the token claims to populate the user without any network call. You can populate that in the user model of associated framework if needed.
For more on session management, you can refer to this django documentation: https://docs.djangoproject.com/en/3.0/topics/http/sessions/

django-auth: login with user uuid and limit permissions

I'm trying to create a kind of quick response form where a user does not need to login but is identified with his uuid (in the url). Moreover i need to restrict his permissions for this session so that he only could to a few things.
User gets url with UUID and ID of event (Where he can response)
User clicks on link and response page opens
User is identified via uuid
With the id of the event the event response form is generated
User can chose options and submit the form
Normally there are multiple other options (e.g. in the menue) available but these should only be accessible if user identifies with his username and password.
Of course i could write a special view but is there a more elegant way where i could reuse my existing view for the response?
First you'll want to use the UUID to trigger the login.
How you approach this will depend on whether you mind using a specific login url/view or you want people to arrive directly at the intended url/view (just with the UUID parameter). If you use a specific view you'll check the UUID, (presumably mark it as used/expired), then login the user. Alternatively for the UUID to checked and have users login via any url/view, you'll want a to use a custom middleware that's placed ahead of AuthenticationMiddleware in your middleware settings. In each case, once you have the logged in the user, you'll want to store in session some sort of flag to indicate they've auth'd via a temporary login UUID.
Now that you've authenticated and logged in the user via the UUID, it's time to serve them the view. At this point in your View you'll check for presence of the flag in the user session to determine their permissions.
You could go further and create another middleware class to encapsulate the session lookups and add a property, say "is_auth_temporary", to the request.User object that is a sibling to the is_anonymous and is_authenticated property.

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