示例#1
0
    def invoke(self, apiParams, body=None, sessionId=None, requestHash=None):
        # API parameters
        self.logger.debug("apiParams: " + str(apiParams) + "  body: " + str(body))

        if body != None and len(body) > 1:
            # look for a session
            request = JSONDecoder().decode(body)
            if sessionId:
                # invalidate the session
                authentication = Authentication()
                authentication.invalidateSession(sessionId)

        output = {"results": "LOGIN"}
            
        return JSONEncoder().encode(output)
示例#2
0
    def authenticateRequest(self, requestString, noBody = False):
        """
           The request is a map of parameters from the client's JSON.  I expect
           to see the following keys:
           * sessionId
           * requestHash
           * request (map)
           
           This does not validate that the session ID is valid, only that the
           request content hashes to the same value.
        """
        authenticated = False
        
        if noBody:
            # replace the request body for authentication
            requestString = "{}"
        
        if requestString != None and \
           self.requestHash != None and \
           self.sessionId != None:
            
            computedRequestHash = 0
            
            sessionKey = None
            clientKey = None

            # last chance to make sure the JSON values are complete            
            authentication = Authentication()
            (userId, sessionKey, clientKey) = authentication.loadSessionKeys(self.sessionId)
            self.logger.debug("Got session keys: " + str(userId) + "," + str(sessionKey) + "," + str(clientKey))
            
            # ...calculate a hash on what the client sent
            computedRequestHash = self.hash(str(clientKey) + ":" + \
                                    str(sessionKey) + ":" + \
                                    requestString, \
                                    self.TABLE_SIZE)
            self.logger.debug("Content considered for hash: " + str(clientKey) + ":" + \
                              str(sessionKey) + ":" + \
                              requestString)
            self.logger.debug("Calculated hash: " + str(computedRequestHash) + "  client Hash: " + str(self.requestHash))

            authenticated = self.requestHash == str(computedRequestHash)
            
            self.logger.debug("authentication result: " + str(authenticated))
        else:
            self.logger.debug("Missing request body, hash, or session ID")
                
        return authenticated
示例#3
0
    def invoke(self, apiParams, body=None, sessionId=None, requestHash=None):
        # API parameters
        self.logger.debug("apiParams: " + str(apiParams) + "  body: " + str(body))
        
        results = {}

        if body != None and len(body) > 1:
            if self.conn:
                cursor = self.conn.cursor()
            
                # look for a current session (before login)
                if sessionId:
                    # invalidate the session
                    expireTime = db.getDatetime()
                    sql = "update sessions set expire_time = %s where id = %i"
                    self.logger.debug("invalidate session sql %s %s %i", sql, expireTime, sessionId)
                    cursor.execute(sql)
            
                # look for a client key, username, password
                request = JSONDecoder().decode(body)
                if "clientKey" in request and \
                   "username" in request and \
                   "password" in request:
                    # verify the login request
                    authentication = Authentication()
                    
                    try:
                        (newSessionId, newSessionKey) = authentication.login(request["username"], request["password"], "", request["clientKey"])
                        results["results"] = "OK"
                        results["sessionId"] = newSessionId
                        results["sessionKey"] = newSessionKey
                    except FailedLoginException:
                        results["results"] = "FAILED"
                else:
                    # missing keys
                    results["results"] = "FAILED"

            else:
                self.logger.debug("Couldn't process login:  no database connection")
                results["results"] = "FAILED"

        return JSONEncoder().encode(results)
示例#4
0
 def initialize(self):
     self.auth = Authentication()
示例#5
0
class User(QueryInterface):
    def initialize(self):
        self.auth = Authentication()

    def userExists(self, username):
        query = "select id from users where username = '******'".format(
            str(username))
        result = self.executeQuery(query)
        if (len(result) > 0):
            return True
        return False

    def new(self, username, password):
        if (self.userExists(username)):
            return None
        hashedPassword = self.auth.hash(password)
        query = "insert into users (username, auth) values ('{0}', '{1}');".format(
            str(username), str(hashedPassword))
        self.executeQuery(query)
        return self.login(username, password)

    def login(self, username, password):
        query = "select auth from users where username = '******'".format(
            str(username))
        result = self.executeQuery(query)
        if (len(result) == 0):
            return None
        hashedPassword, salt = result[0][0].split(':')
        testPassword = self.auth.hashWithSalt(password, salt).split(':')[0]
        if (hashedPassword == testPassword):
            token, expires = self.auth.createToken(username)
            tokenQuery = "insert into verifications (bearer, timeout) values ('{0}', '{1}');".format(
                str(token), str(expires))
            self.executeQuery(tokenQuery)
            return token
        return None

    def find(self, searchstring, username):
        userID = self._getUserID(username)
        subquery = "select relation from userrelations where userid = {0} and type = 1".format(
            int(userID))
        query = "select id, username from users where id in ({0}) and username like '{1}%'".format(
            str(subquery), str(searchstring))
        return self.executeQuery(query)

    def relationExists(self, userId, targetId):
        query = "select id from userrelations where userid = {0} and relation = {1}".format(
            int(userId), int(targetId))
        result = self.executeQuery(query)
        if (len(result) > 0):
            return True
        return False

    def relate(self, username, target, relationType):
        userID = self._getUserID(username)
        targetID = self._getUserID(target)
        if (userID == None or targetID == None):
            return
        if (self.relationExists(userID, targetID)):
            return
        query = "insert into userrelations (userid, relation, type) values ({0}, {1}, {2})".format(
            int(userID), int(targetID), int(relationType))
        self.executeQuery(query)

    def getFriendRequests(self, username):
        userID = self._getUserID(username)
        subquery = "select relation from userrelations where userid = {0}".format(
            int(userID))
        query = "select username from userrelations left join users u on userid = u.id where relation = {0} and userid not in ({1})".format(
            int(userID), str(subquery))
        return self.executeQuery(query)

    def verify(self, bearer):
        token = bearer[7:]
        query = "select timeout from verifications where bearer = '{0}'".format(
            str(token))
        result = self.executeQuery(query)
        if (len(result) == 0):
            print('Invalid verification')
            return None
        expires = int(result[0][0])
        if (int(time.time()) > expires):
            print('Verification timeout')
            return None
        username = self.auth.getUsername(token)
        return username

    def belongsToGroup(self, userId, groupId):
        if (int(groupId) == -1):
            return True
        query = "select 1 from usergroupregister where userid = {0} and usergroup = {1} and accepted = TRUE and verified = TRUE".format(
            int(userId), int(groupId))
        result = self.executeQuery(query)
        if (len(result) == 0):
            return False
        return True

    def _getUserID(self, name):
        query = "select id from users where username = '******'".format(str(name))
        result = self.executeQuery(query)
        if (len(result) == 0):
            return None
        return result[0][0]