-
Notifications
You must be signed in to change notification settings - Fork 14.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: On window focus, redirect to login if the user has been logged out #18773
Changes from 3 commits
fe68c12
0ff9e56
d99a5c0
40c40ed
f86de51
1be3e0c
e17686b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
/** | ||
* Licensed to the Apache Software Foundation (ASF) under one | ||
* or more contributor license agreements. See the NOTICE file | ||
* distributed with this work for additional information | ||
* regarding copyright ownership. The ASF licenses this file | ||
* to you under the Apache License, Version 2.0 (the | ||
* "License"); you may not use this file except in compliance | ||
* with the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, | ||
* software distributed under the License is distributed on an | ||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
* KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations | ||
* under the License. | ||
*/ | ||
import React from 'react'; | ||
import { fireEvent, waitFor } from '@testing-library/dom'; | ||
import { render } from '@testing-library/react'; | ||
import fetchMock from 'fetch-mock'; | ||
|
||
jest.useFakeTimers(); | ||
|
||
import { useWindowActivatedAuthCheck } from './useWindowActivatedAuthCheck'; | ||
|
||
const HookTester = () => { | ||
useWindowActivatedAuthCheck(); | ||
return <>hook tester</>; | ||
}; | ||
|
||
describe('useWindowActivatedAuthCheck', () => { | ||
beforeEach(() => { | ||
// jsdom doesn't support window location, so just gonna fake it here real simple-like | ||
Object.defineProperty(window, 'location', { | ||
value: { | ||
href: 'http://example.com/fake-test-page', | ||
pathname: '/fake-test-page', | ||
search: '?foo=bar', | ||
}, | ||
writable: true, | ||
}); | ||
}); | ||
|
||
afterEach(() => { | ||
fetchMock.restore(); | ||
}); | ||
|
||
it('redirects when the user tabs back after logging out elsewhere', async () => { | ||
fetchMock.get('glob:*/api/v1/me/', { status: 401 }); | ||
|
||
render(<HookTester />); | ||
|
||
fireEvent(document, new Event('visibilitychange')); | ||
|
||
await waitFor(() => { | ||
expect(window.location.href).toEqual( | ||
'/login?next=/fake-test-page?foo=bar', | ||
); | ||
}); | ||
}); | ||
|
||
it('does not redirect if the user is still logged in', async () => { | ||
fetchMock.get('glob:*/api/v1/me/', { | ||
status: 200, | ||
json: { username: 'test_user' }, | ||
}); | ||
|
||
render(<HookTester />); | ||
|
||
fireEvent(document, new Event('visibilitychange')); | ||
|
||
await jest.runAllTimers(); | ||
|
||
expect(window.location.href).toEqual('http://example.com/fake-test-page'); | ||
}); | ||
}); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
/** | ||
* Licensed to the Apache Software Foundation (ASF) under one | ||
* or more contributor license agreements. See the NOTICE file | ||
* distributed with this work for additional information | ||
* regarding copyright ownership. The ASF licenses this file | ||
* to you under the Apache License, Version 2.0 (the | ||
* "License"); you may not use this file except in compliance | ||
* with the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, | ||
* software distributed under the License is distributed on an | ||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
* KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations | ||
* under the License. | ||
*/ | ||
|
||
import { useEffect } from 'react'; | ||
import { makeApi } from '@superset-ui/core'; | ||
import { User } from 'src/types/bootstrapTypes'; | ||
|
||
const getMe = makeApi<void, User>({ | ||
method: 'GET', | ||
endpoint: '/api/v1/me/', | ||
}); | ||
|
||
/** | ||
* When the window becomes visible, checks for the current auth state. | ||
* If we get a 401, we are no longer logged in and the SupersetClient will redirect us. | ||
* This ensures that if you log out in browser tab A, and click to tab B, | ||
* tab B will also display as logged out. | ||
*/ | ||
export function useWindowActivatedAuthCheck() { | ||
useEffect(() => { | ||
const listener = () => { | ||
// we only care about the tab becoming visible, not vice versa | ||
if (document.visibilityState !== 'visible') return; | ||
|
||
getMe().catch(() => { | ||
// ignore error, SupersetClient will redirect to login on a 401 | ||
}); | ||
}; | ||
|
||
document.addEventListener('visibilitychange', listener); | ||
|
||
return () => { | ||
document.removeEventListener('visibilitychange', listener); | ||
}; | ||
}, []); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
# Licensed to the Apache Software Foundation (ASF) under one | ||
# or more contributor license agreements. See the NOTICE file | ||
# distributed with this work for additional information | ||
# regarding copyright ownership. The ASF licenses this file | ||
# to you under the Apache License, Version 2.0 (the | ||
# "License"); you may not use this file except in compliance | ||
# with the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, | ||
# software distributed under the License is distributed on an | ||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
# KIND, either express or implied. See the License for the | ||
# specific language governing permissions and limitations | ||
# under the License. | ||
from flask import g, Response | ||
from flask_appbuilder.api import BaseApi, expose, safe | ||
|
||
from .schemas import UserResponseSchema | ||
|
||
user_response_schema = UserResponseSchema() | ||
|
||
|
||
class CurrentUserRestApi(BaseApi): | ||
""" An api to get information about the current user """ | ||
|
||
resource_name = "me" | ||
openapi_spec_tag = "Current User" | ||
openapi_spec_component_schemas = (UserResponseSchema,) | ||
|
||
@expose("/", methods=["GET"]) | ||
@safe | ||
def me(self) -> Response: | ||
"""Get the user object corresponding to the agent making the request | ||
--- | ||
get: | ||
description: >- | ||
Returns the user object corresponding to the agent making the request, | ||
or returns a 401 error if the user is unauthenticated. | ||
responses: | ||
200: | ||
description: The current user | ||
content: | ||
application/json: | ||
schema: | ||
type: object | ||
properties: | ||
result: | ||
$ref: '#/components/schemas/UserResponseSchema' | ||
401: | ||
$ref: '#/components/responses/401' | ||
""" | ||
if g.user is None or g.user.is_anonymous: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am wondering if returning 401 for anonymous users won't effectively make read-only access impossible for them? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh ok I see what you are doing in the frontend to avoid this being requested for anon users There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This endpoint is only called if the user |
||
return self.response_401() | ||
return self.response(200, result=user_response_schema.dump(g.user)) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# Licensed to the Apache Software Foundation (ASF) under one | ||
# or more contributor license agreements. See the NOTICE file | ||
# distributed with this work for additional information | ||
# regarding copyright ownership. The ASF licenses this file | ||
# to you under the Apache License, Version 2.0 (the | ||
# "License"); you may not use this file except in compliance | ||
# with the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, | ||
# software distributed under the License is distributed on an | ||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
# KIND, either express or implied. See the License for the | ||
# specific language governing permissions and limitations | ||
# under the License. | ||
from marshmallow import Schema | ||
from marshmallow.fields import Boolean, Integer, String | ||
|
||
|
||
class UserResponseSchema(Schema): | ||
id = Integer() | ||
username = String() | ||
email = String() | ||
first_name = String() | ||
last_name = String() | ||
is_active = Boolean() | ||
is_anonymous = Boolean() |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -81,6 +81,7 @@ def bootstrap_user_data(user: User, include_perms: bool = False) -> Dict[str, An | |
"lastName": user.last_name, | ||
"userId": user.id, | ||
"isActive": user.is_active, | ||
"isAnonymous": user.is_anonymous, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added |
||
"createdOn": user.created_on.isoformat(), | ||
"email": user.email, | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
# Licensed to the Apache Software Foundation (ASF) under one | ||
# or more contributor license agreements. See the NOTICE file | ||
# distributed with this work for additional information | ||
# regarding copyright ownership. The ASF licenses this file | ||
# to you under the Apache License, Version 2.0 (the | ||
# "License"); you may not use this file except in compliance | ||
# with the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, | ||
# software distributed under the License is distributed on an | ||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
# KIND, either express or implied. See the License for the | ||
# specific language governing permissions and limitations | ||
# under the License. | ||
"""Unit tests for Superset""" | ||
import json | ||
from unittest.mock import patch | ||
|
||
from superset import security_manager | ||
from tests.integration_tests.base_tests import SupersetTestCase | ||
|
||
meUri = "/api/v1/me/" | ||
|
||
|
||
class TestCurrentUserApi(SupersetTestCase): | ||
def test_get_me_logged_in(self): | ||
self.login(username="admin") | ||
|
||
rv = self.client.get(meUri) | ||
|
||
self.assertEqual(200, rv.status_code) | ||
response = json.loads(rv.data.decode("utf-8")) | ||
self.assertEqual("admin", response["result"]["username"]) | ||
self.assertEqual(True, response["result"]["is_active"]) | ||
self.assertEqual(False, response["result"]["is_anonymous"]) | ||
|
||
def test_get_me_unauthorized(self): | ||
self.logout() | ||
rv = self.client.get(meUri) | ||
self.assertEqual(401, rv.status_code) | ||
|
||
@patch("superset.security.manager.g") | ||
def test_get_me_anonymous(self, mock_g): | ||
mock_g.user = security_manager.get_anonymous_user | ||
rv = self.client.get(meUri) | ||
self.assertEqual(401, rv.status_code) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I didn't want to add a permission for this API, because it should be callable by any user. @dpgaspar this is safe, yeah?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this getMe API is great, as it may have plenty o' uses (e.g. when we revisit the Profile design). But just to say it "out loud" we could also implement a GET /time API or something as a lightweight, security-irrelevant API, if performance or security ever become a factor here.