Python google.appengine.api.users.is_current_user_admin() Examples

The following are 30 code examples of google.appengine.api.users.is_current_user_admin(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module google.appengine.api.users , or try the search function .
Example #1
Source File: util.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def GetStatsDataTemplatized(params, template='table'):
    """Returns the stats table run through a template.

    Args:
        params: Example:
                        params = {
                            'v': one of the keys in user_agent.BROWSER_NAV,
                            'current_user_agent': a user agent entity,
                            'user_agents': list_of user agents,
                            'tests': list of test names,
                            'stats': dict - stats[test_name][user_agent],
                            'total_runs': total_runs[test_name],
                            'request_path': request.path,
                            'params': result_parent.params, #optional
                        }

    """
    params['browser_nav'] = result_stats.BROWSER_NAV
    params['is_admin'] = users.is_current_user_admin()
    if not re.search('\?', params['request_path']):
        params['request_path'] = params['request_path'] + '?'
    t = loader.get_template('stats_%s.html' % template)
    template_rendered = t.render(Context(params))
    return template_rendered 
Example #2
Source File: appengine_main.py    From golinks with MIT License 6 votes vote down vote up
def post(self, link):
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.path))
      return
    key = link.rstrip("/")
    l = Link.get_by_id(key)
    if l.owner_id:
      if l.owner_id != user.user_id() and not users.is_current_user_admin():
        logging.info("%s tried to delete /%s but doesn't have permission" %
                     (user.email(), key))
        errorPage(self.response, 403, "Access denied")
        return
    l.key.delete()
    logging.info("%s deleted /%s" % (user.email(), key))
    self.redirect("/links/my") 
Example #3
Source File: appengine_main.py    From golinks with MIT License 6 votes vote down vote up
def get(self, param):
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.path))
      return
    sign_out_link = users.create_logout_url('/')
    is_admin = users.is_current_user_admin()
    if param == "all" and is_admin:
      links = Link.query().fetch()
    else:
      links = Link.query(Link.owner_id == user.user_id()).fetch()
    context = {
        "links": links,
        "is_admin": is_admin,
        "sign_out_link": sign_out_link,
        "fqdn": config.GOLINKS_FQDN,
        "hostname": config.GOLINKS_HOSTNAME
    }
    self.response.write(render("template/list.html", context)) 
Example #4
Source File: fileutils.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_credentials(request, other_application='admin',
                      expiration=60 * 60, gae_login=True):
    """ checks that user is authorized to access other_application"""
    if request.env.web2py_runtime_gae:
        from google.appengine.api import users
        if users.is_current_user_admin():
            return True
        elif gae_login:
            login_html = '<a href="%s">Sign in with your google account</a>.' \
                % users.create_login_url(request.env.path_info)
            raise HTTP(200, '<html><body>%s</body></html>' % login_html)
        else:
            return False
    else:
        t0 = time.time()
        dt = t0 - expiration
        s = get_session(request, other_application)
        r = (s.authorized and s.last_time and s.last_time > dt)
        if r:
            s.last_time = t0
            set_session(request,s,other_application)
        return r 
Example #5
Source File: status_ui.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def get(self, resource=''):
    import pipeline  # Break circular dependency
    if pipeline._ENFORCE_AUTH:
      if users.get_current_user() is None:
        self.redirect(users.create_login_url(self.request.url))
        return

      if not users.is_current_user_admin():
        self.response.out.write('Forbidden')
        self.response.set_status(403)
        return

    if resource not in self._RESOURCE_MAP:
      logging.info('Could not find: %s', resource)
      self.response.set_status(404)
      self.response.out.write("Resource not found.")
      self.response.headers['Content-Type'] = 'text/plain'
      return

    relative_path, content_type = self._RESOURCE_MAP[resource]
    path = os.path.join(os.path.dirname(__file__), relative_path)
    if not pipeline._DEBUG:
      self.response.headers["Cache-Control"] = "public, max-age=300"
    self.response.headers["Content-Type"] = content_type
    self.response.out.write(open(path, 'rb').read()) 
Example #6
Source File: status_ui.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def get(self):
    import pipeline  # Break circular dependency
    if pipeline._ENFORCE_AUTH:
      if not users.is_current_user_admin():
        self.response.out.write('Forbidden')
        self.response.set_status(403)
        return

    # XSRF protection
    if (not pipeline._DEBUG and
        self.request.headers.get('X-Requested-With') != 'XMLHttpRequest'):
      self.response.out.write('Request missing X-Requested-With header')
      self.response.set_status(403)
      return

    self.json_response = {}
    try:
      self.handle()
      output = simplejson.dumps(self.json_response, cls=util.JsonEncoder)
    except Exception, e:
      self.json_response.clear()
      self.json_response['error_class'] = e.__class__.__name__
      self.json_response['error_message'] = str(e)
      self.json_response['error_traceback'] = traceback.format_exc()
      output = simplejson.dumps(self.json_response, cls=util.JsonEncoder) 
Example #7
Source File: google.py    From gae-angular-material-starter with MIT License 6 votes vote down vote up
def retrieve_user_from_google(google_user):
    auth_id = 'federated_%s' % google_user.user_id()
    user_db = model.User.get_by('auth_ids', auth_id)
    if user_db:
        if not user_db.admin and users.is_current_user_admin():
            user_db.admin = True
            user_db.put()
        return user_db

    return auth.create_or_get_user_db(
        auth_id=auth_id,
        name=util.create_name_from_email(google_user.email()),
        username=google_user.email(),
        email=google_user.email(),
        verified=True,
        admin=users.is_current_user_admin(),
    ) 
Example #8
Source File: playground.py    From cloud-playground with Apache License 2.0 6 votes vote down vote up
def post(self):  # pylint:disable-msg=invalid-name
    """Handles HTTP POST requests."""
    if not users.is_current_user_admin():
      self.response.set_status(httplib.UNAUTHORIZED)
      return
    key = self.request.data['key']
    url = self.request.data['url']
    client_id = self.request.data.get('client_id')
    client_secret = self.request.data.get('client_secret')
    if client_id and client_secret:
      credential = model.SetOAuth2Credential(key, client_id, client_secret)
    else:
      credential = model.GetOAuth2Credential(key) or model.OAuth2Credential()
    r = {
        'key': key,
        'url': url,
        'client_id': credential.client_id,
        'client_secret': credential.client_secret,
    }
    return r 
Example #9
Source File: gae.py    From github-stats with MIT License 6 votes vote down vote up
def retrieve_user_from_gae(gae_user):
  auth_id = 'federated_%s' % gae_user.user_id()
  user_db = model.User.get_by('auth_ids', auth_id)
  if user_db:
    if not user_db.admin and users.is_current_user_admin():
      user_db.admin = True
      user_db.put()
    return user_db

  return auth.create_user_db(
    auth_id=auth_id,
    name=util.create_name_from_email(gae_user.email()),
    username=gae_user.email(),
    email=gae_user.email(),
    verified=True,
    admin=users.is_current_user_admin(),
  ) 
Example #10
Source File: shared.py    From cloud-playground with Apache License 2.0 6 votes vote down vote up
def HasProjectReadAccess(environ):
  """Assert that the current user has project read permissions.

  Args:
    environ: the current WSGI environ

  Returns:
    True if the current user has read access to the current project.
  """
  project = environ['playground.project']
  if not project:
    Abort(httplib.NOT_FOUND, 'requested read access to non-existent project')
  access_key = environ.get('mimic.access_key')
  if access_key and access_key == project.access_key:
    return True
  if users.is_current_user_admin():
    return True
  user = environ.get('playground.user', None)
  if user and user.key.id() in project.writers:
    return True
  if settings.PUBLIC_PROJECT_TEMPLATE_OWNER in project.writers:
    return True
  if settings.MANUAL_PROJECT_TEMPLATE_OWNER in project.writers:
    return True
  return False 
Example #11
Source File: shared.py    From cloud-playground with Apache License 2.0 6 votes vote down vote up
def HasProjectWriteAccess(environ):
  """Assert that the current user has project write permissions.

  Args:
    environ: the current WSGI environ

  Returns:
    True if the current user as write access to the current project.
  """
  project = environ['playground.project']
  if not project:
    Abort(httplib.NOT_FOUND, 'requested write access to non-existent project')
  if users.is_current_user_admin():
    return True
  user = environ.get('playground.user')
  if user and user.key.id() in project.writers:
    return True
  return False 
Example #12
Source File: auth.py    From love with MIT License 5 votes vote down vote up
def is_admin():
    return users.get_current_user() and users.is_current_user_admin() 
Example #13
Source File: __init__.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def get(self):

    if users.is_current_user_admin():
      self.generate('interactive.html')
    else:
      logging.warning(
          'Non admin user from IP %s attempted to use interactive console',
          self.request.remote_addr)
      self.error(404) 
Example #14
Source File: ui.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def __call__(self, environ, start_response):
    if not environ.get('SERVER_SOFTWARE', '').startswith('Dev'):
      if not users.is_current_user_admin():
        if users.get_current_user() is None:
          start_response('302 Found',
                         [('Location',
                           users.create_login_url(os.getenv('PATH_INFO', '')))])
          return []
        else:
          start_response('403 Forbidden', [])
          return ['Forbidden\n']
    return self._application(environ, start_response) 
Example #15
Source File: lib_config.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def main():
  """Dumps the configuration, using a CGI-style request handler.

  Put this in your `app.yaml` file to enable (you can pick any URL)::

      - url: /lib_config
        script: $PYTHON_LIB/google/appengine/api/lib_config.py


  Note:
      Unless you are using the SDK, you must be an administrator to use this
      function.
  """
  if not os.getenv('SERVER_SOFTWARE', '').startswith('Dev'):
    from google.appengine.api import users
    if not users.is_current_user_admin():
      if users.get_current_user() is None:
        print 'Status: 302'
        print 'Location:', users.create_login_url(os.getenv('PATH_INFO', ''))
      else:
        print 'Status: 403'
        print
        print 'Forbidden'
      return

  print 'Content-type: text/plain'
  print
  _default_registry._dump() 
Example #16
Source File: playground.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def get(self):  # pylint:disable-msg=invalid-name
    """Handles HTTP GET requests."""
    r = {
        'PLAYGROUND_USER_CONTENT_HOST': settings.PLAYGROUND_USER_CONTENT_HOST,
        'git_playground_url': 'http://code.google.com/p/cloud-playground/',
        'playground_namespace': settings.PLAYGROUND_NAMESPACE,
        'email': self.user.key.id(),
        'is_logged_in': bool(users.get_current_user()),
        'is_admin': bool(users.is_current_user_admin()),
        'is_devappserver': bool(_DEV_APPSERVER),
    }
    return r 
Example #17
Source File: decorators.py    From love with MIT License 5 votes vote down vote up
def admin_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if users.get_current_user():
            if not users.is_current_user_admin():
                abort(401)  # Unauthorized
            return func(*args, **kwargs)
        return redirect(users.create_login_url(request.url))
    return decorated_view 
Example #18
Source File: main.py    From cas-eval with Apache License 2.0 5 votes vote down vote up
def export():
    user = users.get_current_user()
    total_shared = Session.query(Session.shared == True).count()
    if user and users.is_current_user_admin():
        bucket_size = max(1, total_shared // (NUM_TASKS - 1))
        for i in range(NUM_TASKS):
            # start a task with delay of 60*i seconds
            taskqueue.add(url='/tasks/process_export', method='GET',
                    params={'bucket':  i, 'bucket_size': bucket_size}, countdown=60*i)
        return 'Trigerred for %d queries' % total_shared, 200
    else:
        return 'Admin access only', 403 
Example #19
Source File: __init__.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def post(self):
    if users.is_current_user_admin():
      if self.interactive_console_enabled():

        save_stdout = sys.stdout
        results_io = cStringIO.StringIO()
        try:
          sys.stdout = results_io


          code = self.request.get('code')
          code = code.replace('\r\n', '\n')

          try:
            compiled_code = compile(code, '<string>', 'exec')
            exec(compiled_code, globals())
          except Exception, e:
            traceback.print_exc(file=results_io)
        finally:
          sys.stdout = save_stdout

        results = results_io.getvalue()
      else:
        results = """The interactive console has been disabled for security
because the dev_appserver is listening on a non-default address.
If you would like to re-enable the console, invoke dev_appserver
with the --enable_console argument.

See https://developers.google.com/appengine/docs/python/tools/devserver#The_Interactive_Console
for more information."""
      self.generate('interactive-output.html', {'output': results})
    else:
      logging.warning(
          'Non admin user from IP %s attempted to use interactive console',
          self.request.remote_addr)
      self.error(404) 
Example #20
Source File: handler.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
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:
      try:
        user_is_authorized = (
            oauth.is_current_user_admin(_scope=self.OAUTH_SCOPES))
      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 
Example #21
Source File: shared.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def AssertIsAdmin():
  if not users.is_current_user_admin():
    Abort(403, 'Admin only function') 
Example #22
Source File: handler.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def gae_cookie_authentication(_request):
  """AppEngine cookie based authentication via users.get_current_user()."""
  user = users.get_current_user()
  if not user:
    return None, None
  try:
    ident = model.Identity(model.IDENTITY_USER, user.email())
  except ValueError:
    raise api.AuthenticationError('Unsupported user email: %s' % user.email())
  return ident, api.new_auth_details(is_superuser=users.is_current_user_admin()) 
Example #23
Source File: playground.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def post(self):  # pylint:disable-msg=invalid-name
    if not users.is_current_user_admin():
      shared.e('You must be an admin for this app')
    model.DeleteReposAndTemplateProjects()
    # force reinitialization
    templates.GetRepoCollections()
    self.redirect('/playground') 
Example #24
Source File: appengine_main.py    From golinks with MIT License 5 votes vote down vote up
def get(self, link):
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.path))
      return
    sign_out_link = users.create_logout_url('/')
    is_admin = users.is_current_user_admin()
    context = {
        "sign_out_link": sign_out_link,
        "is_admin": is_admin,
        "show_visibility": config.ENABLE_GOOGLE_GROUPS_INTEGRATION,
        'hostname': config.GOLINKS_HOSTNAME
    }
    if link:
      link = link.rstrip("/")
      context.update({'key': link})
      l = Link.get_by_id(link)
      if l:
        if l.owner_id:
          if l.owner_id != user.user_id() and not is_admin:
            logging.info(
                "%s tried to check details page of /%s but doesn't have permission"
                % (user.email(), link))
            errorPage(self.response, 403, "Access denied")
            return
        context.update({
            'url': l.url,
            'viewcount': l.viewcount,
            'public': l.public,
            'visibility': l.visibility or '',
            'can_delete': 1,
            'owner': l.owner_name
        })
    logging.info("%s checked details page of /%s" % (user.email(), link))
    self.response.write(render("template/edit.html", context)) 
Example #25
Source File: utils.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def require_api_key_management_permission(handler_method):
    """
    This is a decorator for API Key management feature. The limitation
    is that the decorator can not preserve payloads within a POST/PUT
    request.

    Usage:
    class SomeHandler(utils.BaseHandler):
        @utils.require_api_key_management_permission
        def get(self):
            # ....
            # ....
    """
    def inner(*args, **kwargs):
        handler = args[0]
        user = users.get_current_user()
        if (users.is_current_user_admin() or
            (user and handler.config.key_management_operators and
             user.email() in handler.config.key_management_operators)):
            return handler_method(*args, **kwargs)
        else:
            return handler.redirect(
                users.create_login_url(handler.request.url))
    return inner


# ==== Base Handler ============================================================ 
Example #26
Source File: auth.py    From jacs with Apache License 2.0 5 votes vote down vote up
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) 
Example #27
Source File: handlers.py    From gae-secure-scaffold-python with Apache License 2.0 5 votes vote down vote up
def requires_admin(f):
  """A decorator that requires a currently logged in administrator."""
  @functools.wraps(f)
  def wrapper(self, *args, **kwargs):
    if not users.is_current_user_admin():
      self.DenyAccess()
    else:
      return f(self, *args, **kwargs)
  return wrapper 
Example #28
Source File: decorators.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def admin_required(func):
  """Tests to make sure the current user is an admin."""
  def _wrapper(request, *args, **kw):
    user = users.get_current_user()
    if user:
      if users.is_current_user_admin():
        return func(request, *args, **kw)
      else:
        return HttpResponse('You need to be an admin. <a href="%s">login</a>.'
                            % users.create_login_url(request.get_full_path()))
    else:
      return HttpResponseRedirect(
          users.create_login_url(request.get_full_path()))
  return _wrapper 
Example #29
Source File: middleware.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def process_exception(self, request, exception):
    error = traceback.format_exc()
    logging.error('Traceback: %s', error)
    if users.is_current_user_admin():
      return util.Render(request, '500.html', params={'traceback': error})
    else:
      return None 
Example #30
Source File: user_tests.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def Settings(request):
  if request.POST:
    current_user = users.get_current_user()
    u = models.user_test.User.get_or_insert(current_user.user_id())
    u.email = request.POST.get('email', current_user.email())
    u.save()
    return http.HttpResponseRedirect('/user/settings')

  # Regular GET.
  current_user = users.get_current_user()
  user = models.user_test.User.get_or_insert(
      current_user.user_id(),
      email=current_user.email())
  tests = db.Query(models.user_test.Test)
  tests.filter('user', user)
  # Only admins can see deleted tests.
  if not users.is_current_user_admin():
    tests.filter('deleted', False)
  tests.order('-created')
  if tests.count() == 0:
    tests = None

  params = {
    'api_key': user.key().name(),
    'tests': tests,
    'csrf_token': request.session.get('csrf_token')
  }
  return util.Render(request, 'user_settings.html', params)


# Decorators are inherited by TestEdit