Ejemplo n.º 1
0
    def get(self):
        app_settings = AppSettings.Get()
        # Always use /oauth_callback as the redirect URI, as far as the WCA oauth
        # system is concerned.
        # For staging, use the prod /oauth_callback endpoint.  OAuth does not allow
        # wildcards in redirect URIs, and there will potentially be many different
        # foo-dot-staging-cubingusa-org domains.
        if 'staging-cubingusa-org' in self.request.host:
            redirect_uri = 'https://cubingusa.org/oauth_callback'
        else:
            redirect_uri = self.request.host_url + '/oauth_callback'
        params = {
            'client_id':
            GetClientId(app_settings, self.request.get('scope')),
            'response_type':
            'code',
            'redirect_uri':
            redirect_uri,
            'state':
            json.dumps({
                'handler_data': self.request.get('handler_data'),
                'scope': self.request.get('scope'),
                'oauth_redirect_uri': redirect_uri,
                'actual_redirect_uri': self.request.get('callback'),
            }),
            'scope':
            self.request.get('scope'),
        }

        oauth_url = 'https://www.worldcubeassociation.org/oauth/authorize?' + urllib.urlencode(
            params)
        self.redirect(oauth_url)
Ejemplo n.º 2
0
 def get(self):
     template = JINJA_ENVIRONMENT.get_template('admin/app_settings.html')
     self.response.write(
         template.render({
             'c': common.Common(self),
             'settings': AppSettings.Get(),
         }))
Ejemplo n.º 3
0
  def get(self):
    self.auth_token = None
    code = self.request.get('code')
    if not code:
      self.response.set_status(400)
      return

    state = json.loads(self.request.get('state'))
    self.handler_data = state['handler_data']
    scope = state['scope']
    app_settings = AppSettings.Get()

    # Get OAuth token.
    post_data = {
        'grant_type': 'authorization_code',
        'code': code,
        'client_id': GetClientId(app_settings, scope),
        'client_secret': GetClientSecret(app_settings, scope),
        'redirect_uri': state['redirect_uri'],
    }
    conn = httplib.HTTPSConnection('www.worldcubeassociation.org/oauth/token')
    conn.request('POST', '', urllib.urlencode(post_data), {})
    response = conn.getresponse()
    if response.status != 200:
      self.response.set_status(response.status)
      logging.error('Error from WCA OAuth: ' + response.read())
      return
    self.auth_token = json.loads(response.read())['access_token']
Ejemplo n.º 4
0
 def post(self):
     template = JINJA_ENVIRONMENT.get_template(template_path)
     app_settings = AppSettings.Get()
     if app_settings.recaptcha_secret_key:
         payload = {
             'secret': app_settings.recaptcha_secret_key,
             'response': self.request.get('g-recaptcha-response'),
             'remoteip': self.request.remote_addr,
         }
         fetch = urlfetch.fetch(
             url='https://www.google.com/recaptcha/api/siteverify',
             payload=urllib.urlencode(payload),
             method=urlfetch.POST)
         result = json.loads(fetch.content)
         if not result['success']:
             self.response.write(
                 template.render({
                     'c': common.Common(self),
                     'result': 'failure',
                 }))
             return
     subject = '[%s] Contact form -- %s' % (subject_prefix,
                                            self.request.get('name'))
     if self.request.get('wcaid'):
         body = 'WCA ID: %s\n%s' % (self.request.get('wcaid'),
                                    self.request.get('contact-message'))
     else:
         body = self.request.get('contact-message')
     mail.send_mail(sender=contact_email,
                    to=contact_email,
                    cc=self.request.get('from-address'),
                    subject=subject,
                    body=body)
     self.redirect(self.request.url + '?success=1')
Ejemplo n.º 5
0
 def GetWcaApi(self, path):
     if path[0] != '/':
         path = '/' + path
     # OAuth token obtained, now read information using the person's token.
     headers = {'Authorization': 'Bearer ' + self.auth_token}
     url = AppSettings.Get().wca_website + path
     urlfetch.set_default_fetch_deadline(30)
     result = urlfetch.fetch(url=url, headers=headers)
     return result.content
Ejemplo n.º 6
0
    def post(self):
        settings = AppSettings.Get()
        for prop, val in self.request.POST.items():
            if prop.startswith('PROP_'):
                setattr(settings, prop[5:], val)
        settings.put()

        template = JINJA_ENVIRONMENT.get_template('admin/app_settings.html')
        self.response.write(template.render({
            'settings': settings,
        }))
Ejemplo n.º 7
0
 def PatchWcaApi(self, path, body):
     if path[0] != '/':
         path = '/' + path
     # OAuth token obtained, now read information using the person's token.
     headers = {
         'Authorization': 'Bearer ' + self.auth_token,
         'Content-Type': 'application/json'
     }
     url = AppSettings.Get().wca_website + path
     urlfetch.set_default_fetch_deadline(30)
     result = urlfetch.fetch(url=url,
                             method=urlfetch.PATCH,
                             headers=headers,
                             payload=body)
     return result.content
Ejemplo n.º 8
0
  def get(self):
    app_settings = AppSettings.Get()
    params = {
        'client_id': GetClientId(app_settings, self.request.get('scope')),
        'response_type': 'code',
        'redirect_uri': self.request.get('callback'),
        'state': json.dumps({
            'handler_data': self.request.get('handler_data'),
            'scope': self.request.get('scope'),
            'redirect_uri': self.request.get('callback'),
        }),
        'scope': self.request.get('scope'),
    }

    oauth_url = 'https://www.worldcubeassociation.org/oauth/authorize?' + urllib.urlencode(params)
    self.redirect(oauth_url)
Ejemplo n.º 9
0
 def post(self):
   settings = AppSettings.Get()
   settings.session_secret_key = self.request.POST['session_secret_key']
   settings.wca_oauth_client_id = self.request.POST['wca_oauth_client_id']
   settings.wca_oauth_client_secret = self.request.POST['wca_oauth_client_secret']
   settings.wca_oauth_comp_management_client_id = self.request.POST['wca_oauth_comp_management_client_id']
   settings.wca_oauth_comp_management_client_secret = self.request.POST['wca_oauth_comp_management_client_secret']
   settings.google_maps_api_key = self.request.POST['google_maps_api_key']
   settings.recaptcha_site_key = self.request.POST['recaptcha_site_key']
   settings.recaptcha_secret_key = self.request.POST['recaptcha_secret_key']
   settings.google_analytics_tracking_id = self.request.POST['google_analytics_tracking_id']
   settings.contact_email = self.request.POST['contact_email']
   settings.mailing_list_service_account_credentials = self.request.POST['mailing_list_service_account_credentials']
   settings.put()
   template = JINJA_ENVIRONMENT.get_template('admin/app_settings.html')
   self.response.write(template.render({
       'c': common.Common(self),
       'settings': settings,
   }))
Ejemplo n.º 10
0
 def GetTokenFromRefreshToken(self, refresh_token):
     app_settings = AppSettings.Get()
     post_data = {
         'grant_type': 'refresh_token',
         'refresh_token': refresh_token.token,
         'client_id': app_settings.wca_oauth_client_id,
         'client_secret': app_settings.wca_oauth_client_secret,
     }
     conn = httplib.HTTPSConnection(
         strip(app_settings.wca_website) + '/oauth/token')
     conn.request('POST', '', urllib.urlencode(post_data), {})
     response = conn.getresponse()
     if response.status != 200:
         self.response.set_status(response.status)
         logging.error('Error from WCA OAuth: ' + response.read())
         return
     response_json = json.loads(response.read())
     self.auth_token = response_json['access_token']
     refresh_token.token = response_json['refresh_token']
     refresh_token.put()
Ejemplo n.º 11
0
 def GetTokenFromRefreshToken(self, refresh_token):
     app_settings = AppSettings.Get()
     post_data = {
         'grant_type': 'refresh_token',
         'refresh_token': refresh_token.token,
         'client_id': GetClientId(app_settings, refresh_token.scope),
         'client_secret': GetClientSecret(app_settings,
                                          refresh_token.scope),
     }
     conn = httplib.HTTPSConnection(
         'www.worldcubeassociation.org/oauth/token')
     conn.request('POST', '', urllib.urlencode(post_data), {})
     response = conn.getresponse()
     if response.status != 200:
         self.response.set_status(response.status)
         logging.error('Error from WCA OAuth: ' + response.read())
         return
     response_json = json.loads(response.read())
     self.auth_token = response_json['access_token']
     refresh_token.token = response_json['refresh_token']
     refresh_token.put()
Ejemplo n.º 12
0
    def get(self):
        app_settings = AppSettings.Get()
        redirect_uri = self.request.host_url + '/oauth_callback'

        params = {
            'client_id':
            app_settings.wca_oauth_client_id,
            'response_type':
            'code',
            'redirect_uri':
            redirect_uri,
            'state':
            json.dumps({
                'handler_data': self.request.get('handler_data'),
                'oauth_redirect_uri': redirect_uri,
                'actual_redirect_uri': self.request.get('callback'),
            }),
            'scope':
            'public email manage_competitions',
        }

        oauth_url = app_settings.wca_website + '/oauth/authorize?' + urllib.urlencode(
            params)
        self.redirect(str(oauth_url))
Ejemplo n.º 13
0
    def GetTokenFromCode(self):
        self.auth_token = None
        code = self.request.get('code')
        if not code:
            self.response.set_status(400)
            return

        state = json.loads(self.request.get('state'))
        self.handler_data = state['handler_data']
        app_settings = AppSettings.Get()

        # Get OAuth token.
        post_data = {
            'grant_type': 'authorization_code',
            'code': code,
            'client_id': app_settings.wca_oauth_client_id,
            'client_secret': app_settings.wca_oauth_client_secret,
            'redirect_uri': state['oauth_redirect_uri'],
        }
        conn = httplib.HTTPSConnection(
            strip(app_settings.wca_website) + '/oauth/token')
        conn.request('POST', '', urllib.urlencode(post_data), {})
        response = conn.getresponse()
        if response.status != 200:
            self.response.set_status(response.status)
            logging.error('Error from WCA OAuth: ' + response.read())
            return
        response_json = json.loads(response.read())
        self.auth_token = response_json['access_token']
        # The handler may choose to save this for later use.
        self.refresh_token = response_json['refresh_token']
        if self.user:
            refresh_token = RefreshToken(id=self.user.key.id())
            refresh_token.token = response_json['refresh_token']
            refresh_token.user = self.user.key
            refresh_token.put()
Ejemplo n.º 14
0
def GetAppConfig():
  return {
    'webapp2_extras.sessions': {
      'secret_key': str(AppSettings.Get().session_secret_key),
    },
  }
Ejemplo n.º 15
0
    def get(self):
        app_settings = AppSettings.Get()
        if app_settings.mailing_list_service_account_credentials:
            credentials = service_account.Credentials.from_service_account_info(
                json.loads(
                    app_settings.mailing_list_service_account_credentials),
                scopes=[
                    'https://www.googleapis.com/auth/admin.directory.group.member',
                    'https://www.googleapis.com/auth/spreadsheets.readonly'
                ],
                subject='*****@*****.**')

            directory_service = googleapiclient.discovery.build(
                'admin', 'directory_v1', credentials=credentials)
        else:
            credentials = None
            directory_service = None

        # First update [email protected].
        all_delegate_email_addresses = set()
        url_to_fetch = 'https://www.worldcubeassociation.org/api/v0/delegates'
        while url_to_fetch:
            result = urlfetch.fetch(url_to_fetch)
            url_to_fetch = None
            if result.status_code != 200:
                self.request.status = result.status_code
                self.response.write(result.content)
                return

            for delegate in json.loads(result.content):
                if 'USA' in delegate['region']:
                    all_delegate_email_addresses.add(
                        clean_email(delegate['email']))

            # Delegates list is paginated; find the next page.
            for link in requests.utils.parse_header_links(
                    result.headers['link']):
                if link['rel'] == 'next':
                    url_to_fetch = link['url']
        UpdateMailingList(all_delegate_email_addresses, directory_service,
                          '*****@*****.**')

        # Next update [email protected].
        all_staff_email_addresses = set()
        sheets_service = googleapiclient.discovery.build(
            'sheets', 'v4', credentials=credentials)

        # Nats 2018 staff spreadsheet.
        spreadsheet_id = '1e6SC0zrn24el-6gVJ0DxByy5JfSw_13tczVFDMcIneQ'

        # First find the column containing emails.
        selected_column = 0
        for i, value in enumerate(sheets_service.spreadsheets().values().get(
                spreadsheetId=spreadsheet_id, range='1:1',
                majorDimension='ROWS').execute()['values'][0]):
            if 'email' in value.lower():
                selected_column = i + 1

        # Convert column number to name
        column_name = ''
        num = selected_column
        while num > 0:
            num, remainder = divmod(num - 1, 26)
            column_name = chr(65 + remainder) + column_name
        # Ignore the first two rows (the header, and the nats-organizers header):
        for value in sheets_service.spreadsheets().values().get(
                spreadsheetId=spreadsheet_id,
                range='%s:%s' % (column_name, column_name),
                majorDimension='COLUMNS').execute()['values'][0][2:]:
            if value == 'END_IMPORT':
                break
            if value:
                all_staff_email_addresses.add(clean_email(value))

        UpdateMailingList(all_staff_email_addresses, directory_service,
                          '*****@*****.**')
        self.response.write('ok')
Ejemplo n.º 16
0
 webapp2.Route('/about/who',
               handler=BasicHandler('about_who.html'),
               name='about_who'),
 webapp2.Route('/about/donations',
               handler=BasicHandler('donations.html'),
               name='about_donations'),
 webapp2.Route(
     '/about/documents', handler=DocumentsHandler, name='documents'),
 webapp2.Route(
     '/about/get_document/<document_id:.*>/<document_name:.*>',
     handler=GetDocumentHandler,
     name='get_document'),
 webapp2.Route(
     '/about/logo', handler=BasicHandler('logo.html'), name='logo'),
 webapp2.Route('/about/contact',
               handler=ContactHandler(AppSettings.Get().contact_email,
                                      'contact.html', 'CubingUSA'),
               name='contact'),
 webapp2.Route('/newengland',
               handler=BasicHandler('newengland.html'),
               name='newengland'),
 webapp2.Route(
     '/app',
     handler=webapp2.RedirectHandler,
     defaults={'_uri': 'https://cubingusa.org/nationals/2019/app'}),
 webapp2.Route(
     '/results',
     handler=webapp2.RedirectHandler,
     defaults={'_uri': 'https://cubecomps.cubing.net/live.php'}),
 # Async
 webapp2.Route(
Ejemplo n.º 17
0
 webapp2.Route('/logout', handler=LogoutHandler, name='logout'),
 webapp2.Route('/edit', handler=EditUserHandler, name='edit_user'),
 webapp2.Route('/edit/<user_id:.*>', handler=EditUserHandler, name='edit_user_by_id'),
 webapp2.Route('/regional', handler=BasicHandler('regional.html'), name='competitions_regional'),
 webapp2.Route('/supported', handler=BasicHandler('supported.html'), name='supported'),
 webapp2.Route('/state_rankings', handler=BasicHandler('state_rankings.html', include_wca_disclaimer=True),
               name='state_rankings'),
 webapp2.Route('/about', handler=BasicHandler('about.html'), name='about'),
 webapp2.Route('/about/who', handler=BasicHandler('about_who.html'), name='about_who'),
 webapp2.Route('/about/donations', handler=BasicHandler('donations.html'), name='about_donations'),
 webapp2.Route('/about/documents', handler=DocumentsHandler, name='documents'),
 webapp2.Route('/about/get_document/<document_id:.*>/<document_name:.*>',
               handler=GetDocumentHandler, name='get_document'),
 webapp2.Route('/about/logo', handler=BasicHandler('logo.html'), name='logo'),
 webapp2.Route('/about/contact',
               handler=ContactHandler(AppSettings.Get().contact_email, 'contact.html', 'CubingUSA'),
               name='contact'),
 # Async
 webapp2.Route('/async/champions_by_year/<event_id:.*>/<championship_type:.*>/<championship_region:.*>',
               handler=ChampionsByYearHandler),
 webapp2.Route('/async/state_rankings/<event_id:.*>/<state_id:.*>/<use_average:\d>',
               handler=StateRankingsHandler),
 # Admin
 webapp2.Route('/admin/edit_users',
               handler=BasicHandler('admin/edit_users.html',
                                    permitted_roles=Roles.AllRoles()),
               name='admin_edit_users'),
 webapp2.Route('/admin/upload_document', handler=UploadDocumentHandler,
               name='upload_document'),
 webapp2.Route('/admin/delete_document/<document_id:.*>', handler=DeleteDocumentHandler,
               name='delete_document'),
Ejemplo n.º 18
0
 def app_settings(self):
   return AppSettings.Get()