-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
IA-3516 Adapt the token API to multi-account users
If a user request a token to api/token we should look if that user has a tenant_user for the account corresponding to the app_id in the url, and if it’s the case, send a token for that tenant_user on that account instead of the token for the login user.
- Loading branch information
Showing
3 changed files
with
41 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from django.contrib.auth.models import User | ||
|
||
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer | ||
|
||
from iaso.models import Project | ||
|
||
|
||
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): | ||
def validate(self, attrs): | ||
""" | ||
Override this method to be able to take into account the app_id query param. | ||
If the user is a multi-account user, we return a token for the correct | ||
"account user" (based on the `app_id`) instead of the main user that was | ||
used for logging in. | ||
""" | ||
data = super().validate(attrs) | ||
|
||
if self.user.tenant_users.exists(): | ||
request = self.context.get("request") | ||
if request: | ||
app_id = request.query_params.get("app_id", None) | ||
project = Project.objects.get(app_id=app_id) | ||
|
||
account_user = User.objects.filter( | ||
tenant_user__main_user=self.user, | ||
iaso_profile__account=project.account, | ||
).first() | ||
|
||
refresh = self.get_token(account_user) | ||
|
||
data["refresh"] = str(refresh) | ||
data["access"] = str(refresh.access_token) | ||
|
||
return data |