Middleware

Middleware are pieces of code that are executed every time a request is made to the app. It is used to do pre-validations and, in our case, add global values ​​as props to each frontend render. The accounts middleware is:

AuthPropsMiddleware

Provides the frontend with the user’s authentication information, if authenticated, and other information necessary for the account module.

    class AuthPropsMiddleware:
      def __init__(self, get_response):
          self.get_response = get_response
          # One-time configuration and initialization.

      def __call__(self, request):

          if request.user.is_authenticated:
              try:
                  email_address = models.EmailAddress.objects.get(
                      user=request.user, primary=True
                  )
              except models.EmailAddress.DoesNotExist:
                  verified = ""
              else:
                  verified = email_address.verified

              share(
                  request,
                  "auth",
                  {
                      "user": {
                          "id": request.user.id,
                          "firstName": request.user.first_name,
                          "lastName": request.user.last_name,
                          "email": request.user.email,
                          "isBusiness": request.user.is_business,
                          "groups": [
                              group["name"]
                              for group in request.user.groups.all().values("name")
                          ],
                      },
                      "emailAddress": {
                          "verified": verified,
                          "emailMethod": app_settings.EMAIL_VERIFICATION,
                      },
                  },
              )
          else:
              share(
                  request,
                  "auth",
                  {
                      "user": {
                          "id": "",
                          "firstName": "",
                          "lastName": "",
                          "email": "",
                          "isBusiness": False,
                          "groups": [],
                      },
                      "emailAddress": {
                          "verified": "",
                          "emailMethod": app_settings.EMAIL_VERIFICATION,
                      },
                  },
              )
          response = self.get_response(request)
          return response