Exemplo n.º 1
0
def echo_controller(request):
    data = request[DATA]
    with session_scope() as session:
        # message = Message(data=data[MESSAGE])
        message = Message(data=data[MESSAGE], created=datetime.now())
        session.add(message)
    return create_response(request, OK, data)
Exemplo n.º 2
0
def get_contacts_controller(request):
    contact_list = []
    if request[DATA][MESSAGE]:
        user_name = request[DATA][MESSAGE]
        with session_scope() as session:
            user = session.query(User).filter_by(name=user_name).first()
            if user:
                user_id = user.id
                contacts = session.query(Contact).filter_by(user_id=user_id)
                for contact in contacts:
                    contact_list.append(contact.name)
                if contact_list:
                    response = create_response(request, ACCEPTED,
                                               {MESSAGE: str(contact_list)})
                else:
                    response = create_response(request, ACCEPTED,
                                               {MESSAGE: "Контакт лист пуст"})
            else:
                response = create_response(
                    request, CONFLICT,
                    {MESSAGE: f"Клиент {user_name} не зарегистрирован"})
    else:
        print("Не задано имя пользователя")
        response = create_response(request, CONFLICT,
                                   {MESSAGE: "Не задано имя пользователя"})
    return response
Exemplo n.º 3
0
def delete_message_controller(request):
    # message_id = request.get("message_id")
    message_id = request[DATA][MESSAGE]
    with session_scope() as session:
        message = session.query(Message).filter_by(id=message_id).first()
        session.delete(message)
    return create_response(request, OK)
Exemplo n.º 4
0
def registration_controller(request):
    errors = {}
    is_valid = True
    data = request.get(DATA)

    if PASSWORD not in data:
        errors.update({PASSWORD: "******"})
        is_valid = False
    if LOGIN not in data:
        errors.update({LOGIN: "******"})
        is_valid = False

    if not is_valid:
        # return create_response(request, WRONG_REQUEST, {"errors": errors})
        return create_response(request, WRONG_REQUEST, {MESSAGE: errors})
    hmac_obj = hmac.new(SECRET_KEY.encode(), data.get(PASSWORD).encode())
    password_digest = hmac_obj.hexdigest()
    with session_scope() as session:
        user_already_exists = session.query(User).filter_by(
            name=data.get(LOGIN))
        if user_already_exists.count():
            return create_response(request, CONFLICT, {
                MESSAGE:
                f"User with login '{data.get(LOGIN)}' already exists"
            })
        user = User(name=data.get(LOGIN), password=password_digest)
        session.add(user)
    token = login(request, user)
    return create_response(request, OK, {TOKEN: token})
Exemplo n.º 5
0
def authenticate(login, password):
    with session_scope() as session:
        user = session.query(User).filter_by(name=login).first()
        hmac_obj = hmac.new(SECRET_KEY.encode(), password.encode())
        password_digest = hmac_obj.hexdigest()
        if user and hmac.compare_digest(password_digest.encode(),
                                        user.password.encode()):
            return user
Exemplo n.º 6
0
def login(request, user):
    with session_scope() as session:
        hash_obj = hashlib.sha256()
        hash_obj.update(SECRET_KEY.encode())
        hash_obj.update(str(request[TIME]).encode())
        token = hash_obj.hexdigest()
        user_session = Session(user=user, token=token, created=datetime.now())
        session.add(user_session)
        return token
Exemplo n.º 7
0
    def wrapper(request, *args, **kwargs):
        if TOKEN not in request:
            return create_response(request, FORBIDDEN, {MESSAGE: "Access denied"})
        with session_scope() as session:
            user_session = session.query(Session).filter_by(token=request[TOKEN]).first()
            if not user_session or user_session.closed:
                return create_response(request, FORBIDDEN, {MESSAGE: "Access denied"})

        return func(request, *args, **kwargs)
Exemplo n.º 8
0
def get_messages_controller(request):
    with session_scope() as session:
        messages = reduce(
            lambda value, item: value + [
                {MESSAGE: item.data, "created": item.created.timestamp()}
            ],
            session.query(Message).all(),
            []
        )
        return create_response(request, OK, {MESSAGE: str(messages)})
Exemplo n.º 9
0
def update_message_controller(request):
    # message_id = request.get("message_id")
    # message_data = request.get("message_data")

    request_list = request[DATA][MESSAGE].split()
    try:
        message_id = request_list[0]
        message_data = " ".join(request_list[1:])
    except IndexError:
        # print("Не задан id или текст сообщения")
        return create_response(request, WRONG_REQUEST, {MESSAGE: "Не задан id или текст сообщения"})
    else:
        with session_scope() as session:
            message = session.query(Message).filter_by(id=message_id).first()
            message.data = message_data
        return create_response(request, OK)
Exemplo n.º 10
0
def remove_contact_controller(request):
    request_list = request[DATA][MESSAGE].split()
    try:
        user_name = request_list[0]
        contact_name = request_list[1]
    except IndexError:
        print("Не заданы имя пользователя или контакта")
        response = create_response(
            request, CONFLICT,
            {MESSAGE: "Не заданы имя пользователя или контакта"})
    else:
        with session_scope() as session:
            user = session.query(User).filter_by(name=user_name).first()
            print(f"user = {user}")
            contact = session.query(User).filter_by(name=contact_name).first()
            print(f"contact = {contact}")
            if user and contact:
                contact_exist = session.query(Contact).filter_by(
                    user_id=user.id).filter_by(name=contact.name).first()
                if contact_exist:
                    session.delete(contact_exist)
                    print(
                        f"Contact '{contact_name}' removed from {user_name}'s contact list"
                    )
                    response = create_response(
                        request,
                        ACCEPTED,
                        # f"Contact '{contact_name}' removed from {user_name}'s contact list"
                        {MESSAGE: "Contact removed"})
                else:
                    print(
                        f"Contact '{contact_name}' does not exist at {user_name}'s contact list"
                    )
                    response = create_response(
                        request,
                        ACCEPTED,
                        # f"Contact '{contact_name}' does not exist at {user_name}'s contact list"
                        {MESSAGE: "Contact does not exist"})
            else:
                response = create_response(request, OK, {
                    MESSAGE:
                    "Такого пользователя или контакта не существует"
                })
    return response
Exemplo n.º 11
0
def add_contact_controller(request):
    request_list = request[DATA][MESSAGE].split()
    try:
        user_name = request_list[0]
        contact_name = request_list[1]
        if len(request_list) > 2:
            info = " ".join(request_list[2:])
        else:
            info = ""
    except IndexError:
        print("Не заданы имя пользователя или контакта")
        response = create_response(
            request, CONFLICT,
            {MESSAGE: "Не заданы имя пользователя или контакта"})
    else:
        with session_scope() as session:
            user = session.query(User).filter_by(name=user_name).first()
            contact = session.query(User).filter_by(name=contact_name).first()
            if user and contact:
                contact_exist = session.query(Contact).filter_by(
                    user_id=user.id).filter_by(name=contact.name).first()
                if contact_exist:
                    print(
                        f"Contact '{contact_name}' already exists at {user_name}'s contact list"
                    )
                    response = create_response(
                        request, ACCEPTED, {MESSAGE: "Contact already exists"})
                else:
                    new_contact = Contact(name=contact.name,
                                          user_id=user.id,
                                          info=info)
                    session.add(new_contact)
                    print(
                        f"Contact '{contact_name}' added to {user_name}'s contact list"
                    )
                    response = create_response(
                        request,
                        ACCEPTED,
                        # f"Contact '{contact_name}' added to {user_name}'s contact list"
                        {MESSAGE: "Contact added"})
    return response
Exemplo n.º 12
0
def update_contact_controller(request):
    print("Добавление контакта")
    request_list = request[DATA][MESSAGE].split()
    try:
        user_name = request_list[0]
        contact_name = request_list[1]
        if len(request_list) > 2:
            info = " ".join(request_list[2:])
        else:
            info = ""
    except IndexError:
        print("Не заданы имя пользователя или контакта")
        response = create_response(
            request, CONFLICT,
            {MESSAGE: "Не заданы имя пользователя или контакта"})
    else:
        with session_scope() as session:
            user = session.query(User).filter_by(name=user_name).first()
            contact = session.query(User).filter_by(name=contact_name).first()
            if user and contact:
                contact_exist = session.query(Contact).filter_by(
                    user_id=user.id).filter_by(name=contact.name).first()
                if contact_exist:
                    contact_exist.info = info
                    response = create_response(
                        request,
                        ACCEPTED,
                        # f"Contact '{contact_name}' updated at {user_name}'s contact list"
                        {MESSAGE: "Contact updated"})
                else:
                    print(
                        f"Contact '{contact_name}' does not exist at {user_name}'s contact list"
                    )
                    response = create_response(
                        request,
                        ACCEPTED,
                        # f"Contact '{contact_name}' does not exist at {user_name}'s contact list"
                        {MESSAGE: "Contact does not exist"})
    return response
Exemplo n.º 13
0
def get_contact_controller(request):
    request_list = request[DATA][MESSAGE].split()
    try:
        user_name = request_list[0]
        contact_name = request_list[1]
    except IndexError:
        print("Не заданы имя пользователя или контакта")
        response = create_response(
            request, CONFLICT,
            {MESSAGE: "Не заданы имя пользователя или контакта"})
    else:
        with session_scope() as session:
            user = session.query(User).filter_by(name=user_name).first()
            print(f"user = {user}")
            contact = session.query(User).filter_by(name=contact_name).first()
            print(f"contact = {contact}")
            if user and contact:
                contact_exist = session.query(Contact).filter_by(
                    user_id=user.id).filter_by(name=contact.name).first()
                if contact_exist:
                    response = create_response(
                        request, ACCEPTED, {
                            MESSAGE:
                            f"Name: {contact_exist.name} info:{contact_exist.info}"
                        })
                else:
                    response = create_response(request, ACCEPTED, {
                        MESSAGE:
                        "Такого контакта не существует в контакт листе"
                    })
            else:
                response = create_response(request, ACCEPTED, {
                    MESSAGE:
                    "Такого пользователя или контакта не существует"
                })
    return response
Exemplo n.º 14
0
def logout_controller(request):
    with session_scope() as session:
        user_session = session.query(Session).filter_by(
            token=request.get(TOKEN)).first()
        user_session.closed = datetime.now()
        return create_response(request, OK, {MESSAGE: "Session closed"})