def oauth_aware(self, method):
"""Decorator that sets up for OAuth 2.0 dance, but doesn't do it.
Does all the setup for the OAuth dance, but doesn't initiate it.
This decorator is useful if you want to create a page that knows
whether or not the user has granted access to this application.
From within a method decorated with @oauth_aware the has_credentials()
and authorize_url() methods can be called.
Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.
"""
def setup_oauth(request_handler, *args, **kwargs):
if self._in_error:
self._display_error_message(request_handler)
return
user = users.get_current_user()
# Don't use @login_decorator as this could be used in a
# POST request.
if not user:
request_handler.redirect(users.create_login_url(
request_handler.request.uri))
return
self._create_flow(request_handler)
self.flow.params['state'] = _build_state_value(request_handler,
user)
self.credentials = self._storage_class(
self._credentials_class, None,
self._credentials_property_name, user=user).get()
try:
resp = method(request_handler, *args, **kwargs)
finally:
self.credentials = None
return resp
return setup_oauth
python类get_current_user()的实例源码
def context_setup():
"""
Sets up context for the request
"""
g.user = users.get_current_user()
g.domain = address.parse(g.user.email()).hostname
g.stats = Stats(g.domain)
g.base_report_query = EmailReport.domain_query(g.domain)
def context_setup():
"""
Sets up context for the request
"""
g.user = users.get_current_user()
g.domain = address.parse(g.user.email()).hostname
g.base_report_query = EmailReport.domain_query(g.domain)
def context_setup():
"""
Sets up context for the request
"""
g.user = users.get_current_user()
g.domain = address.parse(g.user.email()).hostname
def oauth_required(self, method):
"""Decorator that starts the OAuth 2.0 dance.
Starts the OAuth dance for the logged in user if they haven't already
granted access for this application.
Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.
"""
def check_oauth(request_handler, *args, **kwargs):
if self._in_error:
self._display_error_message(request_handler)
return
user = users.get_current_user()
# Don't use @login_decorator as this could be used in a POST request.
if not user:
request_handler.redirect(users.create_login_url(
request_handler.request.uri))
return
self._create_flow(request_handler)
# Store the request URI in 'state' so we can use it later
self.flow.params['state'] = _build_state_value(request_handler, user)
self.credentials = StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').get()
if not self.has_credentials():
return request_handler.redirect(self.authorize_url())
try:
return method(request_handler, *args, **kwargs)
except AccessTokenRefreshError:
return request_handler.redirect(self.authorize_url())
return check_oauth
def oauth_aware(self, method):
"""Decorator that sets up for OAuth 2.0 dance, but doesn't do it.
Does all the setup for the OAuth dance, but doesn't initiate it.
This decorator is useful if you want to create a page that knows
whether or not the user has granted access to this application.
From within a method decorated with @oauth_aware the has_credentials()
and authorize_url() methods can be called.
Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.
"""
def setup_oauth(request_handler, *args, **kwargs):
if self._in_error:
self._display_error_message(request_handler)
return
user = users.get_current_user()
# Don't use @login_decorator as this could be used in a POST request.
if not user:
request_handler.redirect(users.create_login_url(
request_handler.request.uri))
return
self._create_flow(request_handler)
self.flow.params['state'] = _build_state_value(request_handler, user)
self.credentials = StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').get()
return method(request_handler, *args, **kwargs)
return setup_oauth
def callback_handler(self):
"""RequestHandler for the OAuth 2.0 redirect callback.
Usage:
app = webapp.WSGIApplication([
('/index', MyIndexHandler),
...,
(decorator.callback_path, decorator.callback_handler())
])
Returns:
A webapp.RequestHandler that handles the redirect back from the
server during the OAuth 2.0 dance.
"""
decorator = self
class OAuth2Handler(webapp.RequestHandler):
"""Handler for the redirect_uri of the OAuth 2.0 dance."""
@login_required
def get(self):
error = self.request.get('error')
if error:
errormsg = self.request.get('error_description', error)
self.response.out.write(
'The authorization request failed: %s' % _safe_html(errormsg))
else:
user = users.get_current_user()
decorator._create_flow(self)
credentials = decorator.flow.step2_exchange(self.request.params)
StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').put(credentials)
redirect_uri = _parse_state_value(str(self.request.get('state')),
user)
self.redirect(redirect_uri)
return OAuth2Handler
def get_user(self):
user = users.get_current_user()
if user:
return dict(nickname = user.nickname(),
email = user.email(),
registration_id = user.user_id(),
user_id = user.user_id(),
source = "google account")
def CheckSignIn():
user = users.get_current_user()
if not user:
login_url = users.create_login_url('/')
greeting = '<a href="{}">Sign in</a>'.format(login_url)
return render_template('splash.html', login=login_url)
else:
profile = check_if_user_profile(user.user_id())
return redirect('/predictions')
def CreateUser():
"""Route for checking if user exists."""
profile = check_if_user_profile(users.get_current_user().user_id())
return str(profile)
def GetUserBalanceByAuth():
"""Returns current users balance."""
user_key = ndb.Key('Profile', users.get_current_user().user_id())
profile = user_key.get()
return str(profile.balance)
# TODO(goldhaber): change to GetUserPortfolioByAuth By Prediction ID
def GetUserPortfolioByAuth(prediction_id):
"""Returns current users porfolio by prediction_id."""
user_key = ndb.Key('Profile', users.get_current_user().user_id())
profile = user_key.get()
portfolio = []
if prediction_id:
portfolio = [
i for i in profile.user_ledger if i.prediction_id == prediction_id
]
return portfolio
def GetTradesForPredictionId(prediction_id):
user = users.get_current_user()
trades = Trade.query(ndb.AND(Trade.prediction_id == ndb.Key(urlsafe=prediction_id),
Trade.user_id == ndb.Key('Profile', user.user_id()))).fetch()
return str(trades)
def inject_balance():
user = users.get_current_user()
if not user:
return dict(balance=0)
user_key = ndb.Key('Profile', user.user_id())
profile = user_key.get()
return dict(balance=profile.balance)
def check_if_user_profile(user_id):
"""Check if User has a profile, if not create a Profile."""
profile_query = Profile.query(Profile.user_id == user_id).fetch()
if len(profile_query) > 0:
return True
else:
profile = Profile(
user_id=users.get_current_user().user_id(),
balance=100.00,
user_email=users.get_current_user().email())
profile.key = ndb.Key('Profile', users.get_current_user().user_id())
profile_key = profile.put()
return profile
def login_required(handler_method):
"""A decorator to require that a user be logged in to access a handler.
To use it, decorate your get() method like this::
@login_required
def get(self):
user = users.get_current_user(self)
self.response.out.write('Hello, ' + user.nickname())
We will redirect to a login page if the user is not logged in. We always
redirect to the request URI, and Google Accounts only redirects back as
a GET request, so this should not be used for POSTs.
"""
def check_login(self, *args, **kwargs):
if self.request.method != 'GET':
self.abort(400,
detail='The login_required decorator '
'can only be used for GET requests.')
user = users.get_current_user()
if not user:
return self.redirect(users.create_login_url(self.request.url))
else:
handler_method(self, *args, **kwargs)
return check_login
def admin_required(handler_method):
"""A decorator to require that a user be an admin for this application
to access a handler.
To use it, decorate your get() method like this::
@admin_required
def get(self):
user = users.get_current_user(self)
self.response.out.write('Hello, ' + user.nickname())
We will redirect to a login page if the user is not logged in. We always
redirect to the request URI, and Google Accounts only redirects back as
a GET request, so this should not be used for POSTs.
"""
def check_admin(self, *args, **kwargs):
if self.request.method != 'GET':
self.abort(400,
detail='The admin_required decorator '
'can only be used for GET requests.')
user = users.get_current_user()
if not user:
return self.redirect(users.create_login_url(self.request.url))
elif not users.is_current_user_admin():
self.abort(403)
else:
handler_method(self, *args, **kwargs)
return check_admin
def user_view():
"""
User interface (only shows the token).
:return: An http response with the submitted information.
"""
user = users.get_current_user()
if not user:
return redirect(users.create_login_url("/user"))
email = user.email()
doctors = tesis_bd.Doctor.query(tesis_bd.Doctor.email == email).fetch()
if len(doctors) == 0:
return render_template('error.html', message="User not found in the DB.")
doctor = doctors[0]
name = doctor.name
if not doctor.token:
doctor.token = "%016x" % random.getrandbits(64)
code = doctor.token
doctor.put()
logout_url = users.create_logout_url("/")
return render_template('user_view.html', login=doctor.name, name=name, email=email, code=code,
logout_url=logout_url)
def get(self):
current_user = users.get_current_user()
logout_url= users.create_logout_url('/')
login_url= users.create_login_url('/')
template = jinja_environment.get_template("templates/daytravel.html")
template_vars = {
'current_user': current_user,
'logout_url': logout_url,
'login_url': login_url,
}
self.response.write(template.render(template_vars))
def post(self):
city= self.request.get('city')
current_user = users.get_current_user()
logout_url= users.create_logout_url('/')
login_url= users.create_login_url('/')
self.redirect('/plan?city=' + city)