Fix tests as suggested by shivamag00. (#1309)

This commit is contained in:
Jason Robbins 2021-05-06 17:29:03 -07:00 коммит произвёл GitHub
Родитель 8fbebb7989
Коммит 248c2c13fd
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
10 изменённых файлов: 50 добавлений и 45 удалений

Просмотреть файл

@ -24,9 +24,7 @@ from flask import session
from framework import basehandlers
# from framework import permissions
# from framework import ramcache
# from internals import models
import settings
class LoginAPI(basehandlers.APIHandler):
"""Create a session using the id_token generated by Google Sign-In."""
@ -36,8 +34,9 @@ class LoginAPI(basehandlers.APIHandler):
message = "Unable to Authenticate"
try:
CLIENT_ID = '77756740465-e5r4o15qg4hkdfiucjpl231o79k3ipjv.apps.googleusercontent.com'
idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID)
idinfo = id_token.verify_oauth2_token(
token, requests.Request(),
settings.GOOGLE_SIGN_IN_CLIENT_ID)
# userid = idinfo['sub']
# email = idinfo['email']
session["id_token"] = token
@ -48,4 +47,3 @@ class LoginAPI(basehandlers.APIHandler):
pass
return {'message': message}

Просмотреть файл

@ -77,13 +77,12 @@ class BaseHandler(flask.views.MethodView):
def get_current_user(self, required=False):
# TODO(jrobbins): oauth support
current_user = None
if self.request.method == 'POST':
current_user = None
if not settings.UNIT_TEST_MODE and self.request.method == 'POST':
current_user = users.get_current_user() or gae_users.get_current_user()
else:
current_user = users.get_current_user()
if required and not current_user:
self.abort(403, msg='User must be signed in')
return current_user
@ -291,6 +290,7 @@ class FlaskHandler(BaseHandler):
common_data = {
'prod': settings.PROD,
'APP_TITLE': settings.APP_TITLE,
'google_sign_in_client_id': settings.GOOGLE_SIGN_IN_CLIENT_ID,
'current_path': current_path,
'TEMPLATE_CACHE_TIME': settings.TEMPLATE_CACHE_TIME,
'banner_message': settings.BANNER_MESSAGE,
@ -300,8 +300,6 @@ class FlaskHandler(BaseHandler):
user = self.get_current_user()
if user:
user_pref = models.UserPref.get_signed_in_user_pref()
common_data['login'] = (
'Sign out', "SignOut")
common_data['user'] = {
'can_create_feature': permissions.can_create_feature(user),
'can_edit': permissions.can_edit_any_feature(user),
@ -313,8 +311,6 @@ class FlaskHandler(BaseHandler):
common_data['xsrf_token_expires'] = xsrf.token_expires_sec()
else:
common_data['user'] = None
common_data['login'] = (
'Sign in', "Sign In")
common_data['xsrf_token'] = xsrf.generate_token(None)
common_data['xsrf_token_expires'] = 0
return common_data

Просмотреть файл

@ -28,6 +28,7 @@ import werkzeug.exceptions # Flask HTTP stuff.
from framework import users
from framework import basehandlers
from framework import users
from framework import xsrf
from internals import models
import settings
@ -490,9 +491,6 @@ class FlaskHandlerTests(unittest.TestCase):
self.assertIn('prod', actual)
self.assertIsNone(actual['user'])
self.assertEqual('Sign in', actual['login'][0])
self.assertIn('/Login', actual['login'][1])
self.assertIn('/test/path', actual['login'][1])
def test_get_common_data__signed_in(self):
"""When user is signed in, offer sign out link."""
@ -502,9 +500,6 @@ class FlaskHandlerTests(unittest.TestCase):
self.assertIn('prod', actual)
self.assertIsNotNone(actual['user'])
self.assertEqual('Sign out', actual['login'][0])
self.assertIn('/Logout', actual['login'][1])
self.assertIn('/test/path', actual['login'][1])
def test_render(self):
"""We can render a simple template to a string."""
@ -602,9 +597,11 @@ class FlaskHandlerTests(unittest.TestCase):
self.handler.require_task_header()
@mock.patch('settings.UNIT_TEST_MODE', False)
def test_require_xsrf_token__normal(self):
@mock.patch('framework.users.get_current_user')
def test_require_xsrf_token__normal(self, mock_get_user):
"""We accept a POST with a valid token."""
testing_config.sign_in('user1@example.com', 111)
mock_get_user.return_value = users.User(email='user1@example.com')
form_data = {'token': xsrf.generate_token('user1@example.com')}
with test_app.test_request_context('/test', data=form_data):
self.handler.require_xsrf_token()

Просмотреть файл

@ -1,7 +1,9 @@
import sys
import os
from flask import session
from google.oauth2 import id_token
from google.auth.transport import requests
import settings
class User(object):
"""Provides the email address, nickname, and ID for a user.
@ -15,7 +17,7 @@ class User(object):
`federated_identity` and `federated_provider` are decommissioned and should
not be used.
This class is based on google.appengine.api.users.User class
This class is based on google.appengine.api.users.User class
"""
@ -170,30 +172,37 @@ class User(object):
`True` if the user is an administrator; all other user types return `False`.
"""
# This environment variable was set by GAE based on a GAE session cookie.
# This environment variable was set by GAE based on a GAE session cookie.
# With Google Sign-In, it will probably never be present. Hence, currently is always False
# TODO (jrobbins): Implement this method
# TODO (jrobbins): Implement this method
return (os.environ.get('USER_IS_ADMIN', '0')) == '1'
def get_current_user():
if settings.UNIT_TEST_MODE:
if os.environ['USER_EMAIL']!= '':
current_user = User(
email=os.environ['USER_EMAIL'],
_user_id=os.environ['USER_ID'])
else:
current_user = None
return current_user
token = session.get('id_token')
current_user = None
if token:
try:
CLIENT_ID = '77756740465-e5r4o15qg4hkdfiucjpl231o79k3ipjv.apps.googleusercontent.com'
idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID)
idinfo = id_token.verify_oauth2_token(
token, requests.Request(), settings.GOOGLE_SIGN_IN_CLIENT_ID)
current_user = User(email=idinfo['email'], _user_id=idinfo['sub'])
except ValueError:
# Remove the id_token from session if it is invalid or expired
session.clear()
current_user = None
pass
return current_user
def is_current_user_admin():
return False
return False

Просмотреть файл

@ -56,6 +56,10 @@ else:
SITE_URL = 'http://%s.appspot.com/' % APP_ID
CLOUD_TASKS_REGION = 'us-central1'
GOOGLE_SIGN_IN_CLIENT_ID = (
'914217904764-enfcea61q4hqe7ak8kkuteglrbhk8el1.'
'apps.googleusercontent.com')
if UNIT_TEST_MODE:
APP_TITLE = 'Local testing'
SITE_URL = 'http://127.0.0.1:8888/'

Просмотреть файл

@ -29,7 +29,7 @@ limitations under the License.
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="google-signin-client_id" content="77756740465-e5r4o15qg4hkdfiucjpl231o79k3ipjv.apps.googleusercontent.com">
<meta name="google-signin-client_id" content="{{google_sign_in_client_id}}">
<link rel="apple-touch-icon" href="/static/img/crstatus_128.png">
<link rel="apple-touch-icon-precomposed" href="/static/img/crstatus_128.png">
@ -58,11 +58,11 @@ limitations under the License.
</style>
{% block css %}{% endblock %}
{# Google Platform Library for OAuth #}
<script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id_token = googleUser.getAuthResponse().id_token;
@ -80,9 +80,9 @@ limitations under the License.
};
let data = JSON.stringify({ "id_token": id_token})
xhr.send(data);
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
@ -107,16 +107,16 @@ limitations under the License.
});
}
function getQueryStringValue (key) {
return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
function getQueryStringValue (key) {
return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
if (getQueryStringValue("loginStatus") == 'False') {
alert('Please log in.')
}
}
</script>
{# Loaded immediately because it is used by JS code on the page. #}
@ -183,7 +183,7 @@ limitations under the License.
{% block js %}{% endblock %}
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-179341418-1"></script>
<script>
(function() {
'use strict';

Просмотреть файл

@ -32,7 +32,8 @@
</span>
{% else %}
<span class="tooltip" title="Sign in to get email notifications for updates">
<a href="{{login.1}}" data-tooltip>
{# TODO(jrobbins): redo to use Google Sign-in #}
<a href="#" data-tooltip>
<iron-icon icon="chromestatus:star-border"
class="pushicon"></iron-icon>
</a>

Просмотреть файл

@ -52,7 +52,8 @@
{% block content %}
<chromedash-featurelist
{% if user %}signedin{% endif %}
loginurl="{{login.1}}"
{# TODO(jrobbins): Fix to work with Google Sign-In #}
loginurl="#"
{% if user.can_edit %}canedit{% endif %}
></chromedash-featurelist>
{% endblock %}

Просмотреть файл

@ -30,13 +30,11 @@
</a>
<ul>
<li><a href="/settings">Settings</a></li>
<!-- <li><a href="{{login.1}}">{{login.0}}</a></li> -->
<li><a href="#" onclick="signOut()">Sign out</a></li>
</ul>
</div>
{% else %}
<!-- <a href="{{login.1}}">{{login.0}}</a> -->
<li><div class="g-signin2" data-onsuccess="onSignIn"></div></li>
{% endif %}

Просмотреть файл

@ -22,7 +22,8 @@
<section id="releases-section">
<chromedash-schedule
{% if user %}signedin{% endif %}
loginurl="{{login.1}}"
{# TODO(jrobbins): Fix to work with google sign-in #}
loginurl="#"
></chromedash-schedule>
</section>
{% endblock %}