I am writing an application that will have some HTML content (mapping tables, etc.) as well as a JSON API.
For regular HTML, I use AuthTktAuthenticationPolicy for authentication and ACLAuthorizationPolicy for authorization. Thus, the user is provided with a login form and upon successful login to the auth_tkt cookie. The system is operating normally.
Now I want to replicate a similar system for the JSON API. The problem is that the user will not have to be logged in for API requests. Therefore, for each request, the api_key parameter is api_key . Based on the key, if I find a valid user, I will send back JSON. Otherwsie I am showing page 403.
One way to do it in every view
api_key = request.GET.get('api_key',None) user = FrontEndUsers.User_by_api_key(api_key) if user: #Process view else: return HTTPForbidden
However, there seems to be too much boiler plate to use for each point of view to make exaccty an authentication policy would do. Can I specify a separate authentication policy for JSON routes? Or is there any other way to do this?
EDIT
Secondly, it seems that even with AuthTktAuthenticationPolicy I need to do security.authenticated_userid() in all views (if I need authentication information). I already considered this in a separate function
def get_auth_info(): user_id = security.authenticated_userid() login_info = {} if user_id is not None: login_info['login'] = True login_info['logged_in_user'] = FrontendUsers.get_user_by_id(user_id).name else: login_info['login'] = False return login_info
I can enable the API_key check function call in this function so that none of my views change (I still only call get_auth_info() ), and yet I can check if the correct API key was presented.
I would still like to see if there are other ways to do this or if there is a problem with my current circuit