1

I want to tag all requests with a UUID (if the request doesn't have it in the first place).

I want to store the UUID in the session, so I wrote this middleware.

class MachineIDMiddleware:
    """
    tags requests with machine UUIDs.
    The machine-ID is set in the session.
    """

    MID_KEY = "machine_id"

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print(request.session.get(self.MID_KEY))
        if self.MID_KEY not in request.session:
            # set the machine-ID for the request
            # if it has not been set already (making
            # sure that it is serializable).
            next_id = str(uuid.uuid4())
            request.session[self.MID_KEY] = next_id
        return self.get_response(request)

However, from my client, I noticed that the UUID keeps changing for every request. From my client, I noticed that the sessionid cookie also changed for every request made.

As a result, a new UUID was generated for every request. This is not what I want, though. I want to maintain only one UUID per person (who might be anonymous).

How can I achieve this? Thanks a lot!

EDIT

export const Adapter = axios.create({
  baseURL: baseURL,
  headers: {
    "Content-Type": "application/json"
  }
});

Adapter.interceptors.request.use(
  (request) => {
    const token = tokenSelector(store.getState());
    if (token) {
      request.headers.Authorization = `Token ${token}`;
    }
    return request;
  },
  (error) => {
    return Promise.reject(error);
  }
);

Adapter.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // handle unauthorized errors.
    if (error.response.status === 401) {
      store.dispatch(clearToken());
      history.replace(SLUGS.login);
    }
    // handle internal server errors.
    if (error.response.status === 500) {
      toast.dark("Something went wrong. Please try again later.");
    }
    // handle server ratelimits.
    if (error.response.status === 429) {
      toast.dark("You are being ratelimited.");
    }
    return Promise.reject(error);
  }
);

This is how I send requests from the frontend. I use axios. I checked my cookies in the developer tools panel and couldn't see the sessionid cookie there.

EDIT 2 enter image description here

Chrome devtools shows me the following error and is not setting the sessionid cookie properly. Is this the reason maybe?

** Answer (SOLVED)** setting the following variables in my settings.py file made sure that chrome set the cookies correctly.

# CORS configuration
ALLOWED_HOSTS = ["*"]
CORS_ALLOW_ALL_ORIGINS = True
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CORS_ALLOW_CREDENTIALS = True
SESSION_COOKIE_HTTPONLY = False
Aryan Iyappan
  • 323
  • 1
  • 3
  • 15

1 Answers1

0

Here is your correct __call__ function

def __call__(self, request):
     print(request.session.get("MID_KEY"))
     if "MID_KEY" not in request.session:  
             next_id = str(uuid.uuid4())    
             request.session["MID_KEY"] = next_id.   
     return self.get_response(request)

The key shall be a string (constant) not a variable

Mohamed ElKalioby
  • 1,908
  • 1
  • 12
  • 13
  • I am sorry, but I want the session key to persist. That way, I can keep track of anonymous users. This does not do that. – Aryan Iyappan Jun 06 '21 at 05:37
  • 1
    It will do that as for every session the value of `MID_KEY` will be different but the key is the same and this is the idea behind key/value stores. – Mohamed ElKalioby Jun 06 '21 at 05:50