def getReservation(self, sessionId, reservationId):
     self.__db = Database()        
     self.__sessionId = sessionId
     
     if self.__db.connect():
         #check session id and get user id
         auth = AuthenticationManager()
         if auth.isSessionIdCorrect(self.__sessionId):
             self.__userId = auth.getUser().getUserId()
             sql = 'SELECT `username`, `status` FROM `user` WHERE `user_id` = "'+str(self.__userId)+'";'
             self.__db.execute(sql)
             u = self.__db.getCursor().fetchone()
             username = u[0]
             status = u[1]
             
             if str(status).lower() == 'admin':
                 sql = 'SELECT `reservation_id`, `title`, `description`, `start`, `end`, `image_type`, `type` FROM `reservation` WHERE `reservation_id`="'+str(reservationId)+'";'   
                 self.__db.execute(sql)
                 data = self.__db.getCursor().fetchone()
                
                 r = Reservation(data)
                 r.setOwner(username)
                 
                 r.setReservationsSite() 
                 status = r.getReservationsSite()[0].getStatus()
                 return r
                             
     return None
    def getAllReservations(self, sessionId, ended = None):
        self.__db = Database()        
        self.__sessionId = sessionId
        self.__allReservations = []

        if self.__db.connect():
            #check session id and get user id
            auth = AuthenticationManager()
            if auth.isSessionIdCorrect(self.__sessionId):
                self.__userId = auth.getUser().getUserId()
                sql = 'SELECT `status` FROM `user` WHERE `user_id` = "'+str(self.__userId)+'";'
                self.__db.execute(sql)
                status = self.__db.getCursor().fetchone()[0]
                
                if str(status).lower() != 'admin':
                    return False
                else:
                    #get all reservations in the system
                    sql = 'SELECT `user_id` FROM `user`;'
                    self.__db.execute(sql)
                    data = self.__db.getCursor().fetchall()
                    
                    for d in data:
                        self.__allReservations.extend(self.getReservations(userId=d[0],ended=ended))
              
        return self.__allReservations
 def getReservations(self, sessionId = None, userId = None, ended = None):
     
     if sessionId == None and userId == None:
         return None
            
     self.__db = Database()        
     self.__sessionId = sessionId
     self.__reservations = []
     
     if self.__db.connect():
         
         try:
             if userId == None:
                 #check session id and get user id
                 auth = AuthenticationManager()
                 if auth.isSessionIdCorrect(self.__sessionId):
                     self.__userId = auth.getUser().getUserId()
             else:
                 self.__userId = userId
                 
             if self.__userId != None:
                 sql = 'SELECT `username` FROM `user` WHERE `user_id`="'+str(self.__userId)+'";'
                 self.__db.execute(sql)
                 username = self.__db.getCursor().fetchone()[0]
                 self.__db.lock({'reservation':'READ'})
                 sql = 'SELECT `reservation_id`, `title`, `description`, `start`, `end`, `image_type`, `type` FROM `reservation` WHERE `user_id`="'+str(self.__userId)+'";'
                 self.__db.execute(sql)
                 data = self.__db.getCursor().fetchall()
                 currentTime = NOW
                 
                 for d in data:
                     end = d[4]
                     diff = currentTime - end
                     
                     r = Reservation(d)
                     r.setOwner(username)
                     
                     r.setReservationsSite() 
                     status = r.getReservationsSite()[0].getStatus()
                     
                     if ended == None:
                         #for pcc
                         self.__reservations.append(r)
                         
                     elif ended:
                         #history (already ended)
                         if diff >= timedelta(hours=0) or status == 'cancel':
                             self.__reservations.append(r)
                     
                     else:
                         #see reservations which havn't ended
                         if diff < timedelta(hours=0) and status != 'cancel':                   
                             self.__reservations.append(r)  
                             
                 self.__db.unlock()
         finally:
             self.__db.close()
             
     return self.__reservations
Exemplo n.º 4
0
    def AuthenticateUser(self):
        # dislpay login prompt for user
        validUID = False
        validPassword = False
        print("###################################################################################")
        print("########################   Welcome to the Login Screen   ##########################")
        print("###################################################################################\n")

        while not validUID: 
            # alternative implementation of a do-while loop in python
            uid = input("enter your uid: ")
            if (not isinstance(uid, str)):
                # return to beginning of authenticate while loop
                print("email entry is not of type(str)")
                continue
            if (not AuthenticationManager.checkIfUniqueIdExists(uid)):
                # return to beginning of authenticate while loop since email is not in database
                print("uid is not recognized in database, please ensure uid is correct")
                continue
            validUID = True

        while not validPassword:
            password = input("enter your password: "******"password entry is not of type(str)")
                continue
            if (not AuthenticationManager.checkIfPaswwordMatchesUniqueId(uid, password)):
                # return to beginning of authenticate while loop since email is not in database
                print("password is not correct")
                continue
            validPassword = True
        userType = AuthenticationManager.getUserType(uid)
        fullname = AuthenticationManager.getUserFullname(uid)
        if (userType == 'a'):
            return RegistryAgent(userType, fullname)
        elif (userType == 'o'):
            return TrafficOfficer(userType, fullname)
        else:
            print("Authenticated User is of an unrecognizable type\n")
            return None
            
    def updateReservationStatus(self,sessionId,reservationId,siteId,reservationStatus, adminDescription=''):
        self.__db = Database()        
        self.__sessionId = sessionId
        self.__allReservations = []
        
        if self.__db.connect():
            #check session id and get user id
            auth = AuthenticationManager()
            if auth.isSessionIdCorrect(self.__sessionId):
                self.__userId = auth.getUser().getUserId()
                sql = 'SELECT `status` FROM `user` WHERE `user_id` = "'+str(self.__userId)+'";'
                self.__db.execute(sql)
                status = self.__db.getCursor().fetchone()[0]
                
                if str(status).lower() != 'admin':
                    return False
                else:
                    #update site_reserved table
                    sql = 'UPDATE `site_reserved` SET `status` = "'+str(reservationStatus)+'" WHERE `reservation_id` = "'+str(reservationId)+'" AND `site_id` = "'+str(siteId)+'";'
                    sql2 = 'UPDATE `site_reserved` SET `admin_description` = "'+str(adminDescription)+'" WHERE `reservation_id` = "'+str(reservationId)+'" AND `site_id` = "'+str(siteId)+'";'

                    if self.__db.execute(sql2):
                        if self.__db.execute(sql):
                            #update both site's status and admin's description
                            self.__db.commit()
                            return True
                        else:
                            #update an admin's description but site's status is as same as the previous version
                            sql = 'SELECT * FROM `site_reserved` WHERE `status` = "'+str(reservationStatus)+'" AND `reservation_id` = "'+str(reservationId)+'" AND `site_id` = "'+str(siteId)+'";'
                            if self.__db.execute(sql):
                                if self.__db.getCursor().fetchone() != None:
                                    self.__db.commit()
                                    return True
                    elif self.__db.execute(sql):
                        #update a site's status only but description is as same as the previous version
                        self.__db.commit()
                        return True

        return False
Exemplo n.º 6
0
import cgi
form = cgi.FieldStorage()

###variable from front-end###
USERNAME = form.getvalue('username')
PASSWORD = form.getvalue('password')
#############################


print "Content-Type: text/html"     
print "Access-Control-Allow-Origin: *"  
print

from AuthenticationManager import AuthenticationManager
from JSONFormatter import JSONFormatter

auth = AuthenticationManager()
result = auth.authenticate(USERNAME,PASSWORD)

jsonFormatter = JSONFormatter()
jsonStr = '{ "result" : "' +str(result)+ '",'

if result :
    user = auth.getUser()
    jsonStr += jsonFormatter.formatUser(user)
else:
    jsonStr = jsonStr[:-1]

jsonStr += ' }'

print jsonStr
Exemplo n.º 7
0
 def __init__(self, database, user_manager):
     self.database = database
     self.user_manager = user_manager
     self.authentication_manager = AuthenticationManager(user_manager)
Exemplo n.º 8
0
class UserDocumentResource:
    def __init__(self, database, user_manager):
        self.database = database
        self.user_manager = user_manager
        self.authentication_manager = AuthenticationManager(user_manager)

    def validate_json_content(req, resp, resource, params):
        if req.content_type is None or req.content_type not in "application/json":
            msg = 'Body of request should be application/json'
            raise falcon.HTTPBadRequest('Bad request', msg)

    @falcon.before(validate_json_content)
    def on_get(self, req, resp, endpoint_type, table=None, doc_id=None):
        [valid_end_point,
         end_point_type] = self.__check_endpoint__(endpoint_type)

        if valid_end_point is False:
            raise falcon.HTTPBadRequest('Bad request', "Invalid endpoint")

        [valid_token, token_result,
         user] = self.authentication_manager.verify_token(req.headers)

        if valid_token is False or user is None:
            resp.body = token_result
            return

        table = self.__generate_table_name__(table,
                                             user['local']['displayName'],
                                             end_point_type)
        if doc_id:
            resp.body = self.database.get_one_by_id(table, doc_id)
        else:
            filter_by = self.__construct_filter_from_query_params__(
                req.query_string)
            sort_by = self.__parse_sort_from_query_params__(req.query_string)
            result = self.database.get_all(table,
                                           filter_by=filter_by,
                                           select_by=None,
                                           sort=sort_by)
            if result is None:
                resp.body = json.dumps({
                    "status": "Fail",
                    "message": "Document not found"
                })
            else:
                resp.body = self.database.get_all(table,
                                                  filter_by=filter_by,
                                                  select_by=None,
                                                  sort=sort_by)

    @falcon.before(validate_json_content)
    def on_post(self, req, resp, endpoint_type, table=None):
        [valid_end_point,
         end_point_type] = self.__check_endpoint__(endpoint_type)
        if valid_end_point is False:
            raise falcon.HTTPBadRequest('Bad request', "404")

        [valid_token, token_result,
         user] = self.authentication_manager.verify_token(req.headers)

        if user is None or valid_token is False:
            resp.body = token_result
            return

        if end_point_type == 'public':
            if self.__check_user_can_post_to_endpoint(user, table) is False:
                resp.body = json.dumps({
                    "status":
                    "fail",
                    "message":
                    "Cannot post to this endpoint"
                })
                return

        metadata = self.__construct_metadata_from_query_params__(
            req.query_string)

        if 'addDatestampToPosts' in user:
            add_datestamp = user['addDatestampToPosts']
        else:
            add_datestamp = False
        table = self.__generate_table_name__(table,
                                             user['local']['displayName'],
                                             end_point_type)

        # If table does not exist, create it
        self.database.add_table(table)
        try:

            raw_json = req.stream.read().decode('utf-8')
            parsed_json = json.loads(raw_json)

            if 'explode' in metadata:
                if metadata['explode'] in parsed_json:
                    parsed_json = parsed_json[metadata['explode']]
                    doc_save_result = self.__save_documents__(
                        table, parsed_json, add_datestamp)
                else:
                    resp.body = json.dumps({
                        "status":
                        "fail",
                        "message":
                        "Could not find attribute '" + metadata['explode'] +
                        "' to explode"
                    })
                    return
            else:
                doc_save_result = self.__save_documents__(
                    table, [parsed_json], add_datestamp)

            resp.body = json.dumps(doc_save_result,
                                   cls=JSONEncoder).replace('_id', 'id')
        except ValueError:
            resp.body = json.dumps({"status": "fail", "message": "Bad JSON"})
            return

    def on_delete(self, req, resp, endpoint_type, table=None, doc_id=None):
        [valid_end_point,
         end_point_type] = self.__check_endpoint__(endpoint_type)
        if valid_end_point is False:
            raise falcon.HTTPBadRequest('Bad request', "404")

        [status, jwt_result,
         user] = self.authentication_manager.verify_token(req.headers)
        if status is True:
            table = self.__generate_table_name__(table,
                                                 user['local']['displayName'],
                                                 end_point_type)
            if doc_id:
                if doc_id == "all":
                    deleted_count = self.database.delete_all(table)
                    resp.body = json.dumps({
                        "status": "success",
                        "deleted_count": deleted_count
                    })
                else:
                    result = self.database.delete(table,
                                                  {'_id': ObjectId(doc_id)})
                    if result.deleted_count == 1:
                        resp.body = json.dumps({
                            "status": "success",
                            "id": doc_id
                        })
                    else:
                        resp.body = json.dumps({{
                            "status": "fail",
                            "id": doc_id
                        }})
            else:
                filter_by = self.__construct_filter_from_query_params__(
                    req.query_string)
                result = self.database.delete(table, filter_by)
                resp.body = json.dumps({
                    "status": "success",
                    "deleted_count": result.deleted_count
                })

        else:
            resp.body = jwt_result

    @falcon.before(validate_json_content)
    def on_put(self, req, resp, endpoint_type, table=None, doc_id=None):
        [valid_end_point,
         end_point_type] = self.__check_endpoint__(endpoint_type)
        if valid_end_point is False:
            raise falcon.HTTPBadRequest('Bad request', "404")

        [status, token_result,
         user] = self.authentication_manager.verify_token(req.headers)
        if status is True:
            table = self.__generate_table_name__(table,
                                                 user['local']['displayName'],
                                                 end_point_type)
            # Return note for particular ID
            if doc_id:
                try:
                    raw_json = req.stream.read().decode('utf-8')
                    parsed_json = json.loads(raw_json)
                    resp.body = self.database.update(table, doc_id,
                                                     parsed_json)
                except ValueError:
                    raise falcon.HTTPError(
                        falcon.HTTP_400, 'Invalid JSON',
                        'Could not decode the request body. '
                        'The '
                        'JSON was incorrect.')
            else:
                resp.body = json.dumps({
                    "success":
                    "fail",
                    "message":
                    "No document found with supplied ID"
                })
        else:
            resp.body = token_result

    def __generate_table_name__(self, table, username, end_point_type):
        """Append the name of the user to the table name."""
        # If private endpoint
        if end_point_type == 'private':
            if username != "":
                return table + "_" + username
            else:
                return table
        else:
            return table

    def __save_documents__(self, table, docs, add_datestamp):
        doc_save_result = []
        for i in range(len(docs)):
            if isinstance(docs[i], dict) is False:
                print(json.loads(docs[i]))
                docs[i] = json.loads(docs[i])
                #return {"status": "fail", "message": "Bad JSON"}
            if add_datestamp:
                docs[i]['created'] = datetime.now().strftime(
                    '%Y-%m-%dT%H:%M:%S.%fZ')
            self.database.save(docs[i], table)
            doc_save_result.append(docs[i])
        if len(doc_save_result) == 1:
            doc_save_result = doc_save_result[0]
        return doc_save_result

    def __parse_sort_from_query_params__(self, query_params):
        sort_by = [('_id', 1)]
        q_params = falcon.uri.parse_query_string(query_params,
                                                 keep_blank_qs_values=False,
                                                 parse_qs_csv=True)
        sortby_val = '_id'
        order_val = 1
        sortby = False
        if 'sortby' in q_params:
            sortby = True
            sortby_val = q_params['sortby']
        if 'order' in q_params:
            order_val = q_params['order']
            if order_val.lower() == 'asc' or order_val == 1:
                order_val = 1
            elif order_val.lower() == 'desc' or order_val == -1:
                order_val = -1

        if sortby is True:
            sort_by = [(sortby_val, int(order_val))]

        return sort_by

    def __construct_filter_from_query_params__(self, query_params):
        filter_val = {}
        q_params = falcon.uri.parse_query_string(query_params,
                                                 keep_blank_qs_values=False,
                                                 parse_qs_csv=True)
        # Get user supplied filters
        for key, value in q_params.items():
            if not self.__reserved__word__(key):
                filter_val[key] = value

        return filter_val

    def __construct_metadata_from_query_params__(self, query_params):
        metadata = {}
        q_params = falcon.uri.parse_query_string(query_params,
                                                 keep_blank_qs_values=False,
                                                 parse_qs_csv=True)

        for key, value in q_params.items():
            if key[:len(config.metadata_key)] == config.metadata_key:
                metadata[key[len(config.metadata_key):]] = value

        return metadata

    def __reserved__word__(self, word):
        return word in config.reserved_words

    def __check_endpoint__(self, end_point):
        if end_point == 'd':
            return [True, 'private']
        elif end_point == 'p':
            return [True, 'public']
        else:
            return [False, '']

    def __check_user_can_post_to_endpoint(self, user, table):
        allowed_to_post_to_endpoint = False
        if 'publicEndpoints' in user:
            for public_endpoint in user['publicEndpoints']:
                if public_endpoint['endpoint'] == table:
                    allowed_to_post_to_endpoint = True

        return allowed_to_post_to_endpoint
import cgitb
cgitb.enable()

print "Content-Type: text/html"
print "Access-Control-Allow-Origin: *"
print "Access-Control-Allow-Headers: Content-Type"
print

from AuthenticationManager import AuthenticationManager

import cgi
form = cgi.FieldStorage()

###variable from front-end###
EMAIL = form.getvalue('email')
NEW_PASSWORD = form.getvalue('password')
#############################

authManager = AuthenticationManager()
u = authManager.createUser(email=EMAIL)
user = authManager.getUser()
result = False

if user != None:
    result = user.resetPassword(NEW_PASSWORD)

jsonStr = '{ "result" : "' + str(result) + '" }'

print jsonStr
Exemplo n.º 10
0
cgitb.enable()


import cgi
form = cgi.FieldStorage()

###variable from front-end###
USERNAME = form.getvalue('username')
SESSION_ID = form.getvalue('session_id')
#############################

print "Content-Type: text/html"     
print "Access-Control-Allow-Origin: *"  
print

from AuthenticationManager import AuthenticationManager
from JSONFormatter import JSONFormatter

auth = AuthenticationManager()
u = auth.createUser(USERNAME,getAnotherUserData=True)
user = auth.getUser()

jsonFormatter = JSONFormatter()
jsonStr = '{ "result" : "' +str(user!=None)+ '",'

if user!=None :
    jsonStr += jsonFormatter.formatUser(user)

jsonStr += ' }'

print jsonStr
Exemplo n.º 11
0
@author: CS401:Nannapas Banluesombatkul
"""


import cgitb
cgitb.enable()

import cgi
form = cgi.FieldStorage()

###variable from front-end###
SESSION_ID = form.getvalue('session_id')
#############################


print "Content-Type: text/html"     
print "Access-Control-Allow-Origin: *"  
print

from AuthenticationManager import AuthenticationManager
from JSONFormatter import JSONFormatter

auth = AuthenticationManager()
result = auth.signOut(SESSION_ID)

jsonFormatter = JSONFormatter()
jsonStr = '{ "result" : "' +str(result)+ '"}'

print jsonStr
 def cancel(self, sessionId, reservationId, reason):
     self.__db = Database() 
     
     if self.__db.connect():
         
         try:
             #check session id and get user id
             auth = AuthenticationManager()
             if auth.isSessionIdCorrect(sessionId):
                 self.__userId = auth.getUser().getUserId()               
                 
                 #---get start and end time of reservation---
                 sql = 'SELECT `start`, `end` FROM `reservation` WHERE `reservation_id` = "'+str(reservationId)+'";'
                 self.__db.execute(sql)
                 data = self.__db.getCursor().fetchone()    
                 begin = str(data[0])
                 end = str(data[1])
                 
                 #---get list of site in the reservation---
                 sql = 'SELECT * FROM `site_reserved` WHERE `reservation_id` = "'+str(reservationId)+'";'
                 self.__db.execute(sql)
                 data = self.__db.getCursor().fetchall()    
                 sites = []
                 
                 for d in data:
                     siteId = d[1]
                     
                     self.__db.execute('SELECT * FROM `site` WHERE `site_id` = "'+str(siteId)+'";')
                     site_data = self.__db.getCursor().fetchone()   
                     
                     site = Site(site_data) #create site just for getting the amount of resource types
                     r = site.getResources()
                         
                     for i in range(0,len(r)):
                         #d[4] = CPU, d[5] = Memory
                         r[i].setAmount(d[4+i])
                     
                     sites.append(site)
                 
                 
                 #---set new the reservation table data---
                 #reservation table
                 newEnd = NOW.strftime("%Y-%m-%d %H:00:00") 
                 sql = 'UPDATE `reservation` SET `end`="'+str(newEnd)+'" WHERE `reservation_id` = "'+str(reservationId)+'";'   
                 self.__db.execute(sql)                      
                     
                 #site_reserved table
                 sql = 'UPDATE `site_reserved` SET `status`="cancel" WHERE `reservation_id` = "'+str(reservationId)+'";'
                 self.__db.execute(sql)
                 
                 
                 #canceled_reservation table
                 sql = 'INSERT INTO `canceled_reservation` VALUES ( "'+str(reservationId)+'", "'+str(reason)+'", "'+str(end)+'");'             
                 self.__db.execute(sql)
                 
                 
                 #schedule table 
                 self.__db.lock({'schedule':'WRITE'})
                 diff = datetime.strptime(begin, "%Y-%m-%d %H:00:00")-NOW
                 if diff < timedelta(hours=0):
                     #running reservation
                     tmpBegin = NOW.strftime("%Y-%m-%d %H:00:00")                                                                    
                 else:
                     #havn't start yet
                     tmpBegin = begin
                     
                 beginToEnd = datetime.strptime(end, "%Y-%m-%d %H:00:00")-datetime.strptime(tmpBegin, "%Y-%m-%d %H:00:00")
                     
                 while beginToEnd>=timedelta(hours=1):
                     tmpEnd = (datetime.strptime(tmpBegin, "%Y-%m-%d %H:00:00")+timedelta(hours=1)).strftime("%Y-%m-%d %H:00:00")
                         
                     for i in range(0,len(sites)):
                         
                         siteId = sites[i].getSiteId()
                         r = sites[i].getResources()
                         sql = 'SELECT * FROM `schedule` WHERE `site_id` = "'+str(siteId)+'" and `start` = "'+str(tmpBegin)+'";'
                         self.__db.execute(sql)
                         data = self.__db.getCursor().fetchone()
                         
                         usedAmount = []
                         for k in range(0,len(r)):
                             #CPU = data[3], Memory = data[4]
                             usedAmount.append(data[k+3])
                         
                         tableDesc = self.__db.getCursor().description
                         
                         sql = 'UPDATE `schedule` SET'
                         
                         for j in range(0,len(r)):
                             #note : data[3] is CPU
                             sql += ' `'+str(tableDesc[3+j][0]) + '` = "' + str(int(usedAmount[j])-int(r[j].getAmount()))+'",'
                          
                         sql = sql[:-1]
                         sql += ' WHERE `site_id` = "'+str(siteId)+'" AND `start` = "'+str(tmpBegin)+'";'
          
                         self.__db.execute(sql)
                      
                     tmpBegin = tmpEnd
                     beginToEnd = datetime.strptime(end, "%Y-%m-%d %H:00:00")-datetime.strptime(tmpBegin, "%Y-%m-%d %H:00:00")
  
                 
                 self.__db.commit()
                 return True
            
         except:
             self.__db.rollback()
             return False
         finally:
             self.__db.close()
         
     return False
    def canCreateReservation(self, sessionId, begin, end, sitesId, resources, imgType, step=1):
        self.__db = Database()        
        self.__sessionId = sessionId
        self.__begin = begin
        self.__end = end
        self.__sitesId = sitesId 
        self.__resources = resources
        self.__imgType = imgType
        
        if self.__db.connect():
            
            #check session id and get user id
            auth = AuthenticationManager()
            if auth.isSessionIdCorrect(self.__sessionId):
                self.__userId = auth.getUser().getUserId()
                
                #check available resources in sites
                siteStatus = [False]*len(sitesId)
                
                #get data of this site
                if step == 1:
                    self.__db.lock({ 'site' : 'READ', 'schedule':'READ' })
                else:
                    self.__db.lock({ 'site' : 'READ', 'schedule':'WRITE', 'site_reserved' : 'WRITE', 'reservation':'WRITE' })
                
                for i in range(0,len(sitesId)):
                    #sitesId = list of all site user selected.
                    self.__db.execute('SELECT * FROM `site` WHERE `site_id` = "'+str(sitesId[i])+'";')
                    data = self.__db.getCursor().fetchone()
                    site = Site(site=data,db=self.__db)        
                    
                    #-> check image type
                    self.__imgTypeError = True
                    for img in site.getImageType():
                        if str(self.__imgType) in img.get('name'):
                            self.__imgTypeError = False
                            
                    if self.__imgTypeError :
                        return False
                        
                    #-> check available resources in site from begin to end
                    res = site.getResources()
                    resStatus = [False]*len(res)
                    
                    for j in range(0,len(res)):
                        res[j].setAvailableAmount(db=self.__db,begin=begin,end=end)
                        if int(res[j].getAvailableAmount()) >= int(resources[i][j]):
                            resStatus[j] = True
                        else:
                            self.__addSiteError(i)
                            self.__addResourceError(j)                   
                            
                    if not False in resStatus:
                        #resources of this site are available enough
                        siteStatus[i] = True 
                 
                if step == 1:
                     self.__db.unlock()
                     self.__db.close()

                if not False in siteStatus:
                #all conditions are okay, this reservation can be created
                    return True
                             
        return False             
    def extend(self, sessionId, end, reservationId):

        self.__db = Database() 
        sites = []
        
        if self.__db.connect():
            
            #check session id and get user id
            auth = AuthenticationManager()
            if auth.isSessionIdCorrect(sessionId):
                self.__userId = auth.getUser().getUserId()
                
                try:
                    self.__db.lock({'site':'READ','schedule':'WRITE','site_reserved':'READ','reservation':'WRITE'})
                    sql = 'SELECT `end` FROM `reservation` WHERE `reservation_id`="'+str(reservationId)+'";'
                    self.__db.execute(sql)
                    data = self.__db.getCursor().fetchone()            
                    endOld = str(data[0])
                    
                    if endOld != end:
                    
                        sql = 'SELECT * FROM `site_reserved` WHERE `reservation_id` = "'+str(reservationId)+'";'
                        self.__db.execute(sql)
                        data = self.__db.getCursor().fetchall()   
            
                        siteManager = SiteManager()
                        
                        for d in data:
                            
                            #one round = one site
                            siteId = d[1]
                            site = siteManager.getSite(siteId=siteId,dateReq=endOld,end=end,db=self.__db,locked=True)
                            
                            #check resource available from end of this reservation to end of new reservation
                            r = site.getResources()
                            for i in range(0,len(site.getResources())):
                                #d[4] = CPU, d[5] = Memory
                                if int(r[i].getAvailableAmount()) < int(d[4+i]):
                                    return False
                                r[i].setAmount(d[4+i])
                            
                            sites.append(site)
                                
                            
            
                        #----the resources are available----#
                        #reservation table
                        sql = 'UPDATE `reservation` SET `end` = "'+str(end)+'" WHERE `reservation_id` = "'+str(reservationId)+'";'
                        self.__db.execute(sql)  
    
                        
                        #site_reserved table no need to be updated
                        
                        #schedule table
                        tmpBegin = str(endOld)
                        beginToEnd = datetime.strptime(end, "%Y-%m-%d %H:00:00")-datetime.strptime(tmpBegin, "%Y-%m-%d %H:00:00")
                            
                        while beginToEnd>=timedelta(hours=1):
                            
                            tmpEnd = (datetime.strptime(tmpBegin, "%Y-%m-%d %H:00:00")+timedelta(hours=1)).strftime("%Y-%m-%d %H:00:00")
                                
                            for i in range(0,len(sites)):
                                
                                siteId = sites[i].getSiteId()
                                r = sites[i].getResources()
                                
                                self.__db.execute('SELECT * FROM `schedule` WHERE `site_id` = "'+str(siteId)+'" and `start` = "'+str(tmpBegin)+'";')
                                data = self.__db.getCursor().fetchone()
                                
                                if data == None:
                                    #still not have this time slot of this site
                                
                                    sql = 'INSERT INTO `schedule` VALUES ('
                                    sql += '"'+str(siteId)+'","'+str(tmpBegin)+'","'+str(tmpEnd)+'","'
                                    
                                    for j in range(0,len(r)):
                                        sql += str(r[j].getAmount())+'","'
                                     
                                    sql = sql[:-2]
                                    sql += ');'
                                
                                else:
                                    #already have this time slot of this site
                                
                                    self.__db.execute("SELECT * FROM `schedule` LIMIT 0;")
                                    tableDesc = self.__db.getCursor().description
                                    
                                    sql = 'UPDATE `schedule` SET'
                                    
                                    for j in range(0,len(r)):
                                        #note : data[3] is CPU
                                        sql += ' `'+str(tableDesc[3+j][0]) + '` = "' + str(int(r[j].getAmount())+int(data[3+j]))+'",'
                                     
                                    sql = sql[:-1]
                                    sql += ' WHERE `site_id` = "'+str(siteId)+'" AND `start` = "'+str(tmpBegin)+'";'
                                    
                                self.__db.execute(sql)
                                    
                                
                            tmpBegin = tmpEnd
                            beginToEnd = datetime.strptime(end, "%Y-%m-%d %H:00:00")-datetime.strptime(tmpBegin, "%Y-%m-%d %H:00:00")
                    
                    
                        self.__db.commit()
                        return True
                
                except:
                    self.__db.rollback()
                    return False
                finally:
                    self.__db.unlock()
                    self.__db.close() 
                  
            else:
                self.__db.close() 
            
        return False