Ejemplo n.º 1
0
def user_profile_setemail(token, email):
    # check if the token is valid
    if check_valid(token) is False:
        raise AccessError(description='error occurred: token is not valid')

    exist_change = False
    regex = r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'

    if re.search(regex, email):  # check Email entered is valid
        exist_change = True
    if exist_change is False:
        raise InputError(
            description='error occurred: email entered is not valid')

    # check email address is independent
    db_connect = DbConnector()
    db_connect.cursor()
    sql = "SELECT email FROM project.user_data WHERE email=(%s);"
    value = (email, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()
    if ret is not None:
        raise InputError(
            description='error occurred: email is already used by another user'
        )

    # get user's u_id from token
    token_operation = TokenJwt()
    u_id = token_operation.get_uid(token)

    sql = "UPDATE project.user_data SET email=(%s) WHERE u_id=(%s)"
    value = (email, u_id)
    db_connect.execute(sql, value)

    db_connect.close()

    return {}
Ejemplo n.º 2
0
def user_profile(token, u_id):
    # check if the token is valid
    if check_valid(token) is False:
        raise AccessError(description='error occurred: token is not valid')

    db_connect = DbConnector()
    db_connect.cursor()
    sql = "SELECT email, name_first, name_last, handle, \
           profile_img_url FROM project.user_data WHERE u_id=(%s);"

    value = (u_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()

    # check uid is valid
    if ret is None:
        raise InputError(
            description='error occurred: User with u_id is not a valid user')

    user_dict = {}  # for return
    email = ret[0]
    name_first = ret[1]
    name_last = ret[2]
    handle_str = ret[3]
    profile_img_url = ret[4]

    user_dict['u_id'] = u_id
    user_dict['email'] = email
    user_dict['name_first'] = name_first
    user_dict['name_last'] = name_last
    user_dict['handle_str'] = handle_str
    user_dict['profile_img_url'] = profile_img_url

    # close database connection
    db_connect.close()

    return {'user': user_dict}
Ejemplo n.º 3
0
def auth_passwordreset_reset(reset_code: str, new_password: str) -> dict:
    '''
    Given a reset code for a user,
    set that user's new password to the password provided.

    :param reset_code: generated random code sent to user
    :param new_password: user's new password to be reset
    :return:
    '''
    # check if new password is valid
    if len(new_password) < 6:
        raise InputError(description='error occurred: Password entered is less '
                                     'than 6 characters long')
    # check if reset code match
    db_connect = DbConnector()
    db_connect.cursor()
    sql = "SELECT u_id FROM project.user_data WHERE reset_code=(%s)"
    value = (reset_code,)
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()
    if ret is None:
        raise InputError(description='error occurred: Reset code entered does not match')

    # use for sql query
    u_id = ret[0]

    # UPDATE new password and remove the reset code from database
    password = hashlib.sha256(new_password.encode()).hexdigest()
    sql = "UPDATE project.user_data set password=(%s), reset_code = (%s) WHERE u_id=(%s)"
    value = (password, None, u_id)
    db_connect.execute(sql, value)

    # close database connection
    db_connect.close()

    return {}
Ejemplo n.º 4
0
def standup_send(token, channel_id, message):
    token_operation = TokenJwt()
    # check if the token is valid
    if check_valid(token) is False:
        raise AccessError(description='error occurred: token is not valid')
    # check channel id is valid
    db_connect = DbConnector()
    db_connect.cursor()
    sql = "SELECT member FROM project.channel_data WHERE channel_id=(%s);"
    value = (channel_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()
    if ret is None:
        raise InputError(description='error occurred: channel is not valid')

    # get member list
    member_list = ret[0]

    # check if the message longer than 1000
    if len(message) > 1000:
        raise InputError(description='Message is more than 1000 characters')
    exist_active = standup_active(token, channel_id)["is_active"]
    if not exist_active:
        raise InputError(
            description='error occurred: no standup is running in this channel'
        )

    u_id = token_operation.get_uid(token)
    # check user is valid
    if u_id not in member_list:
        raise AccessError(
            description='error occurred: user is not a member of this channel')

    # get handle
    sql = "SELECT handle FROM project.user_data WHERE u_id=(%s)"
    value = (u_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()
    handle = ret[0]

    # get msg from active buffer
    sql = "SELECT message FROM project.active_data WHERE channel_id=(%s)"
    value = (channel_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()

    if ret[0] is not None:
        message_stand = ret[0]
        message_stand += "\n" + handle + ": " + message
    else:
        message_stand = handle + ": " + message

    # add to active data
    sql = "UPDATE project.active_data SET message=(%s) WHERE channel_id=(%s);"
    value = (message_stand, channel_id)
    db_connect.execute(sql, value)

    # close database connection
    db_connect.close()

    return {}
Ejemplo n.º 5
0
		size = 4096
		while True:
			try:
				event_data = pickle.loads(client.recv(size))
				response = False
				if event_data._event_type == 'ORDER':
					response = self._exchange.handle_order(event_data)
				elif event_data._event_type == 'REGISTER':
					response = self._exchange.handle_player_registration(event_data)
				else:
					raise Exception("Client disconnected")
				print(response)
				client.send(pickle.dumps(response))
			except Exception as e:
				print(e)
				self._connected_players.remove(client)
				self.update_exchange_client_list()
				print(f'closing for client {client} due to inactivity')
				client.close()
				return False

	def update_exchange_client_list(self):
		self._exchange._clients = self._connected_players


if __name__ == '__main__':
	conn = DbConnector('postgres', 5432, 'exchangedb', '127.0.0.1')
	cs = CastingServer('', 12346)
	
	ex = Exchange(conn, cs)
	server = ExchangeServer('', 12345, ex).listen_for_clients()
Ejemplo n.º 6
0
from flask import Flask, Response, url_for
from db_connector import DbConnector
import simplejson
from collections import defaultdict

app = Flask(__name__)
db_connector = DbConnector()


def get_sql_query(file_path):
    file = open(file_path, 'r')
    sql_query = file.read()
    file.close()
    return sql_query


def get_sql_results(sql_query):
    query_result = db_connector.execute_query(sql_query)
    print(query_result)

    json = simplejson.dumps(dict(query_result),
                            use_decimal=True,
                            sort_keys=True)

    response = Response(json, status=200, mimetype='application/json')

    return response


@app.route('/')
def home():
Ejemplo n.º 7
0
from player import Player
from event_manager import EventManager
from db_connector import DbConnector
from data_listener import BookListener

initial_money = 10000
player_name = 'Notroop'

em = EventManager()
conn = DbConnector('postgres', 5432, 'postgres', '127.0.0.1')
file_path = 'D:\\genericbacktesters\\book_data\\file.dat'
bl = BookListener('', 12347, file_path)

player = Player(initial_money, player_name, em, conn)

symbol = 'YESBANK_EQ'
price = 1000
direction = 'SHORT'
quantity = 50
order_id = '9f04581c-a00b-4cd1-bb07-fd25ecf64315'
player.place_new_order(symbol, price, direction, quantity)
Ejemplo n.º 8
0
        if isNone:
            # song_list가 빈 경우 실패 메세지도 같이 전송
            data = {"type": "2", "result": "failure"}
        else:
            data = {"type": "2"}
    else:
        data = {
            "type": "1",
            "step":
            step,  # 1: 성별, 2: 활동유형, 3:장르, 4:년도, 5:OST 여부, 6:피처링 여부, 7:분위기, 8:관련성
            "question_type_name":
            question_type_name[step - 1],  # 질문에 나올 질문할 속성 명
            "question_type": question_type[step - 1],  # 답변으로 표시될 노래 속성값들
        }

    emit('response', data, to=socket_id)


# https://flask-socketio.readthedocs.io/en/latest/
if __name__ == "__main__":
    db = DbConnector()
    song_list = db.select_all()
    for i in range(len(song_list)):
        song_list[i]['words'] = song_list[i]['words'].split()
    print(len(song_list))
    socketIo.run(app, host='0.0.0.0', port=5000)

# app.run(debug=True)
# host 등을 직접 지정하고 싶다면
# app.run(host="127.0.0.1", port="5000", debug=True)
Ejemplo n.º 9
0
 def test_open_connection(self):
     """
     Tests to check that a dbConnector returns true when trying to open a connection.
     """
     connector = DbConnector()
     self.assertTrue(connector.open_connection())
Ejemplo n.º 10
0
def auth_register(email: str, password: str, name_first: str, name_last: str) -> dict:
    """
    Given a user's first and last name, email address, and password,
    create a new account for them and return a new token for authentication in their session.

    :param email: user's email
    :param password: user's password
    :param name_first: user's first name
    :param name_last: user's last name
    :return: dictionary with keys "u_id" and "token"
    """
    # check if email invalid
    if not check(email):
        raise InputError(description='error occurred: Email entered is not a valid email')

    # check if email has already been used
    db_connect = DbConnector()
    db_connect.cursor()  # connect to database and get cursor
    sql = "SELECT email from project.user_data WHERE email = %s"
    value = (email,)
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()
    if ret is not None:
        raise InputError(description='error occurred: Email address is already '
                                     'being used by another user')

    # check the length of password
    if len(password) < 6:
        raise InputError(description='error occurred: Password entered is less '
                                     'than 6 characters long')

    if len(name_first) not in range(1, 51):
        raise InputError(description='error occurred: first name is not '
                                     'between 1 and 50 characters inclusively in length')

    if len(name_last) not in range(1, 51):
        raise InputError(description='error occurred: last name is not '
                                     'between 1 and 50 characters inclusively in length')

    # generate u_id for the new user
    sql = "INSERT INTO project.user_data (email) VALUES (%s)"
    value = (email,)
    db_connect.execute(sql, value)

    sql = "SELECT u_id FROM project.user_data WHERE email=(%s)"
    value = (email,)
    db_connect.execute(sql,value)
    ret = db_connect.fetchone()
    user_uid = ret[0]
    # sql = "SELECT COUNT(*) FROM project.user_data"
    # db_connect.execute(sql)
    # ret = db_connect.fetchone()
    # user_uid = ret[0] + 1
    # print(user_uid)

    # generate a handle for the new user
    # which contains the first letter of the name_first by default
    # cut off the part where exceeds 20

    handle = (name_first[0] + name_last).lower()

    if len(handle) > 20:
        handle = handle[0:20]

    # check if it is unique otherwise
    sql = "SELECT handle from project.user_data WHERE handle=%s"
    value = (handle,)
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()
    # if it exceeds 20, cutoff the extra part from the original handle and remain user_uid
    # add user_uid at the end of the handle
    if ret is not None:
        if len(handle + str(user_uid)) > 20:
            handle = handle[0:(20 - len(str(user_uid)))] + str(user_uid)
        else:
            handle = handle + str(user_uid)

    # generate the token
    token_operation = TokenJwt()
    token = token_operation.encode_token({'u_id': user_uid})
    # hashing the password
    hash_password = hashlib.sha256(password.encode()).hexdigest()

    # add user in database
    sql = '''
    UPDATE project.user_data
    set password=(%s), name_first=(%s), name_last=(%s), token=(%s), handle=(%s)
    WHERE email=(%s)
    '''
    value = (hash_password, name_first, name_last, token, handle, email)
    db_connect.execute(sql, value)

    if user_uid == 1:
        sql = "INSERT INTO project.flockr_data (owner) VALUES ('{%s}')"
        value = [user_uid]
        db_connect.execute(sql, value)

    db_connect.close()

    return {
        'u_id': user_uid,
        'token': token
    }
Ejemplo n.º 11
0
def channel_details(token: str, channel_id: int) -> dict:
    """
    Given a Channel with ID channel_id that the authorised user is part of,
    provide basic details about the channel

    :param token: user's token
    :param channel_id: channel's id
    :return: a dictionary with keys 'name', 'owner_members' and 'all_members'
    """
    token_operation = TokenJwt()
    # check if the token is valid
    if check_valid(token) is False:
        raise AccessError(description='error occurred: token is not valid')
    # get the user's u_id from token
    u_id = token_operation.get_uid(token)

    # get info for the channel
    db_connect = DbConnector()
    db_connect.cursor()
    sql = "SELECT * FROM project.channel_data  WHERE channel_id = (%s)"
    value = (channel_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchall()
    # check if channel id invalid
    if len(ret) == 0:
        raise InputError(
            description='error occurred: the channel ID is not a valid channel'
        )

    channel_name = ret[0][1]
    member_list = ret[0][2]
    owner_list = ret[0][3]
    # check if the authorised user is member of this channel
    if u_id not in member_list:
        raise AccessError(description='error occurred: the authorised user '
                          'is not a member of channel with this channel_id')

    # get channel member basic information
    db_connect.cursor()
    sql = '''
    DROP TABLE IF EXISTS project.detail_data;
    CREATE TABLE project.detail_data
    (
        id   serial NOT NULL,
        u_id int
    );
    INSERT INTO project.detail_data(u_id)
    select unnest((
        SELECT member
        FROM project.channel_data
        WHERE channel_id = (%s)));
    SELECT u.u_id, name_last, name_first, profile_img_url
    FROM project.user_data u
    INNER JOIN project.detail_data d ON u.u_id = d.u_id
    ORDER BY d.id;
    '''
    value = (channel_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchall()
    all_members = []
    # get member details
    for detail in ret:
        all_members.append({
            'u_id': detail[0],
            'name_last': detail[1],
            'name_first': detail[2],
            'profile_img_url': detail[3]
        })

    # get owner details
    owner_members = []
    for member in all_members:
        if member['u_id'] in owner_list:
            owner_members.append(member)

    # close database connection
    db_connect.close()

    details = {
        'name': channel_name,
        'owner_members': owner_members,
        'all_members': all_members
    }

    return details
Ejemplo n.º 12
0
def channel_invite(token: str, channel_id: int, u_id: int) -> dict:
    """
    Invites a user (with user id u_id) to join a channel with ID channel_id.
    Once invited the user is added to the channel immediately

    :param token: token of user who try to invite user
    :param channel_id: the id of channel which the user will be invited in
    :param u_id: uid of user who has been invited to join the channel
    :return: if it can successfully invite somebody to this channel,
             it will return an empty dictionary
    """

    token_operation = TokenJwt()
    # check if the token is valid
    if check_valid(token) is False:
        raise AccessError(description='error occurred: token is not valid')

    # check if channel id is valid
    db_connect = DbConnector()
    db_connect.cursor()
    sql = "SELECT channel_id FROM project.channel_data WHERE channel_id = (%s)"
    value = (channel_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()
    if ret is None:
        raise InputError(
            description=
            'error occurred: channel_id does not refer to a valid channel')

    # check if uid is valid
    sql = "SELECT u_id FROM project.user_data WHERE u_id = (%s)"
    value = (u_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()
    if ret is None:
        raise InputError(
            description='error occurred: u_id does not refer to a valid user')

    # check if the authorised user( is a member of the channel)
    authorised_uid = token_operation.get_uid(token)
    sql = "SELECT member, owner  FROM project.channel_data  WHERE channel_id =(%s)"
    value = (channel_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()
    member_list = ret[0]
    owner_list = ret[1]
    if authorised_uid not in member_list:
        raise AccessError(description='error occurred: the authorised user '
                          'is not a member of the channel')

    # get flockr owner list
    sql = "SELECT owner FROM project.flockr_data;"
    db_connect.execute(sql)
    ret = db_connect.fetchone()
    flockr_list = ret[0]

    # if no error, add the user to the channel
    if u_id not in member_list:
        sql = "UPDATE project.channel_data SET member=(%s), owner=(%s) WHERE channel_id=(%s);"
        # if invite flockr, flockr will be owner
        if u_id in flockr_list:
            member_list.append(u_id)
            owner_list.append(u_id)
            value = (member_list, owner_list, channel_id)
        else:
            member_list.append(u_id)
            value = (member_list, owner_list, channel_id)
        db_connect.execute(sql, value)

    db_connect.close()

    return {}
Ejemplo n.º 13
0
def channel_messages(token: str, channel_id: int, start: int):
    """
    Given a Channel with ID channel_id that the authorised user is part of,
    return up to 50 messages between index "start" and "start + 50"
    :param token: the authorised user's token
    :param channel_id: the channel ID
    :param start: the start number
    :return: dictionary of messages as required
    """
    token_operation = TokenJwt()
    # check if the token is valid
    if check_valid(token) is False:
        raise AccessError(description='error occurred: token is not valid')

    # start = int(start)
    # channel_id = int(channel_id)
    db_connect = DbConnector()
    db_connect.cursor()
    sql = "SELECT member FROM project.channel_data WHERE channel_id=(%s)"
    value = (channel_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()
    # check channel_id is valid
    if ret is None:
        raise InputError(description='error occurred: channel id is not valid')
    member_list = ret[0]
    # get user's u_id from token
    u_id = token_operation.get_uid(token)
    # check u_id is a member for the channel
    if u_id not in member_list:
        raise AccessError(
            description='Authorised user is not a member of channel')

    # check start valid
    sql = "SELECT COUNT(*) FROM project.message_data WHERE channel_id=(%s)"
    value = (channel_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchone()
    total_message = ret[0]
    # start is greater than the total number of messages
    if start > total_message:
        raise InputError(description='error occurred: start is greater than '
                         'the total number of messages')

    # determine end
    retuen_end = -1
    if total_message > start + 50:
        end = start + 50
        retuen_end = end
    else:
        end = total_message

    # store all the required messages
    msg = []
    sql = "SELECT * FROM project.message_data WHERE channel_id=(%s) ORDER BY time_created DESC"
    value = (channel_id, )
    db_connect.execute(sql, value)
    ret = db_connect.fetchall()
    for detail in ret:
        react_uid = detail[6]
        if u_id in react_uid:
            react_cond = True
        else:
            react_cond = False
        msg.append({
            'message_id':
            detail[0],
            'channel_id':
            detail[1],
            'time_created':
            detail[3],
            'u_id':
            detail[4],
            'message':
            detail[2],
            'is_pinned':
            detail[5],
            'reacts': [{
                'is_this_user_reacted': react_cond,
                'react_id': 1,
                'u_ids': react_uid
            }]
        })

    # close database connection
    db_connect.close()

    return {'messages': msg, 'start': start, 'end': retuen_end}
Ejemplo n.º 14
0
 def __init__(self):
     self._conn = DbConnector('postgres', 5000, 'postgres', 'localhost')
     self._engine = Engine()
     self._symbol_list = self._get_all_symbols()
Ejemplo n.º 15
0
 def __init__(self):
     self._engine_id = uuid4()
     self._conn = DbConnector('postgres', 5000, 'postgres', 'localhost')