def testGetCurrentUserOauth(self): self.mox.StubOutWithMock(oauth, 'get_current_user') oauth.get_current_user('scope').AndReturn(users.User('*****@*****.**')) self.mox.ReplayAll() os.environ['ENDPOINTS_USE_OAUTH_SCOPE'] = 'scope' user = users_id_token.get_current_user() self.assertEqual(user.email(), '*****@*****.**') self.mox.VerifyAll()
def post(self): if users.get_current_user(): link = Link() link.author = users.get_current_user() link.content = urllib2.quote(self.request.get("link")) link.put() self.response.out.write("Sent %s to the cloud." % self.request.get("link")) elif oauth.get_current_user(): link = Link() link.author = oauth.get_current_user() link.content = urllib2.quote(self.request.get("link")) link.put() self.response.out.write("Sent %s to the cloud." % self.request.get("link")) else: self.redirect(users.create_login_url("/links/add"))
def from_request(cls, request): email = None admin = False auth = [] app_id = request.headers.get('X-Appengine-Inbound-Appid') if app_id in TRUSTED_APP_IDS: auth.append(cls.AUTH_TRUSTED_APP) if getattr(request, 'authenticated', None) == 'hmac': # Added via hmac_util.CheckHmacAuth decorator. auth.append(cls.AUTH_HMAC) try: oauth_user = oauth.get_current_user(endpoints.EMAIL_SCOPE) email = oauth_user.email() admin = oauth.is_current_user_admin(endpoints.EMAIL_SCOPE) auth.append(cls.AUTH_OAUTH) if email in TRUSTED_CLIENT_EMAILS: auth.append(cls.AUTH_TRUSTED_CLIENT) except oauth.OAuthRequestError: u = users.get_current_user() if u: email = u.email() admin = users.is_current_user_admin() auth.append(cls.AUTH_COOKIES) return cls(email, admin, auth)
def get(self, name=False): user = False try: user = oauth.get_current_user() except oauth.InvalidOAuthTokenError, e: self.response.out.write("InvalidOAuthTokenError: %s" % e) user = users.get_current_user()
def get(self): """Renders the main page. When this page is shown, we create a new channel to push asynchronous updates to the client.""" try: user = oauth.get_current_user() except: user = users.get_current_user() override = {} if self.request.get("display_name"): override["display_name"] = self.request.get("display_name") if self.request.get("name"): override["name"] = self.request.get("name") if self.request.get("flush_memcache"): memcache.flush_all() if user: user_data = UserData.all().filter("user ="******"user") user_data = db.get(main.new(override)) if self.request.get("name"): device = user_data.devices.filter("name =", self.request.get("name")).get() else: device = user_data.devices.order("default").get() if not device: main = Maintainer("device") device = db.get(main.new(override)) messager = DeviceMessager(device.address) logging.info(messager.receiver.address) channel_token = messager.CreateChannelToken() template_values = {"channel_id": channel_token, "device": device.address, "device_name": device.name} path = os.path.join(os.path.dirname(__file__), "devlinks_index.html") self.response.out.write(template.render(path, template_values)) else: self.redirect(users.create_login_url(self.request.uri))
def Authorize(): try: user = oauth.get_current_user(OAUTH_SCOPES) except oauth.Error: raise NotLoggedInError if not user: raise NotLoggedInError try: if not user.email().endswith('.gserviceaccount.com'): # For non-service account, need to verify that the OAuth client ID # is in our whitelist. client_id = oauth.get_client_id(OAUTH_SCOPES) if client_id not in OAUTH_CLIENT_ID_WHITELIST: logging.info('OAuth client id %s for user %s not in whitelist', client_id, user.email()) user = None raise OAuthError except oauth.Error: raise OAuthError logging.info('OAuth user logged in as: %s', user.email()) if utils.IsGroupMember(user.email(), 'chromeperf-access'): datastore_hooks.SetPrivilegedRequest()
def get(self): if users.get_current_user(): self.response.out.write('<form method="post"><input type="text" name="link"><input type="submit"></form>') elif oauth.get_current_user(): self.response.out.write('<form method="post"><input type="text" name="link"><input type="submit"></form>') else: self.redirect(users.create_login_url("/links/add"))
def get(self): user = users.get_current_user() user_oauth = oauth.get_current_user() self.response.write(user_oauth) if user: client_id = "676481030478-0fi923mg6rbe1tqbvffr8n5ih56p63gg.apps.googleusercontent.com" client_secret = "AXSaN3iaVse0lL_GCRp7ioPQ" scope = urllib.unquote(self.request.get("scope")).decode("utf-8") redirect_uri = urllib.unquote(self.request.get("redirect_uri")).decode("utf-8") flow = Oauth2WebServerFlow(client_id, client_secret, scope,redirect_uri=redirect_uri) code = self.request.get("code") redirect_uri = "http://localhost:19080/oauth" grant_type = "authorization_code" form_fields = { "code" : code, "client_id" : client_id, "client_secret" : client_secret, "redirect_uri" : redirect_uri, "grant_type" : grant_type, } form_data = urllib.urlencode(form_fields) url_validator = "https://www.googleapis.com/oauth2/v1/tokeninfo" #url_validator = "https://www.googleapis.com/o/oauth2/token?access_token=" + code result = urlfetch.fetch( headers = {'Content-Type': 'application/x-www-form-urlencoded'}, url = url_validator, payload = form_data, method = urlfetch.POST, ) self.response.write(result.content)
def from_request(cls, request): email = None admin = False auth = [] app_id = request.headers.get('X-Appengine-Inbound-Appid') if app_id in TRUSTED_APP_IDS: auth.append(cls.AUTH_TRUSTED_APP) if getattr(request, 'authenticated', None) == 'hmac': # Added via hmac_util.CheckHmacAuth decorator. auth.append(cls.AUTH_HMAC) try: oauth_user = oauth.get_current_user(endpoints.EMAIL_SCOPE) email = oauth_user.email() admin = oauth.is_current_user_admin(endpoints.EMAIL_SCOPE) auth.append(cls.AUTH_OAUTH) if email in TRUSTED_CLIENT_EMAILS: auth.append(cls.AUTH_TRUSTED_CLIENT) except oauth.OAuthRequestError: u = users.get_current_user() if u: email = u.email() admin = users.is_current_user_admin() auth.append(cls.AUTH_COOKIES) return cls(email, admin, auth)
def authenticate(self): """Returns an authenticated User. Or an Exception if the User is not properly authenticated. """ _trace = TRACE + "APIBase:: authenticate() " logging.info(_trace) user = None try: user = oauth.get_current_user() logging.info(_trace + "user = "******"InvalidOAuthParametersError! The client provided OAuth parameters with the request, but they are invalid." ) self.error(401) except oauth.InvalidOAuthTokenError: logging.error( _trace + "InvalidOAuthTokenError! The client provided an OAuth token with the request, but it has been revoked by the user, or is otherwise invalid." ) self.error(401) except oauth.OAuthServiceFailureError: logging.error(_trace + "OAuthServiceFailureError! There was an internal error with the OAuth service.") self.error(401) return user
def post(self): """Handles the output posted from taskqueue puller. name is a queryparam that is the task_id of the task whose output is being posted by the puller. We first find the image_name for the task and store the processed image as image_name_processed. This helps when user searches for the image and we can show both uploaded as well as processed image. This handler is OAuth enabled, so that only the administrators of this app can call this handler using an OAuth token. """ try: user = oauth.get_current_user() # Currently there is no way to figure out if a given OAuth user is an # admin. users.is_current_user_admin() only takes care of logged in users, # not users who are presenting tokens on OAuth. We should fix this! if user and user.nickname() == '*****@*****.**': task_name = self.request.get('name') name = self.GetImageNameFromTaskImageMap(task_name) if name: image_key = name + '_processed' image_contents = self.request.body small_image = SmallImage(key_name=image_key, image_name=image_key, image=db.Blob(image_contents)) small_image.put() else: logging.error('No image associated with this task') self.error(404) else: logging.error('unauthorized user ' + user.nickname()) self.error(403) except oauth.OAuthRequestError, e: logging.error('no oauth token detected') self.error(403)
def get_current_user(): """Get user information from the id_token or oauth token in the request. This should only be called from within an Endpoints request handler, decorated with an @endpoints.method decorator. The decorator should include the https://www.googleapis.com/auth/userinfo.email scope. If the current request uses an id_token, this validates and parses the token against the info in the current request handler and returns the user. Or, for an Oauth token, this call validates the token against the tokeninfo endpoint and oauth.get_current_user with the scopes provided in the method's decorator. Returns: None if there is no token or it's invalid. If the token was valid, this returns a User. Only the user's email field is guaranteed to be set. Other fields may be empty. """ if not _is_auth_info_available(): logging.error('endpoints.get_current_user() called outside a request.') return None if _ENV_USE_OAUTH_SCOPE in os.environ: return oauth.get_current_user(os.environ[_ENV_USE_OAUTH_SCOPE]) if (_ENV_AUTH_EMAIL in os.environ and _ENV_AUTH_DOMAIN in os.environ): if not os.environ[_ENV_AUTH_EMAIL]: return None return users.User(os.environ[_ENV_AUTH_EMAIL], os.environ[_ENV_AUTH_DOMAIN] or None) return None
def __init__(self, request, response): super(BaseHandler, self).__init__(request, response) user = users.get_current_user() if user: logging.debug('User authenticated via SACSID cookie: ' + user.email()) else: try: user = oauth.get_current_user() logging.debug('User authenticated via OAuth token: ' + user.email()) except oauth.InvalidOAuthTokenError: logging.info('User provided an invalid OAuth token') self.abort(401, explanation='Invalid OAuth token') except oauth.InvalidOAuthParametersError: pass if not user: logging.info('No valid user authentication credentials supplied') self.user = None return key = models.User.get_memcache_key(user.user_id()) self.user = memcache.get(key) if self.user is None: self.user = models.User.get_or_insert(user.user_id(), email=user.email()) memcache.set(key, self.user) if self.user.email != user.email(): self.user.email = user.email() memcache.set(key, self.user) self.user.last_visit_at = datetime.datetime.now() db.put_async(self.user)
def get_current_rietveld_oauth_user(): """Gets the current OAuth 2.0 user associated with a request. This user must be intending to reach this application, so we check the token info to verify this is the case. Returns: A users.User object that was retrieved from the App Engine OAuth library if the token is valid, otherwise None. """ # TODO(dhermes): Address local environ here as well. try: current_client_id = oauth.get_client_id(EMAIL_SCOPE) except oauth.Error: return accepted_client_id, _, additional_client_ids = SecretKey.get_config() if (accepted_client_id != current_client_id and current_client_id not in additional_client_ids): logging.debug('Client ID %r not intended for this application.', current_client_id) return try: return oauth.get_current_user(EMAIL_SCOPE) except oauth.Error: logging.warning('A Client ID was retrieved with no corresponsing user.')
def get(self, name=False): user = False try: user = oauth.get_current_user() except oauth.InvalidOAuthTokenError, e: self.response.out.write("InvalidOAuthTokenError: %s" % e) user = users.get_current_user()
def GetEmail(): """Returns email address of the current user. Uses OAuth2 for /api/ requests, otherwise cookies. Returns: The email address as a string or None if there is no user logged in. Raises: OAuthRequestError: The request was not a valid OAuth request. OAuthServiceFailureError: An unknown error occurred. """ request_uri = os.environ.get('REQUEST_URI', '') if any(request_uri.startswith(e) for e in OAUTH_ENDPOINTS): # Prevent a CSRF whereby a malicious site posts an api request without an # Authorization header (so oauth.get_current_user() is None), but while the # user is signed in, so their cookies would make users.get_current_user() # return a non-None user. if 'HTTP_AUTHORIZATION' not in os.environ: # The user is not signed in. Avoid raising OAuthRequestError. return None user = oauth.get_current_user(OAUTH_SCOPES) else: user = users.get_current_user() return user.email() if user else None
def GetRequester(self, metadata): """Return the email address of the signed in user or None.""" # When running on localhost, allow request to specify test account. if TEST_ACCOUNT_HEADER in metadata: if not settings.local_mode: raise exceptions.InputException( 'x-test-account only accepted in local_mode') test_account = metadata[TEST_ACCOUNT_HEADER] if not test_account.endswith('@example.com'): raise exceptions.InputException( 'test_account must end with @example.com') logging.info('Using test_account: %r' % test_account) return test_account # Cookie-based auth user = users.get_current_user() if user: logging.info('Using cookie user: %r', user.email()) return user.email() # Oauth try: user = oauth.get_current_user(framework_constants.OAUTH_SCOPE) if user: logging.info('Oauth requester %s', user.email()) return user.email() except oauth.Error as ex: logging.info('Got oauth error: %r', ex) return None
def GetEmail(): """Returns email address of the current user. Uses OAuth2 for /api/ requests, otherwise cookies. Returns: The email address as a string or None if there is no user logged in. Raises: OAuthRequestError: The request was not a valid OAuth request. OAuthServiceFailureError: An unknown error occurred. """ request_uri = os.environ.get('REQUEST_URI', '') if any(request_uri.startswith(e) for e in OAUTH_ENDPOINTS): # Prevent a CSRF whereby a malicious site posts an api request without an # Authorization header (so oauth.get_current_user() is None), but while the # user is signed in, so their cookies would make users.get_current_user() # return a non-None user. if 'HTTP_AUTHORIZATION' not in os.environ: # The user is not signed in. Avoid raising OAuthRequestError. return None user = oauth.get_current_user(OAUTH_SCOPES) else: user = users.get_current_user() return user.email() if user else None
def generate(self, template_name, template_values={}): """Generate takes renders and HTML template along with values passed to that template Args: template_name: A string that represents the name of the HTML template template_values: A dictionary that associates objects with a string assigned to that object to call in the HTML template. The defualt is an empty dictionary. """ # We check if there is a current user and generate a login or logout URL user = users.get_current_user() ouser = oauth.get_current_user() if user or ouser: log_in_out_url = users.create_logout_url('/') else: log_in_out_url = users.create_login_url(self.request.path) #we need to shuttle them back where they came from in this instance # We'll display the user name if available and the URL on all pages values = {'user': user, 'log_in_out_url': log_in_out_url} values.update(template_values) # Construct the path to the template directory = os.path.dirname(__file__) path = os.path.join(directory, 'templates', template_name) # Respond to the request by rendering the template return template.render(path, values, debug=_DEBUG)
def get_current_rietveld_oauth_user(): """Gets the current OAuth 2.0 user associated with a request. This user must be intending to reach this application, so we check the token info to verify this is the case. Returns: A users.User object that was retrieved from the App Engine OAuth library if the token is valid, otherwise None. """ # TODO(dhermes): Address local environ here as well. try: current_client_id = _get_client_id() except oauth.Error as e: logging.debug('OAuth error occurred: %s' % str(e.__class__.__name__)) return # SecretKey.get_config() below returns client ids of service accounts that # are authorized to connect to this instance. # If modifying the following lines, please look for places where # 'developer.gserviceaccount.com' (service account domain) is used. Some # code relies on the filtering performed here. accepted_client_id, _, additional_client_ids = SecretKey.get_config() if (accepted_client_id != current_client_id and current_client_id not in additional_client_ids): logging.debug('Client ID %r not intended for this application.', current_client_id) return try: return oauth.get_current_user(EMAIL_SCOPE) except oauth.Error: logging.warning( 'A Client ID was retrieved with no corresponding user.')
def getCurrentUser(): user = False try: user = oauth.get_current_user() except: user = users.get_current_user() return user
def _authenticate_user(): try: if oauth.is_current_user_admin(): # The user on whose behalf we are acting is indeed an administrator # of this application, so we're good to go. logging.info('Authenticated on behalf of user %s.' % oauth.get_current_user()) return else: raise UserNotAuthenticatedException( 'We are acting on behalf of ' 'user %s, but that user is not ' 'an administrator.' % oauth.get_current_user()) except oauth.OAuthRequestError as exception: raise UserNotAuthenticatedException('Invalid OAuth request: %s' % exception.__class__.__name__)
def check_login(self, *args, **kwargs): host = self.request.headers.get('host', 'nohost') try: user = oauth.get_current_user() admin = oauth.is_current_user_admin() except oauth.OAuthRequestError, e: admin = False
def get_current_rietveld_oauth_user(): """Gets the current OAuth 2.0 user associated with a request. This user must be intending to reach this application, so we check the token info to verify this is the case. Returns: A users.User object that was retrieved from the App Engine OAuth library if the token is valid, otherwise None. """ # TODO(dhermes): Address local environ here as well. try: current_client_id = _get_client_id() except oauth.Error as e: logging.debug('OAuth error occurred: %s' % str(e.__class__.__name__)) return # SecretKey.get_config() below returns client ids of service accounts that # are authorized to connect to this instance. # If modifying the following lines, please look for places where # 'developer.gserviceaccount.com' (service account domain) is used. Some # code relies on the filtering performed here. accepted_client_id, _, additional_client_ids = SecretKey.get_config() if (accepted_client_id != current_client_id and current_client_id not in additional_client_ids): logging.debug('Client ID %r not intended for this application.', current_client_id) return try: return oauth.get_current_user(EMAIL_SCOPE) except oauth.Error: logging.warning('A Client ID was retrieved with no corresponding user.')
def get_current_user(): """Get user information from the id_token or oauth token in the request. This should only be called from within an Endpoints request handler, decorated with an @endpoints.method decorator. The decorator should include the https://www.googleapis.com/auth/userinfo.email scope. If the current request uses an id_token, this validates and parses the token against the info in the current request handler and returns the user. Or, for an Oauth token, this call validates the token against the tokeninfo endpoint and oauth.get_current_user with the scopes provided in the method's decorator. Returns: None if there is no token or it's invalid. If the token was valid, this returns a User. Only the user's email field is guaranteed to be set. Other fields may be empty. """ if not _is_auth_info_available(): logging.error("endpoints.get_current_user() called outside a request.") return None if _ENV_USE_OAUTH_SCOPE in os.environ: return oauth.get_current_user(os.environ[_ENV_USE_OAUTH_SCOPE]) if _ENV_AUTH_EMAIL in os.environ and _ENV_AUTH_DOMAIN in os.environ: if not os.environ[_ENV_AUTH_EMAIL]: return None return users.User(os.environ[_ENV_AUTH_EMAIL], os.environ[_ENV_AUTH_DOMAIN] or None) return None
def delete(self, package_id, id, format): """Delete one of this package's uploaders. Only uploaders may delete uploaders. If only one uploader remains, that uploader may not be deleted until a new one is added. """ package = handlers.request().package if oauth.get_current_user() not in package.uploaders: handlers.http_error( 403, "You aren't an uploader for package '%s'." % package.name) user_to_delete = users.User(id) if user_to_delete not in package.uploaders: handlers.http_error( 400, "'%s' isn't an uploader for package '%s'." % (user_to_delete.nickname(), package.name)) if len(package.uploaders) == 1: handlers.http_error( 400, ("Package '%s' only has one uploader, so that uploader " + "can't be removed.") % package.name) package.uploaders.remove(user_to_delete) package.put() return handlers.json_success( "'%s' is no longer an uploader for package '%s'." % (id, package.name))
def get(self): if users.get_current_user(): self.response.out.write("<form method=\"post\"><input type=\"text\" name=\"link\"><input type=\"submit\"></form>") elif oauth.get_current_user(): self.response.out.write("<form method=\"post\"><input type=\"text\" name=\"link\"><input type=\"submit\"></form>") else: self.redirect(users.create_login_url("/links/add"))
def get_current_user(): user = users.get_current_user() logging.info("User (users): %s" % user) if not user: ouser = oauth.get_current_user() logging.info("User (oauth): %s" % user) return user
def __init__(self, request, response): super(BaseHandler, self).__init__(request, response) user = users.get_current_user() if user: logging.debug('User authenticated via SACSID cookie: ' + user.email()) else: try: user = oauth.get_current_user() logging.debug('User authenticated via OAuth token: ' + user.email()) except oauth.InvalidOAuthParametersError: pass if not user: logging.info('No valid user authentication credentials supplied') self.user = None return key = models.User.get_memcache_key(user.user_id()) self.user = memcache.get(key) if self.user is None: self.user = models.User.get_or_insert(user.user_id(), email=user.email()) memcache.set(key, self.user) if self.user.email != user.email(): self.user.email = user.email() memcache.set(key, self.user) self.user.last_visit_at = datetime.datetime.now() db.put_async(self.user)
def _late_init(self): """Initializes self._is_admin and self._user once the request is setup.""" self._is_admin = False def look_for_password(): """Looks for password parameter""" password = self.request.get('password') if password: sha1_pass = hashlib.sha1(password).hexdigest() if Passwords.gql('WHERE password_sha1 = :1', sha1_pass).get(): # The password is valid, this is a super admin. self._is_admin = True else: if utils.is_dev_env() and password == 'foobar': # Dev server is unsecure. self._is_admin = True else: logging.error('Password is invalid') self._user = users.get_current_user() if utils.is_dev_env(): look_for_password() elif not self._user: try: self._user = oauth.get_current_user() except oauth.OAuthRequestError: if self.request.scheme == 'https': look_for_password() if not self._is_admin and self._user: self._is_admin = bool( users.is_current_user_admin() or self._VALID_EMAIL.match(self._user.email())) self._initialized = True logging.info('Admin: %s, User: %s' % (self._is_admin, self._user))
def DoOAuthAuth(is_admin=None, require_level=None): """Verify OAuth was used with a valid account. Args: is_admin: Boolean. When True, checks if the user is an admin. require_level: int, default None, when defined, requires that a session be at level x. Returns: users.User() object. Raises: NotAuthenticated: there is no authenticated user for this request. IsAdminMismatch: the current user is not an administrator. """ # TODO(user): make use of require_level. try: user = oauth.get_current_user(OAUTH_SCOPE) except oauth.OAuthRequestError: raise NotAuthenticated('OAuthRequestError') email = user.email() if is_admin is not None and not IsAdminUser(email): raise IsAdminMismatch if email in _GetGroupMembers('oauth_users'): return user logging.warning('OAuth user unknown: %s', email) raise NotAuthenticated('DoOAuthAuthUnknownUser')
def Authorize(): try: user = oauth.get_current_user(OAUTH_SCOPES) except oauth.Error: raise NotLoggedInError if not user: raise NotLoggedInError try: if not user.email().endswith('.gserviceaccount.com'): # For non-service account, need to verify that the OAuth client ID # is in our whitelist. client_id = oauth.get_client_id(OAUTH_SCOPES) if client_id not in OAUTH_CLIENT_ID_WHITELIST: logging.info('OAuth client id %s for user %s not in whitelist', client_id, user.email()) user = None raise OAuthError except oauth.Error: raise OAuthError logging.info('OAuth user logged in as: %s', user.email()) if utils.IsGroupMember(user.email(), 'chromeperf-access'): datastore_hooks.SetPrivilegedRequest()
def get_current_rietveld_oauth_user(): """Gets the current OAuth 2.0 user associated with a request. This user must be intending to reach this application, so we check the token info to verify this is the case. Returns: A users.User object that was retrieved from the App Engine OAuth library if the token is valid, otherwise None. """ # TODO(dhermes): Address local environ here as well. try: current_client_id = _get_client_id() except oauth.Error: return accepted_client_id, _, additional_client_ids = SecretKey.get_config() if (accepted_client_id != current_client_id and current_client_id not in additional_client_ids): logging.debug('Client ID %r not intended for this application.', current_client_id) return try: return oauth.get_current_user(EMAIL_SCOPE) except oauth.Error: logging.warning( 'A Client ID was retrieved with no corresponsing user.')
def _authenticate_user(): try: if oauth.is_current_user_admin(): # The user on whose behalf we are acting is indeed an administrator # of this application, so we're good to go. logging.info('Authenticated on behalf of user %s.' % oauth.get_current_user()) return else: raise UserNotAuthenticatedException('We are acting on behalf of ' 'user %s, but that user is not ' 'an administrator.' % oauth.get_current_user()) except oauth.OAuthRequestError as exception: raise UserNotAuthenticatedException('Invalid OAuth request: %s' % exception.__class__.__name__)
def get_current_user(): try: if not config.get('DEV_SERVER'): return oauth.get_current_user(SCOPES) except oauth.Error as e: pass return users.get_current_user()
def DoOAuthAuth(is_admin=None, require_level=None): """Verify OAuth was used with a valid account. Args: is_admin: Boolean. When True, checks if the user is an admin. require_level: int, default None, when defined, requires that a session be at level x. Returns: users.User() object. Raises: NotAuthenticated: there is no authenticated user for this request. IsAdminMismatch: the current user is not an administrator. """ # TODO(user): make use of require_level. try: user = oauth.get_current_user() except oauth.OAuthRequestError as e: logging.warning('OAuthRequestError: %s', e) raise NotAuthenticated('OAuthRequestError') email = user.email() if is_admin is not None and not IsAdminUser(email): raise IsAdminMismatch if email in _GetGroupMembers('oauth_users'): return user logging.warning('OAuth user unknown: %s', email) raise NotAuthenticated('DoOAuthAuthUnknownUser')
def get(self): # if users.get_current_user(): # link = Link.all().filter("author =", users.get_current_user()).order("-date").get() # if link and link.content: # self.response.out.write("<link>" + urllib2.unquote(link.content) + "</link>") # else: # self.response.out.write("\"\"") # elif oauth.get_current_user(): if oauth.get_current_user(): link = Link.all().filter("author =", oauth.get_current_user()).order("-date").get() if link and link.content: self.response.out.write("<link>" + urllib2.unquote(link.content) + "</link>") else: self.response.out.write('""') else: self.redirect(users.create_login_url("/links/get"))
def get_current_user(): user = users.get_current_user(); logging.info("User (users): %s" % user) if not user: ouser = oauth.get_current_user(); logging.info("User (oauth): %s" % user) return user
def rebuild_search_index(self, unused_request): """Rebuild the search index""" if is_user_admin(): rebuild_question_search_index() else: message = 'User "%s" does not have admin rights.' % oauth.get_current_user(USER_INFO_SCOPE).nickname() raise endpoints.UnauthorizedException(message) return StatusResponse(status='SUCCESS')
def decorated(*args, **kwargs): try: args += (oauth.get_current_user(EMAIL_SCOPE), ) except oauth.Error: msg = 'Not authorized / invalid token' raise endpoints.UnauthorizedException(msg) return func(*args, **kwargs)
def test_oauth_works_as_expected_in_test(self): oauth_user = oauth.get_current_user(EMAIL_SCOPE) self.assertEqual(oauth_user.email(), TEST_EMAIL) self.assertEqual(oauth_user.auth_domain(), 'gmail.com') self.assertEqual(oauth_user.user_id(), '0') client_id = oauth.get_client_id(EMAIL_SCOPE) self.assertEqual(client_id, CLIENT_ID)
def post(self, action): try: user = oauth.get_current_user() except: pass else: logging.info(user) self.response.out.write("You're using outdated software. Please upgrade your client.")
def get_oauth_id(): """Returns user email ID if OAUTH token present, or None.""" try: user_email = oauth.get_current_user(SCOPE).email() except oauth.Error as e: user_email = None logging.error('OAuth failure: {}'.format(e)) return user_email
def post(self): if users.get_current_user(): link = Link() link.author = users.get_current_user() link.content = urllib2.quote(self.request.get('link')) link.put() memcache.set(link.author.user_id(), link) self.response.out.write("Sent %s to the cloud." % self.request.get('link')) elif oauth.get_current_user(): link = Link() link.author = oauth.get_current_user() link.content = urllib2.quote(self.request.get('link')) link.put() memcache.set(link.author.user_id(), link) self.response.out.write("Sent %s to the cloud." % self.request.get('link')) else: self.redirect(users.create_login_url("/links/add"))
def _get_user_email(): """Returns the email of the oauth client user.""" try: user = oauth.get_current_user([ "https://www.googleapis.com/auth/userinfo.email"]) except (oauth.OAuthRequestError, oauth.OAuthServiceFailureError): user = None return user.email() if user else None
def decorated(*args, **kwargs): try: args += (oauth.get_current_user(EMAIL_SCOPE),) except oauth.Error: msg = 'Not authorized / invalid token' raise endpoints.UnauthorizedException(msg) return func(*args, **kwargs)
def log_upload_data(path, data): import model from google.appengine.ext import db from google.appengine.api import oauth data = db.Text(data) user = oauth.get_current_user() model.DataUploadLog(user=user, path=path, data=data).put()
def new_fn(*args, **kwargs): self = args[0] try: user = oauth.get_current_user() if user: self.user = user except oauth.OAuthRequestError, e: error(str(e))
def GetOauthUserEmail(scope=_EMAIL_SCOPE): """Returns the email of the oauth client user.""" try: user = oauth.get_current_user(scope) # Oauth-based authentication. # TODO (crbug/766768): Retry when meets OAuthServiceFailureError. except (oauth.OAuthRequestError, oauth.OAuthServiceFailureError): user = None # Invalid oauth token or experienced oauth service failure. return user.email() if user else None
def test_oauth_works_as_expected_in_test(self): oauth_user = oauth.get_current_user(EMAIL_SCOPE) self.assertEqual(oauth_user.email(), TEST_EMAIL) self.assertEqual(oauth_user.auth_domain(), 'gmail.com') self.assertEqual(oauth_user.user_id(), '0') client_id = oauth.get_client_id(EMAIL_SCOPE) self.assertEqual(client_id, CLIENT_ID)
def log_upload_data(path, data): import model from google.appengine.ext import db from google.appengine.api import oauth data = db.Text(data) user = oauth.get_current_user() model.DataUploadLog(user=user, path=path, data=data).put()
def check_authorization(self, user_check=True): referer = self.request.headers.get('referer', None) callback = self.request.get('callback', None) if callback is not None and referer is not None: parsed_referer = urlparse(referer) allowed = [ 'localhost', 'localhost:3000', 'localhost:8080', 'localhost:3001', 'www.clockworkmod.com', 'desksms.clockworkmod.com', 'desksms.deployfu.com', 'desksms.appspot.com', '2.desksms.appspot.com' ] if parsed_referer.netloc not in allowed: self.dumps({ 'error': 'jsonp requests from this domain is not supported' }) return self.response.headers[ 'Access-Control-Allow-Origin'] = parsed_referer.netloc current_user = users.get_current_user() is_admin = users.is_current_user_admin() if current_user is None: try: current_user = oauth.get_current_user() is_admin = oauth.is_current_user_admin() except: pass if current_user is None: if user_check: logging.info('user is not logged in') self.redirect(users.create_login_url("/")) #self.dumps({'error': 'not logged in'}) return current_user_email = current_user.email().lower() # if this is a user data path, verify that the current # user has proper access. if user_check: email = urllib.unquote(self.request.path.split('/')[4]).lower() if email == 'default': email = current_user_email elif email != current_user_email and not is_admin: logging.info(email) logging.info(current_user_email) logging.info('not admin') self.dumps({'error': 'not administrator'}) return else: email = current_user_email logging.info(email) self.user = current_user return email
def check_login(self, *args, **kwargs): dev = os.environ['SERVER_SOFTWARE'].startswith('Development') host = self.request.headers.get('host', 'nohost') try: user = oauth.get_current_user() admin = oauth.is_current_user_admin() except oauth.OAuthRequestError, e: logging.error("OAuthRegistrationError") admin = False
def post(self, action): try: user = oauth.get_current_user() except: pass else: logging.info(user) self.response.out.write( "You're using outdated software. Please upgrade your client.")
def authorize(action, table): oauth_user = None oauth_admin = None try: oauth_user = oauth.get_current_user('https://www.googleapis.com/auth/plus.me') oauth_admin = oauth.is_current_user_admin('https://www.googleapis.com/auth/plus.me') except oauth.OAuthRequestError, e: logging.debug("No valid oauth credentials were received: %s" % e)