Example #1
0
def validate_tokens(json):
    assert "access_token" in json
    assert "refresh_token" in json

    access_token = Token.select().where(Token.token_type == "access").get()
    assert json["access_token"]["token"] == access_token.token
    assert (json["access_token"]["valid_until"] >
            datetime.datetime.now().timestamp() + 60 * 60 * 24 * 29)

    assert (json["access_token"]["valid_until"] <
            datetime.datetime.now().timestamp() + 60 * 60 * 24 * 31)

    assert User.get() == access_token.user

    refresh_token = Token.select().where(Token.token_type == "refresh").get()
    assert json["refresh_token"]["token"] == refresh_token.token
    assert (json["refresh_token"]["valid_until"] >
            datetime.datetime.now().timestamp() + 60 * 60 * 24 * 89)

    assert (json["refresh_token"]["valid_until"] <
            datetime.datetime.now().timestamp() + 60 * 60 * 24 * 91)

    assert User.get() == refresh_token.user

    assert refresh_token.token != access_token.token
Example #2
0
def seed_admin():
    print("add admin user")
    db = get_db()
    user = User()
    user.username = '******'
    user.password_hash = generate_password_hash(current_app.config['ADMIN_PASSWORD'])
    db.add(user)
    db.commit()
Example #3
0
def put():
    if request.get_json() is None:
        abort(http.HTTPStatus.BAD_REQUEST)
    try:
        body = request.get_json()
        obj = User()
        obj.dictToUser(body)
        obj = service.update(obj)
        return jsonify(obj.userToJson())
    except Exception:
        abort(http.HTTPStatus.INTERNAL_SERVER_ERROR)
Example #4
0
def test_user_repo_get_user_list_should_all(session):
    for _ in range(20):
        fake = Faker()
        data = {"email": fake.email(), "password": fake.name()}
        User.create(**data)

    page = 1

    res = UserRepository().get_all(page)

    assert len(res.items) == 10
Example #5
0
def register():
    """Регистрация"""
    json = request.get_json()

    missed_payload = []

    if "username" not in json:
        missed_payload.append("username")
    if "password" not in json:
        missed_payload.append("password")
    if "email" not in json:
        missed_payload.append("email")
    if "name" not in json:
        missed_payload.append("name")

    if len(missed_payload) > 0:
        return errors.wrong_payload(missed_payload)

    username = json["username"]
    password = json["password"]
    email = json["email"]
    name = json["name"]

    user = User.get_or_none(User.username == username)
    if user is not None:
        return errors.registration_username_busy()
    user = User.get_or_none(User.email == email)
    if user is not None:
        return errors.registration_email_busy()

    user = User.create(
        username=username,
        password=salted(password, current_app.config["PASSWORD_SALT"]),
        email=email,
        registration_date=datetime.datetime.now(),
        last_active_date=datetime.datetime.now(),
        name=name,
    )

    token = Token.generate_access_token(user)
    refresh_token = Token.generate_refresh_token(user)

    return jsonify({
        "success": 1,
        "access_token": {
            "token": token.token,
            "valid_until": token.valid_until.timestamp(),
        },
        "refresh_token": {
            "token": refresh_token.token,
            "valid_until": refresh_token.valid_until.timestamp(),
        },
    })
def inserirusuario():
    if request.get_json() is None:
        abort(http.HTTPStatus.BAD_REQUEST)
    try:
        body = request.get_json()
        obj = User()
        obj.dictToUser(body)
        service.inserirusuario(obj)
        if (obj.id is None):
            raise Exception('Não autorizado')
        return jsonify(obj.userToJson())
    except Exception:
        abort(http.HTTPStatus.BAD_REQUEST)
Example #7
0
def inseriradmin():
    if not service.isAdmin():
        abort(http.HTTPStatus.UNAUTHORIZED)
    if request.get_json() is None:
        abort(http.HTTPStatus.BAD_REQUEST)
    try:
        body = request.get_json()
        obj = User()
        obj.dictToUser(body)
        service.inserirusuario(obj)
        return jsonify(obj.userToJson())
    except Exception:
        abort(http.HTTPStatus.INTERNAL_SERVER_ERROR)
Example #8
0
def current_user():
    """Получить текущего пользователя или отредактировать профиль"""
    user = get_user_from_request()

    if request.method == "POST":
        json = request.get_json()

        user.email = json.get("email", user.email)
        user.name = json.get("name", user.name)
        user.about = sanitize(json.get("about", user.about))
        user.birthday = json.get("birthday", user.birthday)
        if "avatar" in json:
            content = Content.get_or_none(Content.id == json["avatar"])
            if content:
                if not content.is_image:
                    return errors.user_avatar_is_not_image()
                elif content.size > 1024 * 500:  # 500kb
                    return errors.user_avatar_too_large()
                else:
                    user.avatar = content

        user.save()

    user = User.get(User.id == user.id)

    return jsonify({"success": 1, "user": user.to_json_with_email()})
def removeruser():
    if request.get_json() is None:
        abort(http.HTTPStatus.BAD_REQUEST)
    try:
        body = request.get_json()
        obj = User()
        obj.dictToUser(body)
        obj = service.findById(obj.id)
        if (obj.id is None):
            raise ModuleNotFoundError('Não encontrado')
        service.remove(obj)
        return jsonify(obj.userToJson())
    except ModuleNotFoundError:
        abort((http.HTTPStatus.NO_CONTENT))
    except Exception:
        abort(http.HTTPStatus.BAD_REQUEST)
Example #10
0
def dashboard():
    """Получить статистику по сайту"""
    user = get_user_from_request()

    if not user.is_admin:
        return errors.no_access()

    users = User.select().count()

    d = datetime.datetime.now() - datetime.timedelta(days=7)
    active_users = User.select().where(User.last_active_date > d).count()
    return jsonify({
        "success": 1,
        "users": users,
        "active_users_7_days": active_users
    })
Example #11
0
def leave_feedback():
    """Оставить отзыв"""
    json = request.get_json()
    if "text" in json:
        Feedback.create(text=json["text"], user=get_user_from_request())

        Telegram(current_app.config).notify_admin_channel(
            "Пользователь %s оставил отзыв: %s"
            % (get_user_from_request().username, json["text"])
        )

        success = Trello(current_app.config).create_card(json["text"])
        if not success:
            return errors.feedback_trello_error()

        for user in User.get_admins():
            Notification.create(
                user=user,
                created_date=datetime.datetime.now(),
                text="Пользователь %s оставил отзыв: %s"
                % (get_user_from_request().username, json["text"]),
                object_type="feedback",
            )

        return jsonify({"success": 1})
    else:
        return errors.wrong_payload("text")
Example #12
0
def test_registration_failure(client):
    rv = client.post("/users/register/", json={})
    assert rv.status_code == 400
    assert rv.json["success"] == 0
    assert "token" not in rv.json
    assert User.select().count() == 0
    assert Token.select().count() == 0
Example #13
0
def convert():
    create_app()

    for v in TuVote.select():
        creator = User.get_or_none(User.id == v.user_voter)
        if not creator:
            print("Skipped vote. Owner:" +
                  TuUser.get(TuUser.user == v.user_voter).user_login)
            continue

        t_id = v.target
        t_type = 1
        if v.target_type == "user":
            t_type = 1
        elif v.target_type == "blog":
            t_type = 2
        elif v.target_type == "topic":
            t_type = 3
        elif v.target_type == "comment":
            t_type = 4

        value = 1 if v.vote_direction > 0 else -1

        Vote.create(
            target_id=t_id,
            target_type=t_type,
            voter=creator,
            vote_value=value,
            created_date=v.vote_date,
            updated_date=v.vote_date,
        )
Example #14
0
def unassign_achievement():
    user = get_user_from_request()

    if not user.is_admin:
        return errors.no_access()

    json = request.get_json()

    if "users" not in json or "achievement" not in json:
        return errors.wrong_payload("users", "achievement")

    if len(json["users"]) == 0:
        return errors.wrong_payload("users")

    achievement = Achievement.get_or_none(
        Achievement.id == json["achievement"])
    if achievement is None:
        return errors.wrong_payload("achievement")

    assign_errors = []
    for u in json["users"]:
        user_to_unassign = User.get_or_none(User.id == u)
        if user_to_unassign is None:
            assign_errors.append(f"Cannot unassign achievement from user {u}")
        else:
            assign = AchievementUser.get_or_none(achievement=achievement,
                                                 user=user_to_unassign)
            assign.delete_instance()

    return jsonify({"success": 1, "errors": assign_errors})
Example #15
0
def blog(user, reader_token):
    blog = Blog.create(
        title="test_blog",
        url="test_blog",
        creator=user,
        created_date=datetime.datetime.now(),
        updated_date=datetime.datetime.now(),
    )
    BlogParticipiation.create(blog=blog, user=user, role=1)

    writer = User.create(
        username="******",
        password="******",
        email="asd",
        registration_date=datetime.datetime.now(),
        last_active_date=datetime.datetime.now(),
    )
    BlogParticipiation.create(blog=blog, user=writer, role=2)

    BlogParticipiation.create(blog=blog, user=reader_token[0], role=3)

    from src.model import db

    db.db_wrapper.database.close()

    return blog
Example #16
0
def users():
    for i in range(30):
        User.create(
            username="******" + str(i),
            password="******",
            email="asd" + str(i),
            registration_date=datetime.datetime.now(),
            last_active_date=datetime.datetime.now(),
            name="name",
            birthday=datetime.date.today(),
            about="",
            avatar=None,
        )

    from src.model import db

    db.db_wrapper.database.close()
Example #17
0
def invites(url):
    """Пригласить пользователя или принять инвайт"""
    blog = Blog.get_or_none(Blog.url == url)
    if blog is None:
        return errors.not_found()

    user = get_user_from_request()

    json = request.get_json()

    if "invite" in json:
        invite = BlogInvite.get_or_none(BlogInvite.id == json["invite"])
        if invite is None:
            return errors.invite_not_found()

        if invite.user_to.id != user.id:
            return errors.no_access()

        invite.is_accepted = True
        invite.save()

        BlogParticipiation.create(blog=invite.blog, user=user, role=invite.role)

        return jsonify({"success": 1})
    elif "user" in json and "role" in json:
        user_to = User.get_or_none(User.id == json["user"])
        if user_to is None:
            return errors.not_found()

        role = Blog.get_user_role(blog, user)

        if role is None:
            return errors.no_access()

        role_to = json["role"]
        roles = {"owner": 1, "writer": 2, "reader": 3}

        if role_to not in roles:
            return errors.invite_wrong_role()

        role_to = roles[role_to]
        if role > role_to:
            return errors.no_access()

        invite = BlogInvite.create(
            blog=blog, user_from=user, user_to=user_to, role=role_to
        )

        Notification.create(
            user=user,
            created_date=datetime.datetime.now(),
            text='Вас пригласили в блог "{0}"'.format(blog.title),
            object_type="invite",
            object_id=invite.id,
        )

        return jsonify({"success": 1, "invite": invite.id})
Example #18
0
def login():
    """Авторизация"""
    json = request.get_json()

    has_login = "******" in json or "email" in json
    has_password = "******" in json
    if not has_login:
        return errors.wrong_payload("username", "email")
    if not has_password:
        return errors.wrong_payload("password")

    user = None
    if "username" in json:
        username = json["username"]

        user = User.get_or_none(User.username == username)
        if user is None:
            user = User.get_or_none(User.email == username)
    elif "email" in json:
        email = json["email"]

        user = User.get_or_none(User.username == email)
        if user is None:
            user = User.get_or_none(User.email == email)

    password = json["password"]

    if user is not None and authorize(user, password):
        token = Token.generate_access_token(user)
        refresh_token = Token.generate_refresh_token(user)

        return jsonify({
            "success": 1,
            "access_token": {
                "token": token.token,
                "valid_until": token.valid_until.timestamp(),
            },
            "refresh_token": {
                "token": refresh_token.token,
                "valid_until": refresh_token.valid_until.timestamp(),
            },
        })

    return errors.not_authorized()
Example #19
0
    def register(data: dict) -> bool:

        if not validate_user_data(data):
            return False

        user = User(**data)
        if not UserRepository.create(user):
            return False

        return True
Example #20
0
def user(username):
    """Получить подробную информацию о пользователе"""
    user = User.get_or_none(User.username == username)

    if user is None:
        return errors.not_found()

    user_dict = user.to_json()
    user_dict = Vote.add_votes_info(user_dict, 1, get_user_from_request())
    user_dict = Achievement.add_achievements(user_dict)

    return jsonify({"success": 1, "user": user_dict})
Example #21
0
def user_jams(username):
    """Получить список джемов, которые пользователь организовал"""
    user = User.get_or_none(User.username == username)

    if user is None:
        return errors.not_found()

    query = Jam.get_jams_organized_by_user(user)

    jams = [e.to_json() for e in query]

    return jsonify({"success": 1, "jams": jams})
Example #22
0
def test_registration_not_all_data(client):
    rv = client.post("/users/register/",
                     json={
                         "username": "******",
                         "password": "******"
                     })
    assert rv.status_code == 400
    assert rv.json["success"] == 0
    assert "token" not in rv.json
    assert rv.json["error"]["code"] == 5
    assert User.select().count() == 0
    assert Token.select().count() == 0
Example #23
0
def convert():
    create_app()

    pattern = r".*?getDisplayName\(\) == '(?P<username>.*?)'}(?P<meta>.*?)<img.*src=\"(?P<image>.*?)\" title=['\"](?P<title>.*)['\"]"  # noqa

    achievements = []

    image_base_path = "/var/www/old.kolenka"

    creator = User.get_or_none(User.username == "Xitilon")

    lines = old_ach.split("\n")
    for line in lines:
        m = re.search(pattern, line)
        if m:
            username = m.group("username")

            user = User.get_or_none(User.username == username)
            if user is None:
                print(f"Cannot find user {username}")
                continue

            image = m.group("image")
            title = m.group("title")
            meta = m.group("meta")

            created_achivement = None
            for a in achievements:
                if a.title == title:
                    created_achivement = a
                    break
            if created_achivement is None:
                img = content.upload_image(creator.id, 2020, 3, image_base_path + image)
                created_achivement = Achievement.create(title=title, image=img)
                achievements.append(created_achivement)
            else:
                img = created_achivement.image
            AchievementUser.create(
                achievement=created_achivement, user=user, comment=meta
            )
Example #24
0
def get_achievements():
    """Получить список наград"""
    achievements = Achievement.select()

    achievements = [a.to_json() for a in achievements]
    for a in achievements:
        users = (User.select(User.id, User.username).join(
            AchievementUser, peewee.JOIN.LEFT_OUTER).where(
                AchievementUser.achievement == a["id"]))

        a["users"] = [u.to_json() for u in users]

    return jsonify({"success": 1, "achievements": achievements})
Example #25
0
def test_user_repo_delete_with_id_should_success(session):
    data = {"email": "test", "password": "******"}
    data = User(**data)
    session.add(data)
    session.commit()

    id = User.id
    UserRepository.delete(id)

    res = session.query(User).filter(
        User.id == id).first()  # User.email은 왜 안될까.

    assert res is None
Example #26
0
def test_user_usecase_get_user_list(mock_method, session):
    data_list = []
    for _ in range(20):
        fake = Faker()
        data = {"email": fake.email(), "password": fake.name()}
        data_list.append(User(**data))
    session.add_all(data_list)
    session.commit()

    res = session.query(User).order_by(User.id.desc()).paginate(1, 10)
    mock_method.return_value = res
    page = 1
    res = UserUseCase().get_all(page)
    assert res is not None
Example #27
0
def test_registration(client):
    rv = client.post(
        "/users/register/",
        json={
            "username": "******",
            "password": "******",
            "name": "name",
            "email": "email",
        },
    )
    assert User.select().count() == 1
    assert rv.status_code == 200
    assert rv.json["success"] == 1
    validate_tokens(rv.json)
Example #28
0
def other_user_and_token():
    user = User.create(
        username="******",
        password="******",
        email="asd",
        registration_date=datetime.datetime.now(),
        last_active_date=datetime.datetime.now(),
    )

    token = Token.generate_access_token(user)

    from src.model import db

    db.db_wrapper.database.close()

    return [user, token]
Example #29
0
def test_registration_email_busy(client, user):
    rv = client.post(
        "/users/register/",
        json={
            "username": "******",
            "password": "******",
            "name": "name",
            "email": "asd",
        },
    )
    assert rv.status_code == 400
    assert rv.json["success"] == 0
    assert "token" not in rv.json
    assert rv.json["error"]["code"] == 12
    assert User.select().count() == 1
    assert Token.select().count() == 0
Example #30
0
def users():
    """Получить список пользователей"""
    query = User.get_users_sorted_by_active_date()
    limit = max(1, min(int(request.args.get("limit") or 20), 100))
    paginated_query = PaginatedQuery(query, paginate_by=limit)

    users = [u.to_json() for u in paginated_query.get_object_list()]
    users = [Vote.add_votes_info(u, 1, get_user_from_request()) for u in users]

    return jsonify({
        "success": 1,
        "users": users,
        "meta": {
            "page_count": paginated_query.get_page_count()
        },
    })