Recommended to check: session id request


Lets continue to work with the code example from the API Creation article:

from exthttp import create_app, BaseHandler
from exthttp import http
 
app = create_app("ExampleApp")
 
 
@app.route("hello")
class HelloWorldHandler(BaseHandler):
    def get(self, request, *args, **kwargs):
        return http.JsonResponse({"message": "Hello World"})

By default your new module will not request any authorization.

You can restrict access to your module if you will use True at app.need_auth parameter. Also you can enable\disable authentication for some specific get/post request. To do this, define need_auth for required method.
At the example below, we disable main authentication in module, but we will set it for the POST method:

from exthttp import create_app, BaseHandler
from exthttp import http
 
app = create_app("ExampleApp")
app.need_auth = False
 
 
@app.route("hello")
class HelloWorldHandler(BaseHandler):
    def get(self, request, *args, **kwargs):
        return http.JsonResponse({"message": "Hello World"})

    def post(self, request, *args, **kwargs):
        return http.JsonResponse({"message": "Private Method"})
    
    post.need_auth = True

Please note that this record do not check user permissions. This record will check only authentication fact.

User object, on whose behalf request sent, stored at request.user with next attributes:

  • is_superuser - True if user is Admin.
  • has_view_rights - True if user has view rights.
  • has_modify_rights - True if user has control rights.
  • has_setup_rights - True if user has rights to change parameters.

At the example below, you will find a script code where we allow only POST request only for users with control rights:

from exthttp import create_app, BaseHandler
from exthttp import http
 
app = create_app("ExampleApp")
app.need_auth = False
 
 
@app.route("hello")
class HelloWorldHandler(BaseHandler):
    def get(self, request, *args, **kwargs):
        return http.JsonResponse({"message": "Hello World"})

    def post(self, request, *args, **kwargs):
        if request.user.has_modify_rights:
            return http.JsonResponse({"message": "Private Method"})
        return http.JsonResponse({"error": "Forbidden"}, status=403)
    
    post.need_auth = True


  • Нет меток