Ejemplo n.º 1
0
async def oauth_redirect():
    twitch = OAuth2Session(OAUTH_CLIENT_ID,
                           state=session["oauth_state"],
                           redirect_uri=OAUTH_REDIRECT_URL)
    token: OAuth2Token = await twitch.fetch_token(
        "https://id.twitch.tv/oauth2/token",
        include_client_id=True,
        client_secret=OAUTH_CLIENT_SECRET,
        authorization_response=request.url.replace("http://", "https://"),
    )
    resp = await twitch.get(
        "https://api.twitch.tv/helix/users",
        headers={
            "client-id": OAUTH_CLIENT_ID,
            "authorization": f"Bearer "
            f"{token.get('access_token')}",
        },
    )
    if resp.status == 200:
        body = await resp.json()
        user = body["data"][0]
        username = user["login"]
        log.info(f"Logging in as user {username}")
        login_user(AuthUser(username))
        return redirect(url_for("index"))
Ejemplo n.º 2
0
async def auth():
    data = await request.json
    user_id = str(uuid.uuid4())[:8]
    u = User(user_id)
    u.name = data['login'] or 'Anonymous' + user_id
    login_user(u)
    authorized_users.add(u)
    return {}
Ejemplo n.º 3
0
async def login() -> Any:
    if await current_user.is_authenticated:
        return redirect(url_for("ux.index"))

    if request.method == "GET":
        fluent = get_injector(["login"])
        return await render_template("login.html", **{"_": fluent.format_value})
    else:
        resources = [
            "login"
        ]
        fluent = get_injector(resources)

        form = await request.form

        username = form.get("username")
        password = form.get("password")
        if username is None or password is None:
            await flash(fluent._("form-missing-data"))
            return redirect(url_for("ux.login"))

        async with app.acquire_db() as con:
            await con.execute("""
                SELECT
                    id,
                    password_hash
                FROM
                    users
                WHERE LOWER(username) = ?;
            """, username.lower())
            user_data = await con.fetchone()

        if not user_data:
            await flash(fluent._("invalid-credentials"))
            return redirect(url_for("ux.login"))

        try:
            hasher.verify(user_data["password_hash"], password)
        except VerifyMismatchError:
            await flash(fluent._("invalid-credentials"))
            return redirect(url_for("ux.login"))

        if hasher.check_needs_rehash(user_data["password_hash"]):
            async with app.acquire_db() as con:
                await con.execute("""
                    UPDATE
                        users
                    SET
                        password_hash=?
                    WHERE username=?;
                """, hasher.hash(password), username)

        remember = form.get("remember", False)

        login_user(User(user_data["id"]), remember=remember)

        return redirect(url_for("ux.index"))
Ejemplo n.º 4
0
async def auth_login():
    """User login"""
    data = await request.json
    user_id = str(uuid.uuid4())[:8]
    user = User(user_id)
    user._name = data['login'] or f'Anonymous{user_id}'
    user.queue = asyncio.Queue()
    login_user(user, True)
    authorized_users.add(user)
    return jsonify({'id': user_id, 'name': await user.name}), 200
Ejemplo n.º 5
0
async def login():
    if request.method == "GET":
        return await render_template("auth/login.html")
    else:
        username = request.values.get("username", None)
        password = reqest.values.get("password", None)
        if username is None or password is None:
            abort(401)
        else:
            user = User.get_by_username(username)
            if user.verify_password(password):
                login_user(user)
            else:
                abort(403)
Ejemplo n.º 6
0
async def login():
    if await current_user.is_authenticated:
        return redirect(url_for("ux.index"))

    if request.method == "GET":
        return await render_template("login.html")
    else:
        form = await request.form

        username = form.get("username")
        password = form.get("password")
        if username is None or password is None:
            return abort(400, "Login Form missing required data.")

        async with app.db_pool.acquire() as con:
            user_data = await con.fetchrow(
                """
                SELECT
                    id,
                    password_hash
                FROM
                    users
                WHERE LOWER(username) = $1;
            """, username.lower())

        if not user_data:
            return abort(401, "Invalid username and password combination.")

        try:
            hasher.verify(user_data["password_hash"], password)
        except VerifyMismatchError:
            return abort(401, "Invalid username and password combination.")

        if hasher.check_needs_rehash(user_data["password_hash"]):
            async with app.db_pool.acquire() as con:
                await con.execute(
                    """
                    UPDATE
                        users
                    SET
                        password_hash=$1
                    WHERE username=$2;
                """, hasher.hash(password), username)

        remember = form.get("remember", False)

        login_user(User(user_data["id"]), remember=remember)

        return redirect(url_for("ux.index"))
Ejemplo n.º 7
0
async def login_post():
    form = LoginForm()
    if form["guest"].data:
        log.info("Logging in as a guest")
        login_user(AuthUser("guest"))
        return redirect(url_for("index"))
    else:
        github = OAuth2Session(OAUTH_CLIENT_ID,
                               redirect_uri=OAUTH_REDIRECT_URL)
        authorization_url, state = github.authorization_url(
            "https://id.twitch.tv/oauth2/authorize")

        # State is used to prevent CSRF, keep this for later.
        session["oauth_state"] = state
        return redirect(authorization_url)
Ejemplo n.º 8
0
async def try_login_user(username: str, password: str, remember_me: bool):
    """
    Try to login a user
    """

    # find the user
    check_user = await User.find_one({"username": username})
    if check_user is None:
        raise AuthenticationError("Wrong username")

    if not await asyncio.get_event_loop().run_in_executor(
            None, verify_password_for_user, check_user, password):
        raise AuthenticationError("Wrong password")

    login_user(UserProxy.from_db(check_user), remember_me)
Ejemplo n.º 9
0
async def login():
    if request.method == "POST":
        username = (await request.form)['username']
        password = (await request.form).get('password', '')
        user = await check_user(username, password)
        if user:
            login_user(AuthUser(user.id))
            return redirect(url_for("portal.portal"))
        await flash("username or password incorrect", "red")

    if (await current_user.is_authenticated):
        # if user is already logged in redirect to portal
        return redirect(url_for("portal.portal"))

    return await render_template("login.jinja2")
Ejemplo n.º 10
0
async def do_signup():
    if await current_user.is_authenticated:
        return {"error": "Can't signup while still logged in."}, 403

    msg = await request.json
    payload = signup_schema.load(msg)

    if not await auth.verify_signup_code(payload["token"]):
        return {"error": "Invalid signup code."}, 401

    # create a new user TODO: proper error checking and nicer response
    new_user = await auth.add_blank_user(payload["username"], payload["password"])

    # login user (so subsequent api calls will still work)
    quart_auth.login_user(auth.UserProxy.from_db(new_user))
    
    return '', 201