RooneyMUFC
RooneyMUFC

Reputation: 133

flask restful api dynamic endpoints with restrictions

So i am relatively new to flask only a couple weeks. To learn flask more I have set myself an objective on building my own api.

use case of the API:

  1. authenticated users should be able to hit the endpoint
    www.mydomain.com/api/ and do the below activities (only to their
    tasks)

    • increase count (POST/PUT)
    • decrease count (DELETE)
    • reset count
  2. non authenticated users should be able to go to www.mydomain.com/api/john and view John's metrics. I expect there to be many users each with their own metrics

Current state:

I can perform, post, get, put and delete operations (no authentication setup yet...)

My question:

Is there a way to restrict users based on their userid. by this I mean john only has access to perform requests against www.mydomain.com/api/john.

Upvotes: 1

Views: 470

Answers (1)

CodeLikeBeaker
CodeLikeBeaker

Reputation: 21312

There are several ways of handling this and it's all going to be about what your requirements are.

You can build your own (which is typically what I do), or you can use Role-based authorization which Flask-User supports.

You can read more on how this works here.

Make sure you view their example app to get an idea of how to put it all together.

If you have your own custom permissions, which will be based on user id. Then you can follow the same concept, but handle it based on user id vs roles. Perhaps even store the permission levels in the user object (is_admin, is_general_user, etc.) such as something like this (pseudo code):

class User:
   is_admin = false
   is_read_only = false

   def __init__(**kwargs):
       # handle kwargs to set permissions

Then you can access your User variables after defining the user in some inherited base factory or something (pseudo code):

u = User(**my_permissions)

if(u.is_admin):
    # do something

Upvotes: 0

Related Questions