2

I'm pretty new to development. So, sorry in advance for potentially stupid question:

I'm trying to implement a simple application with 2 micro services:

  1. User Api
  2. TODO Api

I've started implementing auth part and came across something that I don't understand and can't find online.

In User Api I implemented some endpoints and jwt auth. Here is an example of controller. All auth logic is hidden in corresponding decorators @token_required or @admin_token_required

from http import HTTPStatus
from flask_restplus import Namespace, Resource
from app.exceptions import FieldValidationException
from app.v1 import v1_api
from app.v1.main.model.UserModel import User
from app.v1.main.service.UserService import UserService
from utils.decorators import admin_token_required, token_required

ls_user_ns = Namespace("user")
@ls_user_ns.route("/")
class UserList(Resource):
    user_service = UserService()

    @ls_user_ns.marshal_with(
        User.get_user_response_model,
        code=HTTPStatus.OK,
        as_list=True,
        description="Get all users",
        envelope="users",
    )
    @admin_token_required
    def get(self):
        users = self.user_service.get_all_users()
        return users, HTTPStatus.OK

    @ls_user_ns.doc(body=User.create_user_request_model, validate=True)
    @ls_user_ns.marshal_with(
        User.create_user_response_model,
        code=HTTPStatus.CREATED,
        description="Create new user",
    )
    @token_required
    def post(self):
        payload = v1_api.payload
        user, exceptions = self.user_service.create_user(payload)
        if exceptions:
            raise FieldValidationException(exceptions)
        else:
            return user, HTTPStatus.CREATED

I also have another micro service, TODO Api. Here I also want resources to be behind auth. I.e I'd like to use the same @token_required decorator, but from User Api. What is the best way to go around it? All resources that I found online show examples in format: everything in one file or best case scenario, everything split into modules, but within one API. If someone could provide some examples, it would be awesome. Thanks in advance.

1 Answers1

0

To solve this, you'll need to make a decorator token_required

The code for the decorator token_required should look something like:

from functools import wraps
def token_required(controller_function):
    @wraps(controller_function)
    def wrapper_function(*args, **kwargs):
        # Make endpoint in the Auth Service to validate an Auth Token
        # The endpoint will return details such as User's Account ID
        auth_token = request.headers.get('AuthToken', '')
        response = requests.get('mysite.com/validate_auth_token', headers={'AuthToken': auth_token})
        # If the Response Json has an account_id which is not empty, the user is valid
        if response.json().get('account_id'):
            controller_function(account_id, *args, **kwargs)
        else:
            # You can also redirect the user to the login page.
            abort(403, 'Invalid user')

You can also refer to this document for more information on Python Decorators

Ishan Joshi
  • 487
  • 3
  • 7