def test_new_user_has_default_values(self):
     user = User("abc123")
     expected_dict = {
         "id": "abc123",
         "firstname": "Joe",
         "lastname": "User",
         "address": "123 Fake Street",
         "city": "Blacksburg"
     }
     self.assertEquals(user.to_dict(), expected_dict)
Exemple #2
0
 def setup(self):
     db: dataset.Database = self.get_db()
     system_table = db.get_table("system")
     if None == system_table.find_one(key="system_00"):
         system_table: dataset.Table = db.create_table("system")
         system_table.create_column("key", sqlalchemy.VARCHAR(256))
         system_table.create_column("value", sqlalchemy.VARCHAR(256))
         system_table.insert({"key": "system_00", "value": True})
     User.setup(db)
     InstanceInfo.setup(db)
 def test_update_user_from_dictionary(self):
     user = User("abc123")
     update_dict = {
         "firstname": "Sarah",
         "lastname": "Tester",
         "address": "111 Nowhere Way",
         "city": "Christiansburg"
         }
     user.update(update_dict)
     update_dict.update({"id": "abc123"})
     self.assertEquals(user.to_dict(), update_dict)
Exemple #4
0
	def start(self, ip, port, callback):
		"""
		Begin listening for client connections at the given address.

		@param ip The IP address to listen on.
		@param port The port to listen on. Should be 6660-6669 or 7000.
		@param callback The function to call when a thread receives a message
		"""

		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

		self._hostname = ip
		sock.bind((ip, port))

		while True:
			# Listen with no queued connections - will block
			sock.listen(0)
			# A connection has been acquired - get its info
			(conn, (ip, _)) = sock.accept()

			# The user will manage its own connection info
			usr = User(conn, ip)
			# Users are autonomous, but store them as a key to keep track of
			# the channels they belong to
			self._users[usr] = []

			# Let the user start listening on its own thread
			Thread(target = usr.listen, args = (callback,)).start()
Exemple #5
0
    def register_user(client_socket, parts):
        """
        Method to register users and their clients

        :param client_socket: Socket where a connection with a client is happening
        :param parts: Parts of the message that was sent by the client
        """

        username = parts[1]
        one_time_id = parts[2]
        signature = base64.b64decode(parts[3])
        hostname = parts[4]
        port = parts[5]
        client_cert = parts[6]

        valid_signature = Cryptography.verify_signature(
            base64.b64decode(client_cert).decode(), one_time_id, signature)

        if valid_signature and User.login(username, one_time_id):
            ClientsStore.save_client(username, hostname, port, client_cert)
            ClientsStore.set_online(username, hostname, port)
            Administration.__socket_map[client_socket] = username
            client_socket.send('OK'.encode())
        else:
            client_socket.send('NOTOK'.encode())
    def run(self, server, protocol, command):
        login = command['account_name']
        password = command['password']
        public_key = command['public_key']
        hashed_password = get_hash(login, password)

        session = sessionmaker(bind=self.db_engine)()
        db_user = session.query(SQLUser).filter_by(login=login).first()
        if db_user:
            if db_user.password != hashed_password:
                protocol.send_packet(ResponsePacket(402, command['id']))
                session.close()
                return
        else:
            db_user = SQLUser(login=login,
                              password=hashed_password,
                              public_key=public_key)
            session.add(db_user)
            session.commit()

        user = User()
        user.gid = db_user.gid
        user.login = db_user.login
        user.public_key = db_user.public_key
        user.protocol = protocol
        protocol.user = user

        server.logged_users.update({user.login: user})
        protocol.send_packet(ResponsePacket(202, command['id']))
Exemple #7
0
 def init_app(self, email: str, password: str):
     db: dataset.Database = self.get_db()
     system_table = db.get_table("system")
     if None == system_table.find_one(key="app_00"):
         user: User = User()
         user._email = email
         user._name = re.sub(r"@.*$", "", email)
         user._password = password
         self.update_user(user)
         system_table.insert({"key": "app_00", "value": True})
         return True
     else:
         return False
Exemple #8
0
    def list_users(client_socket, parts):
        username = parts[1]
        signature = base64.b64decode(parts[2])

        user = User.load_user(username)
        client = ClientsStore.get_client(username)

        valid_signature = Cryptography.verify_signature(
            base64.b64decode(client['cert']).decode(), username, signature)

        if valid_signature:
            user_list = ClientsStore.list_users(username,
                                                user.get_clearance_level())
            encoded_list = pickle.dumps(user_list)
            client_socket.send(encoded_list)

        else:
            client_socket.send('UNAUTHORIZED'.encode())
Exemple #9
0
    def list_users(username, clearance_level):
        """
        Method to list the User's that are online and which clearance level is compatible with the asking user

        :param username: Username of the user that is asking for the list
        :param clearance_level: Clearance level of the user that is asking for the list
        :return: List of online users that the user can see
        """

        user_list = []
        for user in ClientsStore.__online:
            if user != username:
                if ClientsStore.is_online(username):
                    saved_user = User.load_user(user)
                    if saved_user.get_clearance_level() <= clearance_level:
                        user_entry = ClientsStore.get_client(user)
                        user_entry['username'] = user
                        user_list.append(user_entry)
        return user_list
Exemple #10
0
    def perform_operations(client_socket, parts):
        """
        Method to execute the privileged operations

        :param client_socket: Socket where a connection with a client is happening
        :param parts: Parts of the message that was sent by the client
        """

        username = parts[1]
        signature = base64.b64decode(parts[2])
        n = int(parts[3])
        number = int(parts[4])
        user = User.load_user(username)
        client = ClientsStore.get_client(username)

        valid_signature = Cryptography.verify_signature(
            base64.b64decode(client['cert']).decode(), username, signature)
        if n <= 0.0:
            client_socket.send('INVALID'.encode())
            return

        if valid_signature:
            clearance = user.get_clearance_level()
            if clearance == 1 and n > 2:
                client_socket.send('UNAUTHORIZED'.encode())
                return
            if clearance == 2 and n > 3:
                client_socket.send('UNAUTHORIZED'.encode())
                return
            if n == 2:
                result = Functions.square_root(number)
            elif n == 3:
                result = Functions.cubic_root(number)
            else:
                result = Functions.n_root(number, n)

            client_socket.send(str(result).encode())
        else:
            client_socket.send('UNAUTHORIZED'.encode())
Exemple #11
0
    def run_administration(server):
        """
        Method that runs the administration panel

        :param server: Server instance, whose properties can be fetched
        """

        if Cryptography.get_passphrase() == "":
            while len(Cryptography.get_passphrase()) != 32:
                passphrase = input(
                    "Please insert the server's passphrase (32 characters): ")
                Cryptography.set_passphrase(passphrase)
        """
        Method to start the menu used by the administrator
        """

        banner = """What do you want to do?
    1 - Create user
    2 - Quit
    > """
        print('Welcome to the administration panel!')
        while True:
            option = int(input(banner))
            if option == 1:
                username, one_time_id = User.create()
                print(
                    f'\nUser created with success!\n\tUsername: {username}\n\tOne Time ID: {one_time_id}\n\n'
                )
            elif option == 2:
                print('Quitting server...')
                logging.info('Quitting server...')
                Administration.RUNNING = False
                socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(
                    (server.get_hostname(), server.get_port()))
                _thread.interrupt_main()
                quit(0)
            else:
                print('Option not valid! Try again.')
Exemple #12
0
 def update_user(self, user: User):
     user.update(self.get_db())
Exemple #13
0
 def get_user_info_from_email(self, email: str) -> User:
     return User.find_one_from_email(self.get_db(), email)
import os
from server.database import DatabaseManager
from server.database import db

from server.user import User

databaseName = "database_test"

os.remove(os.path.abspath('./' + databaseName + ".db"))

db = DatabaseManager(databaseName)

user1 = User()
user1.SetName("Erik Palencik")
user1.SetEmail("*****@*****.**")
user1.SetPassword(
    "1234567"
)  #If you see this code i dont use this password anywhere, so dont even try

db.SerializeClass(user1)

rows = db.GetAllUsers().fetchall()

print("Writting all users:")
for row in rows:
    print(row)