Пример #1
0
 def get_user(self) -> dict:
     resp = discord.get(
         DISCORD_API_ENDPOINT + "/users/@me"
     )  # 'discord' is a request.Session with oauth information
     if resp.status_code != 200:
         logging.warning("Unable to get user information: " +
                         str(resp.json()))
     return resp.json()
Пример #2
0
def get_verification_form():
  if not discord.authorized:
    return redirect(url_for('discord.login'))

  user = discord.get('/api/users/@me').json()
  if check_user_verified(user['id']):
    return 'You are already verified, please contact us if you want to change your details.'

  return render_template('verification.html', server_name=config.APP_SERVER_NAME)
Пример #3
0
def test_context_local(make_app):
    responses.add(responses.GET, "https://google.com")

    # set up two apps with two different set of auth tokens
    app1 = make_app(
        "foo1",
        "bar1",
        redirect_to="url1",
        storage=MemoryStorage({"access_token": "app1"}),
    )
    app2 = make_app(
        "foo2",
        "bar2",
        redirect_to="url2",
        storage=MemoryStorage({"access_token": "app2"}),
    )

    # outside of a request context, referencing functions on the `discord` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        discord.get("https://google.com")

    # inside of a request context, `discord` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        app1.preprocess_request()
        discord.get("https://google.com")
        request = responses.calls[0].request
        assert request.headers["Authorization"] == "Bearer app1"

    with app2.test_request_context("/"):
        app2.preprocess_request()
        discord.get("https://google.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
Пример #4
0
def test_context_local(make_app):
    responses.add(responses.GET, "https://google.com")

    # set up two apps with two different set of auth tokens
    app1 = make_app(
        "foo1",
        "bar1",
        redirect_to="url1",
        storage=MemoryStorage({"access_token": "app1"}),
    )
    app2 = make_app(
        "foo2",
        "bar2",
        redirect_to="url2",
        storage=MemoryStorage({"access_token": "app2"}),
    )

    # outside of a request context, referencing functions on the `discord` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        discord.get("https://google.com")

    # inside of a request context, `discord` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        app1.preprocess_request()
        discord.get("https://google.com")
        request = responses.calls[0].request
        assert request.headers["Authorization"] == "Bearer app1"

    with app2.test_request_context("/"):
        app2.preprocess_request()
        discord.get("https://google.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
Пример #5
0
        def join_guild():
            user = discord.get('/api/users/@me').json()

            if not current_user.discord_id:
                current_user.discord_id = user['id']
            elif current_user.discord_id != user['id']:
                flash(
                    'You re-authenticated with a Discord account different from the account linked to your account. '
                    'To connect a different account, disconnect your existing account first.',
                    FLASH_ERROR)
                return

            current_user.discord_username = user['username']
            current_user.discord_discriminator = user['discriminator']
            db.session.commit()
            r = put('https://discordapp.com/api/guilds/{}/members/{}'.format(
                app.config['DISCORD_VERIFICATION_GUILD'], user['id']),
                    json={
                        'access_token': discord.access_token,
                        'roles': [app.config['DISCORD_VERIFICATION_ROLE']],
                        'nick': current_user.kerberos
                    },
                    headers=authorization)
            if r.status_code == 204:
                r = put(
                    'https://discordapp.com/api/guilds/{}/members/{}/roles/{}'.
                    format(app.config['DISCORD_VERIFICATION_GUILD'],
                           user['id'],
                           app.config['DISCORD_VERIFICATION_ROLE']),
                    headers=authorization)
            if r.status_code not in [201, 204]:
                flash(
                    'There was an error granting you access to the Discord server. Please wait a bit and '
                    'click the "Rejoin" button below to try again. If this issue persists, please contact '
                    '<a href="mailto:[email protected]">[email protected]</a> for assistance.',
                    FLASH_ERROR)
                return
            flash(
                'Success! You now have access to the Next House Discord server.',
                FLASH_SUCCESS)
            return
Пример #6
0
def post_verification_form():
  if not discord.authorized:
    return redirect(url_for('discord.login'))
  
  user = discord.get('/api/users/@me').json()
  if check_user_verified(user['id']):
    return 'You are already verified, please contact us if you want to change your details.'

  data = validate_form(request.form)
  code = str(uuid.uuid4())

  # TODO: validation
  with open(f'data/{user["id"]}', 'w') as f:
    f.write(json.dumps({
      **data,
      'verified': False,
      'code': code,
      'discord_id': user['id'],
      'discord_name': f'{user["username"]}#{user["discriminator"]}'
    }))
  
  if data['automated']:
    send_email(data['email'], f'{config.APP_SERVER_NAME} Discord Verification', EMAIL_TEMPLATE_AUTO.format(
      name=data['name'],
      server_name=config.APP_SERVER_NAME,
      contact_email=config.APP_CONTACT_EMAIL,
      verification_url=f'{config.APP_BASE_URL}/verification/link/{user["id"]}/{code}'
    ))
  else:
    send_email(data['email'], f'Manual {config.APP_SERVER_NAME} Discord Verification', EMAIL_TEMPLATE_NOAUTO.format(
      name=data['name'],
      server_name=config.APP_SERVER_NAME,
      contact_email=config.APP_CONTACT_EMAIL,
    ), config.APP_CONTACT_EMAIL)

  return 'Please check your email for an activation link.'
Пример #7
0
def index():
    kerb = getenv('SSL_CLIENT_S_DN_Email').split('@')[0]
    try:
        connection = connect(user=config['database']['username'],
                             password=config['database']['password'],
                             host=config['database']['host'],
                             database=config['database']['database'])
    except Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            return render_template(
                BASE_TEMPLATE,
                message=
                ('The database could not be loaded. Verify that the username '
                 'and password is correct.')), 500
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            return render_template(
                BASE_TEMPLATE,
                message=
                ('The database could not be loaded. Verify that the database '
                 'exists.')), 500
        else:
            return render_template(
                BASE_TEMPLATE,
                message=(
                    'The database could not be loaded. Please contact '
                    '<a href="mailto:[email protected]">[email protected]'
                    '</a> for assistance.')), 500
    # Check if kerb is in bot table. If it is, set user_id from there. If not, check submissions for kerb. If kerb
    # doesn't exist, we go to the error way at the bottom. If it does exist, create a new record in bot with kerb set.
    # Set user_id to None.
    cursor = connection.cursor()
    cursor.execute("SELECT EXISTS(SELECT * FROM bot WHERE kerberos = %s)",
                   (kerb, ))
    kerb_in_bot = cursor.fetchone()[0]

    if kerb_in_bot:
        cursor.execute("SELECT user_id FROM bot WHERE kerberos = %s", (kerb, ))
        user_id = cursor.fetchone()[0]
    else:
        cursor.execute(
            "SELECT EXISTS(SELECT * FROM " + submissions +
            " WHERE kerberos = %s)", (kerb, ))
        if not cursor.fetchone()[0]:
            connection.close()
            return render_template(
                BASE_TEMPLATE,
                message=
                ('You are not on the list of representatives for the CPW 2020 '
                 'Discord server. If this is an error, please contact the other '
                 'representatives of your student organization.')), 401
        cursor.execute("INSERT INTO bot (kerberos) VALUES (%s)", (kerb, ))
        connection.commit()
        user_id = None
    if discord.authorized:
        user = discord.get('/api/users/@me').json()
        if not user_id:
            # Update the database so that in the bot table, the kerb has user id (stored in user['id']).
            cursor.execute("UPDATE bot SET user_id = %s WHERE kerberos = %s",
                           (user['id'], kerb))
            connection.commit()
        elif user['id'] != user_id:
            connection.close()
            return render_template(
                BASE_TEMPLATE,
                message=(
                    "Your current Discord account doesn't match what we "
                    'have on record. Please log into the account you used '
                    'previously. Please contact [email protected] if '
                    'this is an error.')), 403
        connection.close()
        ldap = get_ldap(kerb)
        roles = [
            config['discord']['verified'],
            config['discord']['roles'][ldap['eduPersonAffiliation']]
        ]
        if ldap['eduPersonAffiliation'] == 'student':
            roles.append(config['discord']['roles'][ldap['mitDirStudentYear']])
        r = put('https://discordapp.com/api/guilds/{}/members/{}'.format(
            config['discord']['guild'], user['id']),
                json={
                    'access_token': discord.access_token,
                    'roles': roles
                },
                headers=authorization)
        if r.status_code in [201, 204]:
            if r.status_code == 204:
                for i in roles:
                    r = put(
                        'https://discordapp.com/api/guilds/{}/members/{}/roles/{}'
                        .format(config['discord']['guild'], user['id'], i),
                        headers=authorization)
                    if r.status_code != 204:
                        return render_template(
                            BASE_TEMPLATE,
                            message=(
                                'There was an error granting you access to '
                                'the Discord server. Please contact '
                                '<a href="mailto:[email protected]">'
                                '[email protected]</a> for assistance.'
                            )), 500
            return render_template(
                BASE_TEMPLATE,
                message=(
                    'You should now have access to the CPW 2020 Discord '
                    'server! If you are having problems, please contact us at '
                    '<a href="mailto:[email protected]">'
                    '[email protected]</a> for assistance.'))
        return render_template(
            BASE_TEMPLATE,
            message=(
                'There was an error granting you access to the Discord '
                'server. Please contact '
                '<a href="mailto:[email protected]">[email protected]'
                '</a> for assistance.')), 500
    return render_template(
        BASE_TEMPLATE,
        message=('You\'re one step away from accessing the CPW 2020 Discord '
                 'server! Please <a href="discord">click here</a> to '
                 'authenticate with Discord and verify your Discord account.'))