Hello everyone, so we are trying to make a structure that login is verified on user’s role. Roles are assigned manually in dashboard (no problem because this is highly secured website, this is the correct way.)
So, as testing, we assigned a role as ‘user’. Now my code is structured as below.
def get_user_roles(request, user_id):
# Set your Auth0 domain
auth0_domain = settings.SOCIAL_AUTH_AUTH0_DOMAIN
mgmt_api_access_token = settings.AUTH0_MGMT_API_ACCESS_TOKEN
# Initialize the HTTPS connection
conn = http.client.HTTPSConnection(auth0_domain)
headers = {'authorization': f"Bearer {mgmt_api_access_token}"}
try:
# Request to fetch user roles
conn.request("GET", f"/api/v2/users/{user_id}/roles", headers=headers)
res = conn.getresponse()
data = res.read()
# Decode and extract roles from the response
roles_data = json.loads(data.decode("utf-8"))
roles = [role['name'] for role in roles_data] # Assuming roles are in the 'name' field
return roles
except Exception as e:
# Handle exceptions (log or raise as needed)
print(f"Error fetching roles from Auth0: {e}")
return []
def login(request):
return oauth.auth0.authorize_redirect(
request, request.build_absolute_uri(reverse(“callback”))
)
def callback(request):
token = oauth.auth0.authorize_access_token(request)
id_token = token.get(‘id_token’)
access_token = token.get(‘access_token’)
jwk_set = oauth.auth0.fetch_jwk_set()
user_info = jwt.decode(id_token, jwk_set)
user_id = user_info.get(‘sub’)
user_roles_or_permissions = get_user_roles(user_id, access_token)
required_permission = ‘user’
if required_permission not in user_roles_or_permissions:
messages.error(request, ‘You must verify your email to log in.’)
return redirect('http://localhost:3000/callback') ## Conditions are identified in index.html
request.session['session_id'] = {
'id_token': token.get('id_token'),
# other user information as needed
}
return redirect('http://localhost:3000/callback?token=' + id_token)
However, if required_permission not in user_roles_or_permissions: is constantly true, so nobody can access the website right now. What did I wrong? I checked all the docs but could not get help. Please can you help me to fix this code? What is wrong?