Exemplo n.º 1
0
def api_login():
    headers = {}
    lsession = request.headers.get('LSESSION', None)
    if not lsession:
        lsession = db.create_new_session()
        headers['LSESSION'] = lsession
    if not request.form['email'] or not request.form['password']:
        body = {
            'error': 'missingFields',
            'details': 'Must include email and password'
        }
        return (body, 400, headers)

    email_provided = request.form['email']
    if not db.password_matches(email_provided, request.form['password']):
        print(email_provided, request.form['password'])
        body = {
            'error': 'passwordInvalid',
            'details': 'Password was not valid'
        }
        return (body, 400, headers)

    member_id = db.get_member_by_email(email_provided)
    db.associate_session_with_user(lsession, member_id, request.remote_addr,
                                   request.headers['User-Agent'])
    token = db.add_token(lsession)
    headers['Set-Cookie'] = f'token={token}; Path=/; HttpOnly'
    body = {'error': 'None', 'details': 'Member logged in successfully'}
    return (body, 200, headers)
Exemplo n.º 2
0
 async def link(self, ctx):
     """
     Link a spotify account to the bot.
     """
     if not is_linked(ctx.author.id):
         token = str(uuid.uuid4())
         valid_until = int(
             (datetime.utcnow() + timedelta(days=1)).timestamp())
         add_token(ctx.author.display_name, ctx.author.id, token,
                   valid_until, str(ctx.author.avatar_url))
         web_base_url = get_setting('web_base_url')
         await ctx.author.send(
             f"Please visit {web_base_url}/link/{token} to link your Spotify account. "
             f"This link will expire after 24 hours.")
         if ctx.guild is not None:
             await ctx.message.add_reaction('📬')
     else:
         await ctx.reply("You have already linked a spotify account!")
Exemplo n.º 3
0
def add_token():
    '''Add token'''

    email = request.form['email']
    token = request.form['token']
    if db.add_token(CONN, email, token):
        return jsonify('success')
    else:
        return jsonify('failed')
Exemplo n.º 4
0
def api_join():
    headers = {}

    # Ensure user has a session
    lsession = request.headers.get('LSESSION')
    if lsession is None:  # New user or cookies have been cleared
        lsession = db.create_new_session()
    headers['LSESSION'] = lsession

    # Check fields
    required_fields = {'email', 'password', 'confirm_password'}
    received_fields = set(request.form.keys())
    if received_fields.intersection(required_fields) != required_fields:
        body = {
            'error':
            'Missing fields',
            'details': (f"Fields required: {', '.join(required_fields)}, ",
                        f"Fields received: {', '.join(received_fields)}")
        }
        return (body, 400, headers)

    # Validate password
    pw = request.form.get('password')
    conf_pw = request.form.get('confirm_password')
    if pw != conf_pw:
        body = {
            'error': 'passwordMismatch',
            'details': (f"{pw} != {conf_pw} (password vs confirmation)")
        }
        return (body, 400, headers)

    # Add new member
    try:
        member_id = db.add_new_member(request.form['email'],
                                      request.form['password'])
    except db.InvalidEmailException as iee:
        body = {'error': 'invalidEmail', 'details': str(iee)}
        return (body, 400, headers)

    if member_id == None:  # Failed to create a new member
        body = {
            'error': 'joinFailed',
            'details': 'Failed to create new member'
        }
        return (body, 400, headers)

    # Associate session with user
    user_agent = request.headers['User-Agent']
    db.associate_session_with_user(lsession, member_id, request.remote_addr,
                                   user_agent)
    token_id = db.add_token(lsession)
    headers['Set-Cookie'] = f'token={token_id}; Path=/; HttpOnly'
    body = {'error': 'None', 'details': 'Member created successfully'}
    return (body, 200, headers)
Exemplo n.º 5
0
def do_signin():
    '''Sign in'''
    email = request.form['email']
    password = request.form['password']
    if db.valid_user(CONN, email, password):
        token = email + str(uuid.uuid1())
        while not db.add_token(CONN, email, token):
            token = email + str(uuid.uuid1())
        resp = jsonify("success")
        resp.set_cookie("token", token, max_age=360000)
    else:
        resp = jsonify("failed")
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp