We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Last Active Organization not set in API
Currently, a user's last active organization is set only in the Django code: https://github.com/getsentry/sentry/blob/master/src/sentry/web/frontend/base.py#L34

This means that last active organization is not set when a user navigates to a view via a front-end route.

As more of Sentry's views are converted to React, we will lose accurate functionality around a user's last active organization.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/sentry/api/bases/organization.py`
Content:
```
1 from __future__ import absolute_import
2 
3 from sentry.api.base import Endpoint, logger
4 from sentry.api.exceptions import ResourceDoesNotExist, SsoRequired, TwoFactorRequired
5 from sentry.api.permissions import ScopedPermission
6 from sentry.app import raven
7 from sentry.auth import access
8 from sentry.auth.superuser import is_active_superuser
9 from sentry.models import (
10     ApiKey, Authenticator, Organization, OrganizationMemberTeam, Project, ProjectTeam, ReleaseProject, Team
11 )
12 from sentry.utils import auth
13 
14 
15 class OrganizationPermission(ScopedPermission):
16     scope_map = {
17         'GET': ['org:read', 'org:write', 'org:admin'],
18         'POST': ['org:write', 'org:admin'],
19         'PUT': ['org:write', 'org:admin'],
20         'DELETE': ['org:admin'],
21     }
22 
23     def is_not_2fa_compliant(self, user, organization):
24         return organization.flags.require_2fa and not Authenticator.objects.user_has_2fa(user)
25 
26     def needs_sso(self, request, organization):
27         # XXX(dcramer): this is very similar to the server-rendered views
28         # logic for checking valid SSO
29         if not request.access.requires_sso:
30             return False
31         if not auth.has_completed_sso(request, organization.id):
32             return True
33         if not request.access.sso_is_valid:
34             return True
35         return False
36 
37     def has_object_permission(self, request, view, organization):
38         if request.user and request.user.is_authenticated() and request.auth:
39             request.access = access.from_request(
40                 request,
41                 organization,
42                 scopes=request.auth.get_scopes(),
43             )
44 
45         elif request.auth:
46             if request.auth.organization_id == organization.id:
47                 request.access = access.from_auth(request.auth)
48             else:
49                 request.access = access.DEFAULT
50 
51         else:
52             request.access = access.from_request(request, organization)
53 
54             if auth.is_user_signed_request(request):
55                 # if the user comes from a signed request
56                 # we let them pass if sso is enabled
57                 logger.info(
58                     'access.signed-sso-passthrough',
59                     extra={
60                         'organization_id': organization.id,
61                         'user_id': request.user.id,
62                     }
63                 )
64             elif request.user.is_authenticated():
65                 # session auth needs to confirm various permissions
66                 if self.needs_sso(request, organization):
67 
68                     logger.info(
69                         'access.must-sso',
70                         extra={
71                             'organization_id': organization.id,
72                             'user_id': request.user.id,
73                         }
74                     )
75 
76                     raise SsoRequired(organization)
77 
78                 if self.is_not_2fa_compliant(
79                         request.user, organization):
80                     logger.info(
81                         'access.not-2fa-compliant',
82                         extra={
83                             'organization_id': organization.id,
84                             'user_id': request.user.id,
85                         }
86                     )
87                     raise TwoFactorRequired()
88 
89         allowed_scopes = set(self.scope_map.get(request.method, []))
90         return any(request.access.has_scope(s) for s in allowed_scopes)
91 
92 
93 # These are based on ProjectReleasePermission
94 # additional checks to limit actions to releases
95 # associated with projects people have access to
96 class OrganizationReleasePermission(OrganizationPermission):
97     scope_map = {
98         'GET': ['project:read', 'project:write', 'project:admin', 'project:releases'],
99         'POST': ['project:write', 'project:admin', 'project:releases'],
100         'PUT': ['project:write', 'project:admin', 'project:releases'],
101         'DELETE': ['project:admin', 'project:releases'],
102     }
103 
104 
105 class OrganizationIntegrationsPermission(OrganizationPermission):
106     scope_map = {
107         'GET': ['org:read', 'org:write', 'org:admin', 'org:integrations'],
108         'POST': ['org:write', 'org:admin', 'org:integrations'],
109         'PUT': ['org:write', 'org:admin', 'org:integrations'],
110         'DELETE': ['org:admin', 'org:integrations'],
111     }
112 
113 
114 class OrganizationAdminPermission(OrganizationPermission):
115     scope_map = {
116         'GET': ['org:admin'],
117         'POST': ['org:admin'],
118         'PUT': ['org:admin'],
119         'DELETE': ['org:admin'],
120     }
121 
122 
123 class OrganizationAuthProviderPermission(OrganizationPermission):
124     scope_map = {
125         'GET': ['org:read'],
126         'POST': ['org:admin'],
127         'PUT': ['org:admin'],
128         'DELETE': ['org:admin'],
129     }
130 
131 
132 class OrganizationEndpoint(Endpoint):
133     permission_classes = (OrganizationPermission, )
134 
135     def convert_args(self, request, organization_slug, *args, **kwargs):
136         try:
137             organization = Organization.objects.get_from_cache(
138                 slug=organization_slug,
139             )
140         except Organization.DoesNotExist:
141             raise ResourceDoesNotExist
142 
143         self.check_object_permissions(request, organization)
144 
145         raven.tags_context({
146             'organization': organization.id,
147         })
148 
149         request._request.organization = organization
150 
151         kwargs['organization'] = organization
152         return (args, kwargs)
153 
154 
155 class OrganizationReleasesBaseEndpoint(OrganizationEndpoint):
156     permission_classes = (OrganizationReleasePermission, )
157 
158     def get_allowed_projects(self, request, organization):
159         has_valid_api_key = False
160         if isinstance(request.auth, ApiKey):
161             if request.auth.organization_id != organization.id:
162                 return []
163             has_valid_api_key = request.auth.has_scope('project:releases') or \
164                 request.auth.has_scope('project:write')
165 
166         if not (has_valid_api_key or request.user.is_authenticated()):
167             return []
168 
169         if has_valid_api_key or is_active_superuser(request) or organization.flags.allow_joinleave:
170             allowed_teams = Team.objects.filter(organization=organization).values_list(
171                 'id', flat=True
172             )
173         else:
174             allowed_teams = OrganizationMemberTeam.objects.filter(
175                 organizationmember__user=request.user,
176                 team__organization_id=organization.id,
177             ).values_list(
178                 'team_id', flat=True
179             )
180 
181         return Project.objects.filter(
182             id__in=ProjectTeam.objects.filter(
183                 team_id__in=allowed_teams,
184             ).values_list('project_id', flat=True)
185         )
186 
187     def has_release_permission(self, request, organization, release):
188         return ReleaseProject.objects.filter(
189             release=release,
190             project__in=self.get_allowed_projects(request, organization),
191         ).exists()
192
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/sentry/api/bases/organization.py b/src/sentry/api/bases/organization.py
--- a/src/sentry/api/bases/organization.py
+++ b/src/sentry/api/bases/organization.py
@@ -145,9 +145,13 @@
         raven.tags_context({
             'organization': organization.id,
         })
-
         request._request.organization = organization
 
+        # Track the 'active' organization when the request came from
+        # a cookie based agent (react app)
+        if request.auth is None and request.user:
+            request.session['activeorg'] = organization.slug
+
         kwargs['organization'] = organization
         return (args, kwargs)

{"golden_diff": "diff --git a/src/sentry/api/bases/organization.py b/src/sentry/api/bases/organization.py\n--- a/src/sentry/api/bases/organization.py\n+++ b/src/sentry/api/bases/organization.py\n@@ -145,9 +145,13 @@\n         raven.tags_context({\n             'organization': organization.id,\n         })\n-\n         request._request.organization = organization\n \n+        # Track the 'active' organization when the request came from\n+        # a cookie based agent (react app)\n+        if request.auth is None and request.user:\n+            request.session['activeorg'] = organization.slug\n+\n         kwargs['organization'] = organization\n         return (args, kwargs)\n", "issue": "Last Active Organization not set in API\nCurrently, a user's last active organization is set only in the Django code: https://github.com/getsentry/sentry/blob/master/src/sentry/web/frontend/base.py#L34\r\n\r\nThis means that last active organization is not set when a user navigates to a view via a front-end route.\r\n\r\nAs more of Sentry's views are converted to React, we will lose accurate functionality around a user's last active organization.\r\n\n", "before_files": [{"content": "from __future__ import absolute_import\n\nfrom sentry.api.base import Endpoint, logger\nfrom sentry.api.exceptions import ResourceDoesNotExist, SsoRequired, TwoFactorRequired\nfrom sentry.api.permissions import ScopedPermission\nfrom sentry.app import raven\nfrom sentry.auth import access\nfrom sentry.auth.superuser import is_active_superuser\nfrom sentry.models import (\n    ApiKey, Authenticator, Organization, OrganizationMemberTeam, Project, ProjectTeam, ReleaseProject, Team\n)\nfrom sentry.utils import auth\n\n\nclass OrganizationPermission(ScopedPermission):\n    scope_map = {\n        'GET': ['org:read', 'org:write', 'org:admin'],\n        'POST': ['org:write', 'org:admin'],\n        'PUT': ['org:write', 'org:admin'],\n        'DELETE': ['org:admin'],\n    }\n\n    def is_not_2fa_compliant(self, user, organization):\n        return organization.flags.require_2fa and not Authenticator.objects.user_has_2fa(user)\n\n    def needs_sso(self, request, organization):\n        # XXX(dcramer): this is very similar to the server-rendered views\n        # logic for checking valid SSO\n        if not request.access.requires_sso:\n            return False\n        if not auth.has_completed_sso(request, organization.id):\n            return True\n        if not request.access.sso_is_valid:\n            return True\n        return False\n\n    def has_object_permission(self, request, view, organization):\n        if request.user and request.user.is_authenticated() and request.auth:\n            request.access = access.from_request(\n                request,\n                organization,\n                scopes=request.auth.get_scopes(),\n            )\n\n        elif request.auth:\n            if request.auth.organization_id == organization.id:\n                request.access = access.from_auth(request.auth)\n            else:\n                request.access = access.DEFAULT\n\n        else:\n            request.access = access.from_request(request, organization)\n\n            if auth.is_user_signed_request(request):\n                # if the user comes from a signed request\n                # we let them pass if sso is enabled\n                logger.info(\n                    'access.signed-sso-passthrough',\n                    extra={\n                        'organization_id': organization.id,\n                        'user_id': request.user.id,\n                    }\n                )\n            elif request.user.is_authenticated():\n                # session auth needs to confirm various permissions\n                if self.needs_sso(request, organization):\n\n                    logger.info(\n                        'access.must-sso',\n                        extra={\n                            'organization_id': organization.id,\n                            'user_id': request.user.id,\n                        }\n                    )\n\n                    raise SsoRequired(organization)\n\n                if self.is_not_2fa_compliant(\n                        request.user, organization):\n                    logger.info(\n                        'access.not-2fa-compliant',\n                        extra={\n                            'organization_id': organization.id,\n                            'user_id': request.user.id,\n                        }\n                    )\n                    raise TwoFactorRequired()\n\n        allowed_scopes = set(self.scope_map.get(request.method, []))\n        return any(request.access.has_scope(s) for s in allowed_scopes)\n\n\n# These are based on ProjectReleasePermission\n# additional checks to limit actions to releases\n# associated with projects people have access to\nclass OrganizationReleasePermission(OrganizationPermission):\n    scope_map = {\n        'GET': ['project:read', 'project:write', 'project:admin', 'project:releases'],\n        'POST': ['project:write', 'project:admin', 'project:releases'],\n        'PUT': ['project:write', 'project:admin', 'project:releases'],\n        'DELETE': ['project:admin', 'project:releases'],\n    }\n\n\nclass OrganizationIntegrationsPermission(OrganizationPermission):\n    scope_map = {\n        'GET': ['org:read', 'org:write', 'org:admin', 'org:integrations'],\n        'POST': ['org:write', 'org:admin', 'org:integrations'],\n        'PUT': ['org:write', 'org:admin', 'org:integrations'],\n        'DELETE': ['org:admin', 'org:integrations'],\n    }\n\n\nclass OrganizationAdminPermission(OrganizationPermission):\n    scope_map = {\n        'GET': ['org:admin'],\n        'POST': ['org:admin'],\n        'PUT': ['org:admin'],\n        'DELETE': ['org:admin'],\n    }\n\n\nclass OrganizationAuthProviderPermission(OrganizationPermission):\n    scope_map = {\n        'GET': ['org:read'],\n        'POST': ['org:admin'],\n        'PUT': ['org:admin'],\n        'DELETE': ['org:admin'],\n    }\n\n\nclass OrganizationEndpoint(Endpoint):\n    permission_classes = (OrganizationPermission, )\n\n    def convert_args(self, request, organization_slug, *args, **kwargs):\n        try:\n            organization = Organization.objects.get_from_cache(\n                slug=organization_slug,\n            )\n        except Organization.DoesNotExist:\n            raise ResourceDoesNotExist\n\n        self.check_object_permissions(request, organization)\n\n        raven.tags_context({\n            'organization': organization.id,\n        })\n\n        request._request.organization = organization\n\n        kwargs['organization'] = organization\n        return (args, kwargs)\n\n\nclass OrganizationReleasesBaseEndpoint(OrganizationEndpoint):\n    permission_classes = (OrganizationReleasePermission, )\n\n    def get_allowed_projects(self, request, organization):\n        has_valid_api_key = False\n        if isinstance(request.auth, ApiKey):\n            if request.auth.organization_id != organization.id:\n                return []\n            has_valid_api_key = request.auth.has_scope('project:releases') or \\\n                request.auth.has_scope('project:write')\n\n        if not (has_valid_api_key or request.user.is_authenticated()):\n            return []\n\n        if has_valid_api_key or is_active_superuser(request) or organization.flags.allow_joinleave:\n            allowed_teams = Team.objects.filter(organization=organization).values_list(\n                'id', flat=True\n            )\n        else:\n            allowed_teams = OrganizationMemberTeam.objects.filter(\n                organizationmember__user=request.user,\n                team__organization_id=organization.id,\n            ).values_list(\n                'team_id', flat=True\n            )\n\n        return Project.objects.filter(\n            id__in=ProjectTeam.objects.filter(\n                team_id__in=allowed_teams,\n            ).values_list('project_id', flat=True)\n        )\n\n    def has_release_permission(self, request, organization, release):\n        return ReleaseProject.objects.filter(\n            release=release,\n            project__in=self.get_allowed_projects(request, organization),\n        ).exists()\n", "path": "src/sentry/api/bases/organization.py"}], "after_files": [{"content": "from __future__ import absolute_import\n\nfrom sentry.api.base import Endpoint, logger\nfrom sentry.api.exceptions import ResourceDoesNotExist, SsoRequired, TwoFactorRequired\nfrom sentry.api.permissions import ScopedPermission\nfrom sentry.app import raven\nfrom sentry.auth import access\nfrom sentry.auth.superuser import is_active_superuser\nfrom sentry.models import (\n    ApiKey, Authenticator, Organization, OrganizationMemberTeam, Project, ProjectTeam, ReleaseProject, Team\n)\nfrom sentry.utils import auth\n\n\nclass OrganizationPermission(ScopedPermission):\n    scope_map = {\n        'GET': ['org:read', 'org:write', 'org:admin'],\n        'POST': ['org:write', 'org:admin'],\n        'PUT': ['org:write', 'org:admin'],\n        'DELETE': ['org:admin'],\n    }\n\n    def is_not_2fa_compliant(self, user, organization):\n        return organization.flags.require_2fa and not Authenticator.objects.user_has_2fa(user)\n\n    def needs_sso(self, request, organization):\n        # XXX(dcramer): this is very similar to the server-rendered views\n        # logic for checking valid SSO\n        if not request.access.requires_sso:\n            return False\n        if not auth.has_completed_sso(request, organization.id):\n            return True\n        if not request.access.sso_is_valid:\n            return True\n        return False\n\n    def has_object_permission(self, request, view, organization):\n        if request.user and request.user.is_authenticated() and request.auth:\n            request.access = access.from_request(\n                request,\n                organization,\n                scopes=request.auth.get_scopes(),\n            )\n\n        elif request.auth:\n            if request.auth.organization_id == organization.id:\n                request.access = access.from_auth(request.auth)\n            else:\n                request.access = access.DEFAULT\n\n        else:\n            request.access = access.from_request(request, organization)\n\n            if auth.is_user_signed_request(request):\n                # if the user comes from a signed request\n                # we let them pass if sso is enabled\n                logger.info(\n                    'access.signed-sso-passthrough',\n                    extra={\n                        'organization_id': organization.id,\n                        'user_id': request.user.id,\n                    }\n                )\n            elif request.user.is_authenticated():\n                # session auth needs to confirm various permissions\n                if self.needs_sso(request, organization):\n\n                    logger.info(\n                        'access.must-sso',\n                        extra={\n                            'organization_id': organization.id,\n                            'user_id': request.user.id,\n                        }\n                    )\n\n                    raise SsoRequired(organization)\n\n                if self.is_not_2fa_compliant(\n                        request.user, organization):\n                    logger.info(\n                        'access.not-2fa-compliant',\n                        extra={\n                            'organization_id': organization.id,\n                            'user_id': request.user.id,\n                        }\n                    )\n                    raise TwoFactorRequired()\n\n        allowed_scopes = set(self.scope_map.get(request.method, []))\n        return any(request.access.has_scope(s) for s in allowed_scopes)\n\n\n# These are based on ProjectReleasePermission\n# additional checks to limit actions to releases\n# associated with projects people have access to\nclass OrganizationReleasePermission(OrganizationPermission):\n    scope_map = {\n        'GET': ['project:read', 'project:write', 'project:admin', 'project:releases'],\n        'POST': ['project:write', 'project:admin', 'project:releases'],\n        'PUT': ['project:write', 'project:admin', 'project:releases'],\n        'DELETE': ['project:admin', 'project:releases'],\n    }\n\n\nclass OrganizationIntegrationsPermission(OrganizationPermission):\n    scope_map = {\n        'GET': ['org:read', 'org:write', 'org:admin', 'org:integrations'],\n        'POST': ['org:write', 'org:admin', 'org:integrations'],\n        'PUT': ['org:write', 'org:admin', 'org:integrations'],\n        'DELETE': ['org:admin', 'org:integrations'],\n    }\n\n\nclass OrganizationAdminPermission(OrganizationPermission):\n    scope_map = {\n        'GET': ['org:admin'],\n        'POST': ['org:admin'],\n        'PUT': ['org:admin'],\n        'DELETE': ['org:admin'],\n    }\n\n\nclass OrganizationAuthProviderPermission(OrganizationPermission):\n    scope_map = {\n        'GET': ['org:read'],\n        'POST': ['org:admin'],\n        'PUT': ['org:admin'],\n        'DELETE': ['org:admin'],\n    }\n\n\nclass OrganizationEndpoint(Endpoint):\n    permission_classes = (OrganizationPermission, )\n\n    def convert_args(self, request, organization_slug, *args, **kwargs):\n        try:\n            organization = Organization.objects.get_from_cache(\n                slug=organization_slug,\n            )\n        except Organization.DoesNotExist:\n            raise ResourceDoesNotExist\n\n        self.check_object_permissions(request, organization)\n\n        raven.tags_context({\n            'organization': organization.id,\n        })\n        request._request.organization = organization\n\n        # Track the 'active' organization when the request came from\n        # a cookie based agent (react app)\n        if request.auth is None and request.user:\n            request.session['activeorg'] = organization.slug\n\n        kwargs['organization'] = organization\n        return (args, kwargs)\n\n\nclass OrganizationReleasesBaseEndpoint(OrganizationEndpoint):\n    permission_classes = (OrganizationReleasePermission, )\n\n    def get_allowed_projects(self, request, organization):\n        has_valid_api_key = False\n        if isinstance(request.auth, ApiKey):\n            if request.auth.organization_id != organization.id:\n                return []\n            has_valid_api_key = request.auth.has_scope('project:releases') or \\\n                request.auth.has_scope('project:write')\n\n        if not (has_valid_api_key or request.user.is_authenticated()):\n            return []\n\n        if has_valid_api_key or is_active_superuser(request) or organization.flags.allow_joinleave:\n            allowed_teams = Team.objects.filter(organization=organization).values_list(\n                'id', flat=True\n            )\n        else:\n            allowed_teams = OrganizationMemberTeam.objects.filter(\n                organizationmember__user=request.user,\n                team__organization_id=organization.id,\n            ).values_list(\n                'team_id', flat=True\n            )\n\n        return Project.objects.filter(\n            id__in=ProjectTeam.objects.filter(\n                team_id__in=allowed_teams,\n            ).values_list('project_id', flat=True)\n        )\n\n    def has_release_permission(self, request, organization, release):\n        return ReleaseProject.objects.filter(\n            release=release,\n            project__in=self.get_allowed_projects(request, organization),\n        ).exists()\n", "path": "src/sentry/api/bases/organization.py"}]}