Esempio n. 1
0
def add_user(email, admin, password):
    """Add a new user to the database with email address = EMAIL."""
    if User.find_by_email(email):
        error = f"Error: {email} is already registered"
        click.secho(f"{error}\n", fg="red", bold=True)
        return 1

    new_user = User(email=email, password=password, admin=admin)
    db.session.add(new_user)
    db.session.commit()
    user_type = "admin user" if admin else "user"
    message = f"Successfully added new {user_type}:\n {new_user}"
    click.secho(message, fg="blue", bold=True)
    return 0
Esempio n. 2
0
def process_registration_request(email, password):
    if User.find_by_email(email):
        abort(HTTPStatus.CONFLICT,
              f"{email} is already registered",
              status="fail")
    new_user = User(email=email, password=password)
    db.session.add(new_user)
    db.session.commit()
    access_token = new_user.encode_access_token()
    return _create_auth_successful_response(
        token=access_token.decode(),
        status_code=HTTPStatus.CREATED,
        message="successfully registered",
    )
Esempio n. 3
0
def test_login(client, db):
    register_user(client)
    response = login_user(client)
    assert response.status_code == HTTPStatus.OK
    assert "status" in response.json and response.json["status"] == "success"
    assert "message" in response.json and response.json["message"] == SUCCESS
    assert "access_token" in response.json

    access_token = response.json["access_token"]
    result = User.decode_access_token(access_token)
    assert result.success
    token_payload = result.value
    assert not token_payload["admin"]
    user = User.find_by_public_id(token_payload["public_id"])
    assert user and user.email == EMAIL
Esempio n. 4
0
def get_logged_in_user():
    public_id = get_logged_in_user.public_id
    user = User.find_by_public_id(public_id)
    expires_at = get_logged_in_user.expires_at
    user.token_expires_in = format_timespan_digits(
        remaining_fromtimestamp(expires_at))
    return user
Esempio n. 5
0
def test_decode_access_token_success(user):
    access_token = user.encode_access_token()
    result = User.decode_access_token(access_token)
    assert result.success

    user_dict = result.value
    assert user.public_id == user_dict["public_id"]
    assert user.admin == user_dict["admin"]
Esempio n. 6
0
def test_auth_register(client, db):
    response = register_user(client)
    assert response.status_code == HTTPStatus.CREATED
    assert "status" in response.json and response.json["status"] == "success"
    assert "message" in response.json and response.json["message"] == SUCCESS
    assert "token_type" in response.json and response.json[
        "token_type"] == "bearer"
    assert "expires_in" in response.json and response.json["expires_in"] == 5
    assert "access_token" in response.json

    access_token = response.json["access_token"]
    result = User.decode_access_token(access_token)
    assert result.success

    user_dict = result.value
    assert not user_dict["admin"]

    user = User.find_by_public_id(user_dict["public_id"])
    assert user and user.email == EMAIL
Esempio n. 7
0
def test_auth_register_email_already_registered(client, db):
    user = User(email=EMAIL, password=PASSWORD)
    db.session.add(user)
    db.session.commit()
    response = register_user(client)
    assert response.status_code == HTTPStatus.CONFLICT
    assert ("message" in response.json
            and response.json["message"] == EMAIL_ALREADY_EXISTS)
    assert "token_type" not in response.json
    assert "expires_in" not in response.json
    assert "access_token" not in response.json
Esempio n. 8
0
def process_login_request(email, password):
    user = User.find_by_email(email)
    if not user or not user.check_password(password):
        abort(HTTPStatus.UNAUTHORIZED,
              "email or password does not match",
              status="fail")
    access_token = user.encode_access_token()
    return _create_auth_successful_response(
        token=access_token.decode(),
        status_code=HTTPStatus.OK,
        message="successfully logged in",
    )
Esempio n. 9
0
def _check_access_token(admin_only):
    token = request.headers.get("Authorization")
    if not token:
        raise ApiUnauthorized(description="Unauthorized",
                              admin_only=admin_only)

    result = User.decode_access_token(token)

    if result.failure:
        raise ApiUnauthorized(
            description=result.error,
            admin_only=admin_only,
            error="invalid_token",
            error_description=result.error,
        )

    return result.value
Esempio n. 10
0
def test_decode_access_token_invalid(user):
    access_token = user.encode_access_token()
    split = access_token.split(b".")
    payload_base64 = split[1]
    pad_len = 4 - (len(payload_base64) % 4)
    payload_base64 += pad_len * b"="
    payload_str = urlsafe_b64decode(payload_base64)
    payload = json.loads(payload_str)
    assert not payload["admin"]

    payload["admin"] = True
    payload_mod = json.dumps(payload)
    payload_mod_base64 = urlsafe_b64encode(payload_mod.encode())
    split[1] = payload_mod_base64.strip(b"=")
    access_token_mod = b".".join(split)
    assert not access_token == access_token_mod

    result = User.decode_access_token(access_token_mod)
    assert not result.success
    assert result.error == "Invalid token. Please log in again."
Esempio n. 11
0
def create_widget(widget_dict):
    name = widget_dict["name"]

    if Widget.find_by_name(name):
        error = f"Widget name: {name} already exists, must be unique."
        abort(HTTPStatus.CONFLICT, error, status="fail")
    """
    ** is the dictionary unpacking operator,
    you can find more info on it and the related list unpacking operator (*)
    in PEP 448. It is a concise way to pass the name, info_url,
    and deadline values to the Widget constructor.
    """
    widget = Widget(**widget_dict)
    owner = User.find_by_public_id(create_widget.public_id)
    widget.owner_id = owner.id
    db.session.add(widget)
    db.session.commit()

    response = jsonify(status="success", message=f"New widget added: {name}.")
    response.status_code = HTTPStatus.CREATED
    response.headers["Location"] = url_for("api.widget", name=name)

    return response
Esempio n. 12
0
def test_decode_access_token_expired(user):
    access_token = user.encode_access_token()
    time.sleep(6)
    result = User.decode_access_token(access_token)
    assert not result.success
    assert result.error == "Access token expired. Please log in again."
Esempio n. 13
0
def admin(db):
    """ Create an admin test user """
    admin = User(email=ADMIN_EMAIL, password=PASSWORD, admin=True)
    db.session.add(admin)
    db.session.commit()
    return admin
Esempio n. 14
0
def user(db):
    """ Create a test user """
    user = User(email=EMAIL, password=PASSWORD)
    db.session.add(user)
    db.session.commit()
    return user