def testIsCurrentUserAdminIsAdmin(self): self.users_stub.SetOAuthUser(email='*****@*****.**', domain='google.com', is_admin=True) self.assertTrue(oauth.is_current_user_admin()) self.assertTrue(oauth.is_current_user_admin())
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 CheckIsAdmin(self): user_is_authorized = False if users.is_current_user_admin(): user_is_authorized = True if not user_is_authorized and config.CUSTOM_ENVIRONMENT_AUTHENTICATION: if len(config.CUSTOM_ENVIRONMENT_AUTHENTICATION) == 2: var, values = config.CUSTOM_ENVIRONMENT_AUTHENTICATION if os.getenv(var) in values: user_is_authorized = True else: logging.warning('remoteapi_CUSTOM_ENVIRONMENT_AUTHENTICATION is ' 'configured incorrectly.') if not user_is_authorized and config._ALLOW_OAUTH: try: user_is_authorized = ( oauth.is_current_user_admin(_scope=self.OAUTH_SCOPE)) except oauth.OAuthRequestError: pass if not user_is_authorized: self.response.set_status(401) self.response.out.write( 'You must be logged in as an administrator to access this.') self.response.headers['Content-Type'] = 'text/plain' return False if 'X-appcfg-api-version' not in self.request.headers: self.response.set_status(403) self.response.out.write('This request did not contain a necessary header') self.response.headers['Content-Type'] = 'text/plain' return False return True
def createConference(self, request): """Create a new Conference object""" user = endpoints.get_current_user() if user.email() and oauth.is_current_user_admin(): # we only allow an admin user to create a conference if not request.name or not request.id: raise endpoints.BadRequestException( "Required field (name and/or id) missing" ) data = {field.name: getattr(request, field.name) for field in request.all_fields()} # convert start/end dates if data['cfpDateFrom']: data['cfpDateFrom'] = datetime.strptime( data['cfpDateFrom'][:10], "%Y-%m-%d").date() if data['cfpDateTo']: data['cfpDateTo'] = datetime.strptime( data['cfpDateTo'][:10], "%Y-%m-%d").date() # set the created date/time stamp data['created'] = datetime.now() data['modified'] = data['created'] # store in DataStore Conference(**data).put() return request else: raise endpoints.ForbiddenException( "Only administrators can create a conference" )
def post(self): assert util.development() or oauth.is_current_user_admin() util.log_upload_data(self.request.path, self.request.get("data")) files_added = {} data = StringIO.StringIO(self.request.get("data")) for line in data: data = json.loads(line) # We first load the fileset into the database # For use later, we also add a list of filenames in the fileset f = model.FileSet(key_name=data["name"], display_name=data["name"], files=data["setfiles"]) f.put() for filename in data["setfiles"]: if filename not in files_added: files_added[filename] = [data["name"]] else: files_added[filename].append(data["name"]) # We now update the database with the elements in files_added for filename in files_added: # TODO: Is there a better way of assigning display names? split_index = filename.rfind("_") model.File(key_name=filename, display_name=filename[:split_index], file_sets=files_added[filename]).put() model.filesets().invalidate() model.files().invalidate()
def get_current_user(oauth_scopes=OAUTH_SCOPES): """Returns the currently logged in TitanUser or None. Args: oauth_scopes: If provided, the OAuth scopes to use to request the current OAuth user via the OAuth API. Set to None to skip OAuth checking. Returns: An initialized TitanUser or None if no user is logged in. """ # NOTE: Order is important here. # If the request was made in a deferred task, check the X-Titan-User header. if 'HTTP_X_APPENGINE_TASKNAME' in os.environ: email = os.environ.get('HTTP_X_TITAN_USER') if email: return TitanUser(email) # Avoid more RPCs, no other user can possibly exist in a task. return # If an OAuth scope is provided, request the current OAuth user, if any. This # should capture endpoints users as well as long as the OAuth scope matches. if oauth_scopes and 'HTTP_AUTHORIZATION' in os.environ: user = _get_current_oauth_user(oauth_scopes) if user: is_admin = oauth.is_current_user_admin(_format_oauth_scopes(oauth_scopes)) organization = os.environ.get('USER_ORGANIZATION') return TitanUser(user.email(), organization=organization, _user=user, _is_admin=is_admin, _is_oauth_user=True) user = users_lib.get_current_user() if user: is_admin = users_lib.is_current_user_admin() organization = os.environ.get('USER_ORGANIZATION') return TitanUser(user.email(), organization=organization, _user=user, _is_admin=is_admin)
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 is_current_user_admin(): try: if not config.get('DEV_SERVER'): return oauth.is_current_user_admin(SCOPES) except oauth.Error as e: pass return users.is_current_user_admin()
def from_endpoints(cls): u = endpoints.get_current_user() if not u: return None return cls(u.email(), lambda: oauth.is_current_user_admin(endpoints.EMAIL_SCOPE), cls.AUTH_OAUTH)
def CheckIsAdmin(self): user_is_authorized = False if users.is_current_user_admin(): user_is_authorized = True if not user_is_authorized and config.CUSTOM_ENVIRONMENT_AUTHENTICATION: if len(config.CUSTOM_ENVIRONMENT_AUTHENTICATION) == 2: var, values = config.CUSTOM_ENVIRONMENT_AUTHENTICATION if os.getenv(var) in values: user_is_authorized = True else: logging.warning( 'remoteapi_CUSTOM_ENVIRONMENT_AUTHENTICATION is ' 'configured incorrectly.') if not user_is_authorized and config._ALLOW_OAUTH: try: user_is_authorized = (oauth.is_current_user_admin( _scope=self.OAUTH_SCOPE)) except oauth.OAuthRequestError: pass if not user_is_authorized: self.response.set_status(401) self.response.out.write( 'You must be logged in as an administrator to access this.') self.response.headers['Content-Type'] = 'text/plain' return False if 'X-appcfg-api-version' not in self.request.headers: self.response.set_status(403) self.response.out.write( 'This request did not contain a necessary header') self.response.headers['Content-Type'] = 'text/plain' return False return True
def IsCurrentUserAdmin(scope=_EMAIL_SCOPE): # pragma: no cover """Returns True if the logged-in user is an admin.""" is_admin = users.is_current_user_admin() try: is_admin = is_admin or oauth.is_current_user_admin(scope) except oauth.OAuthRequestError: pass # Not logged-in or invalid oauth token. return is_admin
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 _ensureAdmin(self): user = endpoints.get_current_user() if user: logging.info('user logged in as ' + user.email()) if not oauth.is_current_user_admin(EMAIL_SCOPE): raise endpoints.UnauthorizedException('Admin rights required') else: raise endpoints.UnauthorizedException('Admin rights required')
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)
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 check_for_admin(): endpoints_user = endpoints.get_current_user() if endpoints_user is None: raise endpoints.UnauthorizedException( 'This method requires authentication') # See https://goo.gl/YTYNP6 for why we use os.getenv() here. is_admin = oauth.is_current_user_admin(os.getenv('OAUTH_LAST_SCOPE')) if not is_admin and not os.environ['APPLICATION_ID'].startswith('dev'): raise endpoints.ForbiddenException( 'This method requires administrator privileges')
def post(self): assert util.development() or oauth.is_current_user_admin() util.log_upload_data(self.request.path, self.request.get("data")) gerrit.poll() data = StringIO.StringIO(self.request.get("data")) new_commits = [] for line in data: new_commits.append(self.load(json.loads(line))) model.commits().invalidate() self.update_depth(new_commits)
def confirmVolunteer(self, volunteer): """Method for admins to confirm a volunteers.""" user = endpoints.get_current_user() is_admin = oauth.is_current_user_admin( _format_oauth_scopes(OAUTH_SCOPES)) if not is_admin: raise endpoints.UnauthorizedException( "You are not allowed to make this request.") volunteer.confirmed = True volunteer.confirmed_by = user volunteer.put() return volunteer
def admin_only(wrapped, instance, args, kwargs): endpoint_user = endpoints.get_current_user() if endpoint_user is None: raise endpoints.UnauthorizedException('This API is admin only') scope = 'https://www.googleapis.com/auth/userinfo.email' is_admin = oauth.is_current_user_admin(scope) # only execute when user is admin or running local server if DEBUG or is_admin: return wrapped(*args, **kwargs) else: raise endpoints.UnauthorizedException('This API is admin only')
def check_login(self, *args, **kwargs): host = self.request.headers.get('host', 'nohost') if self.request.scheme != "https": if not os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'): self.error(403, "SSL is required for POST / PUT / DELETE requests") return try: user = oauth.get_current_user() admin = oauth.is_current_user_admin() except oauth.OAuthRequestError, e: admin = False
def testMultipleScopesSuccess(self): self.users_stub.SetOAuthUser(scopes=['scope1', 'scope2', 'scope3']) authorized_scopes = oauth.get_authorized_scopes( ('scope1', 'scope2', 'scope4')) client_id = oauth.get_client_id(('scope1', 'scope2', 'scope4')) user = oauth.get_current_user(['scope1', 'scope2', 'scope5']) self.assertCountEqual(['scope1', 'scope2'], authorized_scopes) self.assertEqual('123456789.apps.googleusercontent.com', client_id) self.assertEqual('*****@*****.**', user.email()) self.assertEqual('0', user.user_id()) self.assertEqual('gmail.com', user.auth_domain()) self.assertFalse(oauth.is_current_user_admin(('scope1', 'scope2'))) authorized_scopes = oauth.get_authorized_scopes( ['scope1', 'scope2', 'scope4']) client_id = oauth.get_client_id(['scope1', 'scope2', 'scope4']) user = oauth.get_current_user(['scope1', 'scope2', 'scope4']) self.assertCountEqual(['scope1', 'scope2'], authorized_scopes) self.assertEqual('123456789.apps.googleusercontent.com', client_id) self.assertEqual('*****@*****.**', user.email()) self.assertEqual('0', user.user_id()) self.assertEqual('gmail.com', user.auth_domain()) self.assertFalse(oauth.is_current_user_admin(('scope1', 'scope2')))
def _authenticate_user(self): 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. 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)
def is_admin_user(user): if not user: return False if users.is_current_user_admin(): return True try: if oauth.is_current_user_admin(): return True except oauth.OAuthRequestError: pass return False
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 post(self): assert util.development() or oauth.is_current_user_admin() util.log_upload_data(self.request.path, self.request.get("data")) data = StringIO.StringIO(self.request.get("data")) for line in data: data = json.loads(line) # We first load the fileset into the database # For use later, we also add a list of filenames in the fileset m = model.Metric(key_name=data["name"], display_name=data["display name"], distortion=data["distortion"], yaxis=data.get("yaxis", None)) m.put() model.metrics().invalidate()
def check_login(self, *args, **kwargs): host = self.request.headers.get('host', 'nohost') if self.request.scheme != "https": if not os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'): self.error( 403, "SSL is required for POST / PUT / DELETE requests") return try: user = oauth.get_current_user() admin = oauth.is_current_user_admin() except oauth.OAuthRequestError, e: admin = False
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 put_metric_index(self, parent, metrics, files): assert util.development() or oauth.is_current_user_admin() util.log_upload_data(self.request.path, self.request.get("data")) if metrics and files: metric_list = list(metrics) file_list = list(files) h = hashlib.sha1() h.update(parent.key().name()) h.update(parent.commit) h.update(parent.config_name) map(h.update, metric_list) map(h.update, file_list) model.CodecMetricIndex(key_name=h.hexdigest(), parent=parent, commit=parent.commit, config_name=parent.config_name, metrics=metric_list, files=file_list).put()
def get_current_user(oauth_scopes=OAUTH_SCOPES): """Returns the currently logged in TitanUser or None. Args: oauth_scopes: If provided, the OAuth scopes to use to request the current OAuth user via the OAuth API. Set to None to skip OAuth checking. Returns: An initialized TitanUser or None if no user is logged in. """ # NOTE: Order is important here. # If the request was made in a deferred task, check the X-Titan-User header. if 'HTTP_X_APPENGINE_TASKNAME' in os.environ: email = os.environ.get('HTTP_X_TITAN_USER') if email: return TitanUser(email) # Avoid more RPCs, no other user can possibly exist in a task. return # If an OAuth scope is provided, request the current OAuth user, if any. This # should capture endpoints users as well as long as the OAuth scope matches. if oauth_scopes and 'HTTP_AUTHORIZATION' in os.environ: user = _get_current_oauth_user(oauth_scopes) if user: is_admin = oauth.is_current_user_admin( _format_oauth_scopes(oauth_scopes)) organization = os.environ.get('USER_ORGANIZATION') return TitanUser(user.email(), organization=organization, _user=user, _is_admin=is_admin, _is_oauth_user=True) user = users_lib.get_current_user() if user: is_admin = users_lib.is_current_user_admin() organization = os.environ.get('USER_ORGANIZATION') return TitanUser(user.email(), organization=organization, _user=user, _is_admin=is_admin)
def is_current_user_admin(): """Determines if the current user associated with a request is an admin. First tries to verify if the user is an admin with the Users API (cookie-based auth), and then falls back to checking for an OAuth 2.0 admin user with a token minted for use with this application. Returns: Boolean indicating whether or not the current user is an admin. """ cookie_user_is_admin = users.is_current_user_admin() if cookie_user_is_admin: return cookie_user_is_admin # oauth.is_current_user_admin is not sufficient, we must first check that the # OAuth 2.0 user has a token minted for this application. rietveld_user = get_current_rietveld_oauth_user() if rietveld_user is None: return False return oauth.is_current_user_admin(EMAIL_SCOPE)
def IsCurrentOauthUserAdmin(scope=_EMAIL_SCOPE): """Returns True if the oauth client user is an admin.""" try: return oauth.is_current_user_admin(scope) except oauth.OAuthRequestError: return False # Invalid oauth token.
def is_current_user_admin(self): try: return oauth.is_current_user_admin() except oauth.Error: return False
def is_user_admin(): """returns true if admin. does not verify allowed clients membership""" # http://stackoverflow.com/questions/16752998/is-there-a-way-to-check-if-the-user-is-an-admin-in-appengine-cloud-endpoints if oauth.is_current_user_admin(endpoints.EMAIL_SCOPE): return True return False or DEBUG
def is_current_user_admin(): try: return oauth.is_current_user_admin(SCOPES) except oauth.Error as e: return users.is_current_user_admin()
def testIsCurrentUserAdminIsNotAdmin(self): self.assertFalse(oauth.is_current_user_admin()) self.assertFalse(oauth.is_current_user_admin())