Esempio n. 1
0
    def getSession(self, sessionId, name) -> Any:
        """

        return the session refered to by a request. If the session is no longer authenticated then the
        AuthenticationError is raised.
        this method also handles verifying the current request. To implement, handle the AuthenticationError

        :param sessionId: the session id returned to user when session created
        :param name:
        :return:
        """
        hashed_username = make_id(name)
        currentTime = time()
        if currentTime - float(sessionId) > int(
                os.getenv('SESSION_TIMEOUT', 1000)):
            logging.info('user session timed out')
            raise AuthenticationError()
        ref = '{}_{}'.format(sessionId, str(hashed_username))
        #print(self.sessions[ref])
        # TODO handle no sessions byb cathcing keyerror on ref
        try:
            logging.info("user is logged in")
            logging.debug("user {} logged in with {}".format(name, ref))
            #return self.sessions[ref]
        except:
            logging.debug("user {} failed logged in with {}".format(name, ref))
            logging.info('unauthenticated user request')
            raise AuthenticationError()
Esempio n. 2
0
    def startSession(self, name, password):
        """
        create a new session in the sessions dictionary and return the sessionId to the client

        if password is correct raise authentication error

        :param name: plain name string
        :param password: hashed password
        :return:
        """
        user = self.getUser(name)

        if password == user.password:
            currentSession = Session(str(make_id(name)))
            self.sessions['{}_{}'.format(currentSession.serverTime,
                                         str(make_id(name)))] = currentSession
            return str(currentSession.serverTime)
        else:

            raise AuthenticationError()
Esempio n. 3
0
def make_user():
    """
    make a single user with a random name and password and return a dict representation to append to a file
    :param out: the list
    :return:
    """
    password = randomString(8)
    name = names.get_first_name().lower()
    out = {'name': name, 'password': password}
    sessionManager.makeUser(name, str(make_id(password)))
    return out
Esempio n. 4
0
    def updateMeasurement(self, name, measurement) -> None:
        """
        find a users measurement and add one observation to it based on a session

        :param session:
        :param measurement:
        :return:
        """
        # TODO implement find_and_modify

        x = self.service.measurement.find_one({"_id": str(make_id(name))})
        try:
            x['measurement'].append(measurement)
        except:
            raise MeasurementNotFound()
        y = self.service.measurement.replace_one(
            filter={"_id": str(make_id(name))}, replacement=x)
        logging.info("Updated measurement for user {}".format(
            str(make_id(name))))
        if y.acknowledged == None:
            logging.error("could not add measurement for user {}".format(
                str(make_id(name))))
Esempio n. 5
0
    def getUser(self, name: str) -> User:
        """
        Get details of a user
        return details of a user

        :param name: the plain name string
        :return:
        """
        user_list = []
        hashedUserName = make_id(name)
        userObject = self.service.users.find_one({'_id': str(hashedUserName)})
        print(userObject)
        user = userObject['_id']
        password = userObject['password']
        return User(username=user, password=password)
Esempio n. 6
0
 def checkUser(self, name: str):
     """
     Check DB for user
     """
     user_list = []
     hashedUserName = make_id(name)
     try:
         userObject = self.service.users.find_one(
             {'_id': str(hashedUserName)})
         print(userObject)
         user = userObject['_id']
         user_list.append(user)
     except:
         pass
     if len(user_list) == 0:
         return 'available'
     return 'not available'
Esempio n. 7
0
    def makeUser(self, name, password):
        """
        Create a new user and empty measurement, keyed by the hashed id of plain string name. The name is as it
        appears in the Session object. Measurements for a user are queried using a session object

        If a user is created with a name already in use, a conflict is returned

        :param name:
        :param password:
        :return:
        """
        new_user = User(username=str(make_id(name)), password=password)
        try:
            self.service.users.insert_one(new_user.__dict__)
            self.service.measurement.insert_one({
                "_id": new_user._id,
                "measurement": []
            })
        except DuplicateKeyError as e:
            raise DuplicateUser()
Esempio n. 8
0
from src.main.domain.methods import make_id

# 0b87e21afd1e2640e9f14f8c
# hyrcvbjn
# 5e18b1f60e5678ab3f497703
# 9b938710211168f2902f9ed4
# a5a49108230cb2aad89ae67c

if __name__ == '__main__':
    x = make_id('sean')
    print(x)

Esempio n. 9
0
    password = randomString(8)
    name = names.get_first_name().lower()
    out = {'name': name, 'password': password}
    sessionManager.makeUser(name, str(make_id(password)))
    return out


if __name__ == '__main__':
    out = []
    # TODO Sean check me out: test data loader. Make a function to pick random string from list for measurement items
    for i in range(10):
        print(i)
        user = make_user()
        out.append(user)

        sessionId = sessionManager.startSession(user['name'], str(make_id(user['password'])))
        for j in range(4):
            measurement = {
                "comment": "free text comment",
                "date": "27-01-38",
                "frequency": 1,
                "location": "Left hand",
                "severity": 1,
                "specific": "Constipation",
                "time": "Morning",
                "trigger": "Skin"
            }
            session = sessionManager.getSession(sessionId, str(make_id(user['name'])))
            measurementManager.updateMeasurement(user['name'], measurement)

    with open('users.txt', 'w') as file: