def authorize(self, client): # where we authorize the user. """ In this method we are trying to get password and user name from the client and check if he has logged on another pc or if his credinitals are correct """ while True: try: data = client.recv(1024) user_and_pass = pickle.loads(data) user = UserHandler(user_and_pass[1], user_and_pass[2]) if user_and_pass[ 0] == 'Register': # if user was trying to register auth = user.register() auth_ = pickle.dumps(auth) client.send(auth_) if auth == "Successfully Registered": self.receive(client, user_and_pass[1], user) else: continue else: # if user was trying to login auth = user.login() auth_ = pickle.dumps(auth) client.send(auth_) if auth == "Successfully Logged In": self.receive(client, user_and_pass[1], user) break else: continue except: break
def updateLabMembers(self, labID, newMembers): #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO db = self.db cursor = self.cursor uHandler = UserHandler(db, cursor) # Find out which members in old members list are not in new members list and delete them oldMembers = self.findMembers(labID) # fetch the IDs of members in oldMembers (a list of User objects) oldMemIDs = [] for m in oldMembers: oldMemIDs.append(m.getUserID()) # Cast each element in newMembers to INT newMemIDs = [] for n in newMembers: newMemIDs.append(int(n)) memDel = utils.diff(oldMemIDs, newMemIDs) for memID in memDel: #self.deleteMember(labID, memID) uHandler.deleteUser(memID)
class TestSimulation(unittest.TestCase): def setUp(self): self.user_handler = UserHandler() def test_format_user_followers_entry_returns_user_followers_list(self): entry = 'Ward follows Martin, Alan' result = self.user_handler.format_user_followers_entry(entry) expected_result = ('Ward', ['Martin', 'Alan']) assert result == expected_result def test_update_empty_user_followers_mapping_returns_user_and_followers_tuple( self): user_followers = ('Ward', ['Martin', 'Alan']) result = self.user_handler.update_user_followers_mapping( {}, user_followers) expected_result = ('Ward', {'Martin', 'Alan'}) assert result == expected_result def test_update_user_followers_mapping_returns_user_and_updated_followers_tuple( self): user_followers = ('Ward', ['Martin', 'Alan']) result = self.user_handler.update_user_followers_mapping( {'Ward': {'Martin'}}, user_followers) expected_result = ('Ward', {'Martin', 'Alan'}) assert result == expected_result def test_get_new_users_returns_new_users_obtained_from_entry(self): user_followers = ('Ward', ['Martin', 'Alan']) result = self.user_handler.get_new_users(set(), user_followers) expected_result = {'Ward', 'Martin', 'Alan'} assert result == expected_result
def findPacket(self, packetID): db = self.db cursor = self.cursor uHandler = UserHandler(db, cursor) newPacket = None cursor.execute("SELECT ownerID, packetName, is_private, comment FROM Packets_tbl p, GeneralComments_tbl c WHERE packetID=" + `packetID` + " AND p.packetDescription = c.commentID AND p.status='ACTIVE' AND c.status='ACTIVE'") result = cursor.fetchone() if result: ownerID = int(result[0]) packetOwner = uHandler.getUserByID(ownerID) packetName = result[1] # private or public accessType = result[2] # Value TRUE or FALSE is returned as a STRING, convert to Boolean if accessType == 'TRUE': isPrivate = True else: isPrivate = False packetDescr = result[3] packetReaders = self.findProjectMembers(packetID, 'Reader') packetWriters = self.findProjectMembers(packetID, 'Writer') newPacket = Packet(packetID, packetName, packetDescr, packetOwner, isPrivate, packetReaders, packetWriters) return newPacket
def login(): data = json.loads(request.data) username = data.get('username') password = data.get('password') user = UserHandler.to_dict(UserHandler().log_user(username, password)) history = GameHandler().get_player_history(user['user_id']) user['history'] = history return json.dumps(user)
def setUp(self): stdscr = curses.initscr() curses.start_color() self.folder_handler = FolderHandler(default_path) self.display_handler = DisplayHandler(self.folder_handler, stdscr) self.user = UserHandler(self.folder_handler, self.display_handler, stdscr)
def addLabMember(self, labID, memberID): db = self.db cursor = self.cursor uHandler = UserHandler(db, cursor) if uHandler.existsUser(memberID): cursor.execute("UPDATE Users_tbl SET labID=" + `labID` + " WHERE userID=" + `memberID` + " AND status='ACTIVE'")
def createProject(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO #print `form` # Handlers pHandler = ProjectDatabaseHandler(db, cursor) uHandler = UserHandler(db, cursor) # Get form values projectID = form.getvalue("packetID") ownerID = form.getvalue("packetOwner") # get owner's name packetOwner = uHandler.getUserByID(ownerID) packetName = form.getvalue("packetName") packetDescription = form.getvalue("packetDescription") # private or public if form.getvalue("private_or_public") == "public": isPrivate = False else: isPrivate = True # Lists of project readers & editors # These are lists of INTEGER USER IDs!!!!! # A User instance needs to be created for each!!!!!!! projectReaderIDs = form.getlist("readersTargetList") projectWriterIDs = form.getlist("writersTargetList") projectReaders = [] projectWriters = [] for rID in projectReaderIDs: tmpReader = uHandler.getUserByID(rID) projectReaders.append(tmpReader) for wID in projectWriterIDs: tmpWriter = uHandler.getUserByID(wID) # Now check if the user is an OpenFreezer writer - otherwise cannot be made Writer on a project if tmpWriter.getCategory() != 'Reader': projectWriters.append(tmpWriter) newProject = Packet(projectID, packetName, packetDescription, packetOwner, isPrivate, projectReaders, projectWriters) packetID = pHandler.insertPacket( newProject) # new project is empty by default self.showProjectDetails('view', newProject)
def modifyProject(self, form): #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO #print `form` db = self.__db cursor = self.__cursor hostname = self.__hostname # Handlers pHandler = ProjectDatabaseHandler(db, cursor) uHandler = UserHandler(db, cursor) # Get project ID from form projectID = form.getvalue("packetID") ownerID = form.getvalue("packetOwner") # get owner's name packetOwner = uHandler.getUserByID(ownerID) packetName = form.getvalue("packetName") packetDescription = form.getvalue("packetDescription") # access type: accessType = form.getvalue("private_or_public") if accessType == 'Private': isPrivate = True else: isPrivate = False # Lists of project readers & editors # In this view, these are list of INTEGER USER IDs # A User instance needs to be created for each!!!!!!! projectReaderIDs = form.getlist("projectReaders") projectWriterIDs = form.getlist("projectWriters") projectReaders = [] projectWriters = [] for rID in projectReaderIDs: tmpReader = uHandler.getUserByID(rID) projectReaders.append(tmpReader) for wID in projectWriterIDs: tmpWriter = uHandler.getUserByID(wID) projectWriters.append(tmpWriter) newProject = Packet(projectID, packetName, packetDescription, packetOwner, isPrivate, projectReaders, projectWriters) self.showProjectDetails('edit', newProject)
def __init__(self, stdscr): # initialize user handler self.folder_handler = FolderHandler(default_path) self.display_handler = DisplayHandler(self.folder_handler, stdscr) self.user_handler = UserHandler(self.folder_handler, self.display_handler, stdscr) self.display_handler.print_path_line() self.display_handler.print_folder_content(0) self.user_handler.set_cursor() self.user_handler.window.refresh()
def deleteAllMembers(self, labID): db = self.db cursor = self.cursor uHandler = UserHandler(db, cursor) members = self.findMembers(labID) for mem in members: memID = mem.getUserID() uHandler.deleteUser(memID)
def createProject(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO #print `form` # Handlers pHandler = ProjectDatabaseHandler(db, cursor) uHandler = UserHandler(db, cursor) # Get form values projectID = form.getvalue("packetID") ownerID = form.getvalue("packetOwner") # get owner's name packetOwner = uHandler.getUserByID(ownerID) packetName = form.getvalue("packetName") packetDescription = form.getvalue("packetDescription") # private or public if form.getvalue("private_or_public") == "public": isPrivate = False else: isPrivate = True # Lists of project readers & editors # These are lists of INTEGER USER IDs!!!!! # A User instance needs to be created for each!!!!!!! projectReaderIDs = form.getlist("readersTargetList") projectWriterIDs = form.getlist("writersTargetList") projectReaders = [] projectWriters = [] for rID in projectReaderIDs: tmpReader = uHandler.getUserByID(rID) projectReaders.append(tmpReader) for wID in projectWriterIDs: tmpWriter = uHandler.getUserByID(wID) # Now check if the user is an OpenFreezer writer - otherwise cannot be made Writer on a project if tmpWriter.getCategory() != 'Reader': projectWriters.append(tmpWriter) newProject = Packet(projectID, packetName, packetDescription, packetOwner, isPrivate, projectReaders, projectWriters) packetID = pHandler.insertPacket(newProject) # new project is empty by default self.showProjectDetails('view', newProject)
def user_list(): page_index = request.args.get('page_index') user_handler = UserHandler() users = user_handler.get_user_list(page_index) if page_index else user_handler.get_user_list() return jsonify({'res': 'ok', 'data': [{ 'id': user.id, 'name': user.name, 'age': user.age, 'sex': user.sex, 'address': user.address, } for user in users]})
def add_user(): if request.method == 'POST': data = deepcopy(request.json) if request.is_json else deepcopy(request.form) user_handler = UserHandler() result, result_msg = user_handler.add_user(data) if not result: return jsonify({'res': 'error', 'msg': result_msg}) else: return jsonify({'res': 'ok', 'msg': result_msg}) else: return jsonify({'res': 'error', 'msg': 'request must be post'})
def addLabMember(self, labID, memberID): db = self.db cursor = self.cursor uHandler = UserHandler(db, cursor) if uHandler.existsUser(memberID): cursor.execute("UPDATE Users_tbl SET labID=" + ` labID ` + " WHERE userID=" + ` memberID ` + " AND status='ACTIVE'")
def save_user(request): user_dict = None response = Response().USER_DOES_NOT_EXIST try: user_dict = json.loads(request.body) except Exception: response = Response().INCOMING_DATA_CORRUPTED pass if user_dict: user_handler = UserHandler(user_dict=user_dict) response = user_handler.save_user() return HttpResponse(json.loads({'response':response}))
def get_user(): user_id = request.args.get('user_id') if not user_id: UserHandler().get_all_users() user = UserHandler().get_user(user_id) if not user: raise InvalidUsage("User %s not found" % user_id, status_code=404) user = UserHandler.to_dict(user) history = GameHandler().get_player_history(user_id) user['history'] = history return json.dumps(user)
def sign_in(): if request.method == 'POST': data = deepcopy(request.json) if request.is_json else deepcopy(request.form) user_id = data.get('user_id') user_handler = UserHandler() result, result_msg = user_handler.sign_in(user_id) if not result: return jsonify({'res': 'error', 'msg': result_msg}) else: return jsonify({'res': 'ok', 'msg': result_msg}) else: return jsonify({'res': 'error', 'msg': 'request must be post'})
def handle(self): db = self.__db cursor = self.__cursor form = cgi.FieldStorage(keep_blank_values="True") uHandler = UserHandler(db, cursor) #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO #print `form` if form.has_key("username"): # store the user ID for use throughout the session; add to other views in addition to create in PHP currUname = form.getvalue("username") currUser = uHandler.getUserByDescription(currUname) Session.setUser(currUser) elif form.has_key("curr_user_id"): currUID = form.getvalue("curr_user_id") currUser = uHandler.getUserByID(currUID) Session.setUser(currUser) if form.has_key("create_project"): self.createProject(form) elif form.has_key("modify_project"): self.modifyProject(form) elif form.has_key("save_project"): self.saveProject(form) elif form.has_key("cancel_project"): self.cancelModification(form) elif form.has_key("delete_project"): self.deleteProject(form) elif form.has_key("view_project"): self.printProjectInfo(form) elif form.has_key("view_packet"): # go to project view from User detailed view self.viewPacket(form) # Oct. 12, 2010 elif form.has_key("search_project_by_keyword"): self.findPacket(form) cursor.close() db.close()
def new_user(): """ create a user """ data = json.loads(request.data) username = data.get('username') password = data.get('password') try: user = UserHandler().add_user(username, password) except DuplicateKeyError as e: raise InvalidUsage(str(e), status_code=403) return json.dumps(UserHandler.to_dict(user))
def get_user(request): user_dict = None response = Response().USER_DOES_NOT_EXIST user = {} try: user_dict = json.loads(request.body) except Exception: response = Response().INCOMING_DATA_CORRUPTED pass if user_dict: user_handler = UserHandler(user_dict=user_dict) user = user_handler.user_as_dict() response = user_handler.response_number return HttpResponse(json.loads({'response':response, 'user':user}))
def viewUser(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO #print `form` uHandler = UserHandler(db, cursor) userID = form.getvalue("view_user") newUser = uHandler.getUserByID(userID) self.printUserInfo('view', newUser)
def viewUser(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname # print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! # print # DITTO # print `form` uHandler = UserHandler(db, cursor) userID = form.getvalue("view_user") newUser = uHandler.getUserByID(userID) self.printUserInfo("view", newUser)
def handle(self): # For convenience, create local copies of global variables db = self.__db cursor = self.__cursor hostname = self.__hostname uHandler = UserHandler(db, cursor) form = cgi.FieldStorage(keep_blank_values="True") #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO #print `form` if form.has_key("loginsubmit"): username = form.getvalue("loginusername_field") passwd = form.getvalue("loginpassword_field") if self.checkPermissions(username, passwd): session = SimpleCookie(os.environ['HTTP_COOKIE']) phpsessid = session['PHPSESSID'].value session["userinfo"] = self.__user utils.redirect(os.environ['HTTP_REFERER'])
class ProcessHandler(webapp.RequestHandler): def __init__(self): self.template_renderer = Renderer('process.html') self.user_handler = UserHandler() self.user_obj = None def setUser(self): self.user_obj = self.user_handler.handleUser() def get(self, step): self.setUser() #self.response.out.write('in step %s' % step) if step == PROCESS_STEP_1_START: return self.ProcessStep1() elif step == PROCESS_STEP_2_EXECUTE: return self.ProcessStep2() else: pass def ProcessStep1(self): self.template_renderer.template_values['process_step'] = '1' self.template_renderer.template_values['next_step'] = PROCESS_STEP_2_EXECUTE self.render() def ProcessStep2(self): self.template_renderer.template_values['process_step'] = '2' self.render() def render(self): self.template_renderer.template_values['token'] = self.user_obj.spreadsheet_session_token self.response.out.write(self.template_renderer.render())
def cancelUserModification(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO #print `form` uHandler = UserHandler(db, cursor) pHandler = ProjectDatabaseHandler(db, cursor) userID = int(form.getvalue('userID')) newUser = uHandler.getUserByID(userID) self.printUserInfo('view', newUser)
def get_users(self, user_filename): '''Get complete list of all users. ''' users = set() user_handler = UserHandler() try: with open(user_filename, 'r') as user_file: for entry in user_file: entry = user_handler.format_user_followers_entry(entry) new_users = user_handler.get_new_users(users, entry) users.update(new_users) return users except IOError: print('The file cannot be opened.') except FormatError: print('Tweet file entry incorrectly formatted')
def cancelUserModification(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname # print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! # print # DITTO # print `form` uHandler = UserHandler(db, cursor) pHandler = ProjectDatabaseHandler(db, cursor) userID = int(form.getvalue("userID")) newUser = uHandler.getUserByID(userID) self.printUserInfo("view", newUser)
def get_user_followers_mapping(self, user_filename): '''Get mapping of users to the users they follow. ''' user_handler = UserHandler() user_followers_mapping = {} try: with open(user_filename, 'r') as user_file: for entry in user_file: entry = user_handler.format_user_followers_entry(entry) user_followers = user_handler.update_user_followers_mapping( user_followers_mapping, entry) user_followers_mapping[ user_followers[0]] = user_followers[1] return user_followers_mapping except IOError: print('The file cannot be opened.') except FormatError: print('Tweet file entry incorrectly formatted')
def get(self): self.user_prefs = UserHandler.handleUser() self.template_renderer.self_uri = self.request.url if self.request.get('token'): self.upgradeToken() else: self.handleAuthSubLogin() self.render()
def findAllProjects(self, isPrivate=""): #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO db = self.db cursor = self.cursor uHandler = UserHandler(db, cursor) projects = [] if isPrivate == "": cursor.execute("SELECT packetID, ownerID, packetName, packetDescription FROM Packets_tbl WHERE status='ACTIVE'") results = cursor.fetchall() for result in results: packetID = int(result[0]) ownerID = int(result[1]) packetName = result[2] packetDescr = result[2] packetOwner = uHandler.getUserByID(ownerID) newPacket = Packet(packetID, packetName, packetDescr, packetOwner) projects.append(newPacket) else: cursor.execute("SELECT packetID, ownerID, packetName, packetDescription FROM Packets_tbl WHERE is_private=" + `isPrivate` + " AND status='ACTIVE'") results = cursor.fetchall() for result in results: packetID = int(result[0]) ownerID = int(result[1]) packetName = result[2] packetDescr = result[2] packetOwner = uHandler.getUserByID(ownerID) newPacket = Packet(packetID, packetName, packetDescr, packetOwner) projects.append(newPacket) return projects
def login(event, context): body = json.loads(event['body']) user_handler = UserHandler(body) result = {} if user_handler.login_body_checker(): result = user_handler.verify_user() return { 'statusCode': 200, 'headers': user_handler.headers, 'body': json.dumps(result) } result['status'] = False result['message'] = "Credentials check failed" return { 'statusCode': 200, 'headers': user_handler.headers, 'body': json.dumps(result) }
def modifyUser(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname uHandler = UserHandler(db, cursor) lHandler = LabHandler(db, cursor) pHandler = ProjectDatabaseHandler(db, cursor) ucMapper = UserCategoryMapper(db, cursor) category_Name_ID_Map = ucMapper.mapCategoryNameToID() # print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! # print # DITTO # print `form` # Get form values userID = int(form.getvalue("userID")) newUser = uHandler.getUserByID(userID) """ labID = int(form.getvalue("labID")) username = form.getvalue("username") firstName = form.getvalue("firstName") lastName = form.getvalue("lastName") description = firstName + " " + lastName email = form.getvalue("email") passwd = form.getvalue("password") """ readProjects = pHandler.findMemberProjects(userID, "Reader") newUser.setReadProjects(readProjects) writeProjects = pHandler.findMemberProjects(userID, "Writer") newUser.setWriteProjects(writeProjects) self.printUserInfo("edit", newUser)
def modifyUser(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname uHandler = UserHandler(db, cursor) lHandler = LabHandler(db, cursor) pHandler = ProjectDatabaseHandler(db, cursor) ucMapper = UserCategoryMapper(db, cursor) category_Name_ID_Map = ucMapper.mapCategoryNameToID() #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO #print `form` # Get form values userID = int(form.getvalue("userID")) newUser = uHandler.getUserByID(userID) ''' labID = int(form.getvalue("labID")) username = form.getvalue("username") firstName = form.getvalue("firstName") lastName = form.getvalue("lastName") description = firstName + " " + lastName email = form.getvalue("email") passwd = form.getvalue("password") ''' readProjects = pHandler.findMemberProjects(userID, 'Reader') newUser.setReadProjects(readProjects) writeProjects = pHandler.findMemberProjects(userID, 'Writer') newUser.setWriteProjects(writeProjects) self.printUserInfo('edit', newUser)
def new_game(self, user_id): content = ContentHandler().get_content(played=self.get_user_history(user_id)) battle_tag = "%s#%d" % (UserHandler().get_user(user_id)['username'], random.randint(1111, 9999)) entry = { 'battle_tag': battle_tag, 'content_id': content['_id'], 'users': {user_id: {'result': []}}, 'status': 'requested' } result = self.game.find_one({'_id': self.game.insert_one(entry).inserted_id}) result['title'] = content['title'] log.info(result) return result
def deleteUser(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname uHandler = UserHandler(db, cursor) pHandler = ProjectDatabaseHandler(db, cursor) # print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! # print # DITTO # print `form` uid = form.getvalue("userID") # list of user IDs # deletionCandidates = form.getlist("deletionCandidates") # Delete users and revoke their access to projects # for uid in deletionCandidates: uHandler.deleteUser(uid) pHandler.deleteMemberFromllProjects(uid) utils.redirect(hostname + "User.php?View=2&Del=1")
def deleteUser(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname uHandler = UserHandler(db, cursor) pHandler = ProjectDatabaseHandler(db, cursor) #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO #print `form` uid = form.getvalue("userID") # list of user IDs #deletionCandidates = form.getlist("deletionCandidates") # Delete users and revoke their access to projects #for uid in deletionCandidates: uHandler.deleteUser(uid) pHandler.deleteMemberFromllProjects(uid) utils.redirect(hostname + "User.php?View=2&Del=1")
def setUp(self): stdscr = curses.initscr() curses.start_color() self.folder_handler = FolderHandler(default_path) self.display_handler = DisplayHandler(self.folder_handler, stdscr) self.user = UserHandler(self.folder_handler, self.display_handler, stdscr) self.functions_dic = {} for name, cls in inspect.getmembers( importlib.import_module("available_functions"), inspect.isclass): function = cls(self) self.functions_dic.update({type(function).__name__: function})
def saveProject(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO #print `form` # Handlers pHandler = ProjectDatabaseHandler(db, cursor) uHandler = UserHandler(db, cursor) # Get project ID from form projectID = form.getvalue("packetID") ownerID = form.getvalue("packetOwner") # get owner's name packetOwner = uHandler.getUserByID(ownerID) packetName = form.getvalue("packetName") packetDescription = form.getvalue("packetDescription") # private or public if form.getvalue("private_or_public") == "public": isPrivate = False else: isPrivate = True # Lists of project readers & editors # Updated Sept. 3/08: Do NOT save readers for a public project if isPrivate: projectReaderIDs = form.getlist("readersList") else: projectReaderIDs = [] # writers are always needed projectWriterIDs = form.getlist("writersList") projectReaders = [] projectWriters = [] for rID in projectReaderIDs: tmpReader = uHandler.getUserByID(rID) projectReaders.append(tmpReader) for wID in projectWriterIDs: tmpWriter = uHandler.getUserByID(wID) # check categories - a Reader cannot be given Write access to a project if tmpWriter.getCategory() != 'Reader': projectWriters.append(tmpWriter) #projectWriters.append(tmpWriter) # Update database values pHandler.updatePacket(projectID, ownerID, packetName, packetDescription, isPrivate, projectReaderIDs, projectWriterIDs) # Output new values newProject = Packet(projectID, packetName, packetDescription, packetOwner, isPrivate, projectReaders, projectWriters) self.showProjectDetails('view', newProject)
def printProjectInfo(self, cmd, project): dbConn = DatabaseConn() hostname = dbConn.getHostname() # to define form action URL db = dbConn.databaseConnect() cursor = db.cursor() uHandler = UserHandler(db, cursor) lHandler = LabHandler(db, cursor) gOut = GeneralOutputClass() currUser = Session.getUser() if cmd == 'view': projectID = project.getNumber() projectOwner = project.getOwner() ownerName = projectOwner.getFullName() ownerID = projectOwner.getUserID() projectName = project.getName() projectDescr = project.getDescription() # private or public isPrivate = project.isPrivate() if isPrivate: accessType = 'Private' else: accessType = 'Public' # Only allow modification by owner or admin AND disallow project deletion if there are reagents in it!!! modify_disabled = True delete_disabled = True if (currUser.getUserID() == ownerID) or (currUser.getCategory() == 'Admin'): modify_disabled = False if project.isEmpty(): delete_disabled = False # Aug. 18/08: Changed b/c of new format #content = gOut.printHeader() + gOut.printMainMenu() content = gOut.printHeader() content += ''' <FORM name="project_form" method="POST" action="%s"> <!-- pass current user as hidden form field --> <INPUT type="hidden" ID="username_hidden" NAME="username"''' content += "value=\"" + currUser.getFullName() + "\">" content += ''' <TABLE height="100%%"> <TABLE width="770px" cellpadding="5px" cellspacing="5px" class="detailedView_tbl"> <TR> <TD class="detailedView_heading" style="white-space:nowrap;"> PROJECT DETAILS PAGE </TD> <TD class="detailedView_heading" style="text-align:right"> ''' content += "<INPUT TYPE=\"submit\" name=\"modify_project\" value=\"Modify Project\"" if modify_disabled: content += " disabled>" else: content += ">" content += "<INPUT TYPE=\"submit\" style=\"margin-left:2px;\" name=\"delete_project\" value=\"Delete Project\" onClick=\"return confirmDeleteProject();\"" if modify_disabled or delete_disabled: content += " disabled>" else: content += ">" content += ''' </TD> </TR> <TR> <TD class="projectDetailedViewName"> Project # </TD> <TD class="detailedView_value" width="87%%"> %d <INPUT TYPE="hidden" name="packetID" value="%d"> </TD> </TR> <TR> <TD class="projectDetailedViewName"> Project Owner: </TD> <TD class="detailedView_value"> %s <INPUT TYPE="hidden" name="packetOwner" value="%d"> </TD> </TR> <TR> <TD class="projectDetailedViewName"> Project Name: </TD> <TD class="detailedView_value"> %s <INPUT TYPE="hidden" name="packetName" value="%s"> </TD> </TR> <TR> <TD class="projectDetailedViewName"> Project Description: </TD> <TD class="detailedView_value"> %s <INPUT TYPE="hidden" name="packetDescription" value="%s"> </TD> </TR> <TR> <TD class="projectDetailedViewName"> Access type: </TD> <TD class="detailedView_value"> %s <INPUT TYPE="hidden" name="private_or_public" value="%s"> </TD> </TR> <TR> <TD colspan="2"> <HR/> </TD> </TR> ''' # Now here, show or hide members section depending on the user's access level # Condition is the same as for determining whether modification is allowed - so use 'modify_disabled' variable if not modify_disabled: content += ''' <TR> <TD class="projectDetailedViewName"> Project Members: </TD> <TD> </TD> </TR> <TR> <TD class="detailedView_value" colspan="2"> <TABLE width="100%%"> <TR> <TD style="font-weight:bold; padding-left:10px" width="30%%"> Readers: </TD> <TD style="font-weight:bold; padding-left:10px"> Writers: </TD> </TR> <TR> <TD class="detailedView_value" style="vertical-align:top"> <UL> ''' if not isPrivate: content += "All OpenFreezer Users" else: # maintain the indent readers = project.getReaders() # sort by labs labs = [] rdrLabs = {} # First, iterate over readers list to extract all the labs for rdr in readers: lab = rdr.getLab().getID() if lab not in labs: labs.append(lab) # Now iterate over the list of labs and link its readers to it for lab in labs: tmpRdrs = [] # list of members in one lab for rdr in readers: tmpLab = rdr.getLab().getID() if tmpLab == lab: # append reader to list of members of this lab if rdrLabs.has_key(lab): tmpRdrs = rdrLabs[lab] tmpRdrs.append(rdr) rdrLabs[lab] = tmpRdrs #for rdr in readers: for lab_id in rdrLabs.keys(): rdrs = rdrLabs[lab_id] # list of objects!! tmp_lab_name = lHandler.findLabName(lab_id) # print out the lab name if currUser.getCategory() == 'Admin': content += "<span class=\"linkShow\" style=\"color:#2E8B57\" onClick=\"goToLabViewFromProject(" + `lab_id` + ");\">" + tmp_lab_name + "</span><BR/>" else: content += "<span style=\"color:#2E8B57\">" + tmp_lab_name + "</span><BR/>" # print reader names for rdr in rdrs: content += "<INPUT TYPE=\"hidden\" name=\"projectReaders\" value=\"" + `rdr.getUserID()` + "\"></INPUT>" # Only show hyperlinks if the viewer is an Admin; otherwise just output plain names if currUser.getCategory() == 'Admin': content += "<LI style=\"list-style:none; padding-left:6px;\">-- <span class=\"linkShow\" onClick=\"redirectToUserFromProject(" + `rdr.getUserID()` + ");\">" + rdr.getFullName() + "</span></LI>" else: content += "<LI style=\"list-style:none; padding-left:6px;\">-- " + rdr.getFullName() + "</LI>" content += ''' </UL> </TD> <TD class="detailedView_value" style="width:250px; vertical-align:top"> <UL> ''' writers = project.getWriters() # sort them by lab too, same as for readers labs = [] wrtrLabs = {} # First, iterate over readers list to extract all the labs for wrtr in writers: lab = wrtr.getLab().getID() if lab not in labs: labs.append(lab) # Now iterate over the list of labs and link its readers to it for lab in labs: tmpWrtrs = [] # list of members in one lab for wrtr in writers: tmpLab = wrtr.getLab().getID() if tmpLab == lab: # append reader to list of members of this lab if wrtrLabs.has_key(lab): tmpWrtrs = wrtrLabs[lab] tmpWrtrs.append(wrtr) wrtrLabs[lab] = tmpWrtrs for lab_id in wrtrLabs.keys(): wrtrs = wrtrLabs[lab_id] # list of objects!! tmp_lab_name = lHandler.findLabName(lab_id) # print out the lab name if currUser.getCategory() == 'Admin': content += "<span class=\"linkShow\" style=\"color:#2E8B57\" onClick=\"goToLabViewFromProject(" + `lab_id` + ");\">" + tmp_lab_name + "</span><BR/>" else: content += "<span style=\"color:#2E8B57\" " + `lab_id` + ");\">" + tmp_lab_name + "</span><BR/>" for wrtr in wrtrs: content += "<INPUT TYPE=\"hidden\" name=\"projectWriters\" value=\"" + `wrtr.getUserID()` + "\">" if currUser.getCategory() == 'Admin': content += "<LI style=\"list-style:none; padding-left:6px;\">-- <span class=\"linkShow\" onClick=\"redirectToUserFromProject(" + `wrtr.getUserID()` + ");\">" + wrtr.getFullName() + "</span></LI>" else: content += "<LI style=\"list-style:none; padding-left:6px;\">-- " + wrtr.getFullName() + "</LI>" content += ''' </UL> </TD> </TR> </TABLE> </TD> </TR> </TABLE> </FORM> <FORM id="viewUserForm" method="POST" action="%s"> <INPUT type="hidden" id="view_user_hidden" name="view_user"> <INPUT type="hidden" ID="curr_userid_hidden" NAME="curr_user_id" value="%d"> </FORM> <FORM id="viewLabForm" method="POST" action="%s"> <INPUT type="hidden" ID="curr_userid_hidden" NAME="curr_user_id" value="%d"> <INPUT type="hidden" id="view_lab_hidden" name="view_lab"> </FORM> </TABLE> ''' content += gOut.printFooter() else: content += ''' </TABLE> </FORM> </TABLE> ''' content += gOut.printFooter() # and here, depending on what sections of the project view were printed, the number of arguments would vary if not modify_disabled: page_content = content % (hostname + "cgi/project_request_handler.py", projectID, projectID, ownerName, ownerID, projectName, projectName, projectDescr, projectDescr, accessType, accessType, hostname + "cgi/user_request_handler.py", currUser.getUserID(), hostname + "cgi/user_request_handler.py", currUser.getUserID()) else: page_content = content % (hostname + "cgi/project_request_handler.py", projectID, projectID, ownerName, ownerID, projectName, projectName, projectDescr, projectDescr, accessType, accessType) print "Content-type:text/html" # THIS IS PERMANENT; DO NOT REMOVE print # DITTO print page_content elif cmd == 'edit': projectID = project.getNumber() projectOwner = project.getOwner() ownerName = projectOwner.getFullName() ownerID = projectOwner.getUserID() projectName = project.getName() projectDescr = project.getDescription() isPrivate = project.isPrivate() content = gOut.printHeader() #content += gOut.printMainMenu() content += ''' <FORM name="project_form" method="POST" action="%s"> <!-- pass current user as hidden form field --> <INPUT type="hidden" ID="username_hidden" NAME="username"''' content += "value=\"" + currUser.getFullName() + "\">" content += ''' <TABLE width="770px" cellpadding="5px" cellspacing="5px" style="border:1px solid black" frame="box" rules="rows"> <TR> <TD colspan="3" style="padding-left:200px; text-align:center"> <span style="color:#0000FF; font-weight:bold">MODIFY PROJECT </span> <span style="color:#FF0000; font-weight:bold">%d</span> <INPUT TYPE="hidden" name="packetID" value="%d"> <INPUT TYPE="submit" style="margin-left:200px;" name="save_project" value="Save" onClick=\"alert('Please note: If your project writers list contains names of users who have read-only access to OpenFreezer, their names will be removed from the list during saving.'); addProjectOwnerToWritersList(); selectAllElements('readers_target_list'); selectAllElements('writers_target_list'); return verifyProjectOwner('projectOwnersList') && verifyProjectName('packet_name') && verifyProjectDescr('packet_descr') && verifyMembers('readers_target_list') && verifyMembers('writers_target_list');\"> <INPUT TYPE="submit" style="margin-left:20px;" name="cancel_project" value="Cancel"> </TD> </TR> <TR> <TD class="projectDetailedViewName"> Project Owner: </TD> <TD class="detailedView_value" colspan="2"> <SELECT ID="projectOwnersList" name="packetOwner"> ''' # Get list of all potential project owners - users with 'CREATOR' or higher privileges # Returns list of User **objects** creators = uHandler.findAllMembersInCategory('Creator', False, '<=') creatorsDict = {} # name, uid for creator in creators: uid = creator.getUserID() name = creator.getFullName() creatorsDict[name] = uid names = creatorsDict.keys() names.sort() #print "Content-type:text/html" #print for name in names: #print name uid = creatorsDict[name] #print uid #print ownerID if uid == ownerID: content += "<OPTION SELECTED value=" + `uid` + ">" + name + "</OPTION>" else: content += "<OPTION value=" + `uid` + ">" + name + "</OPTION>" content += ''' </SELECT> <DIV ID="projectOwnerWarning" STYLE="display:none; color:#FF0000; font-weight:normal;"> <BR>Please select a name from the list above. </DIV> </TD> </TR> <TR> <TD class="projectDetailedViewName"> Project Name: </TD> <TD class="detailedView_value" colspan="2"> <INPUT TYPE="text" id="packet_name" name="packetName" value="%s"> <DIV ID="projectNameWarning" STYLE="display:none; color:#FF0000; font-weight:normal;"> <BR>Please provide a project name. </DIV> </TD> </TR> <TR> <TD class="projectDetailedViewName"> Project Description: </TD> <TD class="detailedView_value" colspan="2"> <INPUT TYPE="text" id="packet_descr" name="packetDescription" value="%s"> <DIV ID="projectDescrWarning" STYLE="display:none; color:#FF0000; font-weight:normal;"> <BR>Please provide a project description. </DIV> </TD> </TR> <TR> <TD class="projectDetailedViewName"> Access type: </TD> <TD class="detailedView_value" style="width:400px"> ''' if not isPrivate: content += "<INPUT TYPE=\"RADIO\" NAME=\"private_or_public\" VALUE=\"public\" checked>Public " content += "<INPUT TYPE=\"RADIO\" NAME=\"private_or_public\" VALUE=\"private\">Private" else: content += "<INPUT TYPE=\"RADIO\" NAME=\"private_or_public\" VALUE=\"public\">Public " content += "<INPUT TYPE=\"RADIO\" NAME=\"private_or_public\" VALUE=\"private\" checked>Private" content += ''' </TD> </TR> <TR> <TD class="projectDetailedViewName"> Project Members: </TD> <TD class="detailedView_value" colspan="2"> </TD> </TR> <TR> <TD class="detailedView_value" colspan="3"> Edit existing project members lists: </TD> </TR> <TR> <TD style="width:100px"> <SELECT multiple size="10" id="readers_target_list" name="readersList"> ''' # Readers and writers associated with this project currReaders = project.getReaders() currWriters = project.getWriters() # Since object comparison is done by reference, cannot check if a User object returned by findAllMembers is a member of this project by using 'in array'. Need to compare user IDs explicitly currReaderIDs = [] currWriterIDs = [] currReaderNames = [] currWriterNames = [] currReadersDict = {} # name, id currWritersDict = {} # need lab IDs too - to match members to their labs when moved between lists, but having a 'memberID, labID' dictionary is too clumsy. Easiest approach: have 'memberID, Member Object' dictionary currReaderObjDict = {} # id, User object currWriterObjDict = {} for r in currReaders: rID = r.getUserID() rName = r.getFullName() # associate rID with its containing object currReaderObjDict[rID] = r currReaderIDs.append(rID) currReaderNames.append(rName) currReadersDict[rName] = rID for w in currWriters: wID = w.getUserID() wName = w.getFullName() currWriterObjDict[wID] = w currWriterIDs.append(wID) currWriterNames.append(wName) currWritersDict[wName] = wID currReaderNames.sort() currWriterNames.sort() for rName in currReaderNames: rID = currReadersDict[rName] rdr = currReaderObjDict[rID] rdrLabID = rdr.getLab().getID() #content += "<OPTION id=" + `rID` + " value=" + `rID` + ">" + rName + "</OPTION>" # June 28/07: Include labID in the option id content += "<OPTION id=\"user_" + `rID` + "_lab_" + `rdrLabID` + "\" value=" + `rID` + ">" + rName + "</OPTION>" content += ''' </SELECT> <BR/> <INPUT TYPE="checkbox" style="margin-top:10px" onClick="selectAll(this.id, 'readers_target_list')" id="select_all_reader_chkbx"> Select All</INPUT> </TD> <TD width="30px"> <input onclick="addMembers('readers_target_list', 'write')" value=" Make Writer >>" type="button"></INPUT><BR/> <input style="margin-top:10px;" onclick="addMembers('writers_target_list', 'read')" value="<< Make Reader" type="button"></INPUT><BR/> <input style="margin-top:10px;" onclick="removeProjectMembers()" value="Remove Selected" type="button"></INPUT> </TD> <TD> <SELECT multiple size="10" id="writers_target_list" name="writersList"> ''' for wName in currWriterNames: wID = currWritersDict[wName] wrtr = currWriterObjDict[wID] wrtrLabID = wrtr.getLab().getID() #content += "<OPTION id=" + `wID` + " value=" + `wID` + ">" + wName + "</OPTION>" # June 28/07: Include labID in the option id content += "<OPTION id=\"user_" + `wID` + "_lab_" + `wrtrLabID` + "\" value=" + `wID` + ">" + wName + "</OPTION>" content += ''' </SELECT> <BR/> <INPUT style="margin-top:10px;" TYPE="checkbox" onClick="selectAll(this.id, 'writers_target_list')" id="select_all_writer_chkbx"> Select All</INPUT> </TD> </TR> <TR> <TD class="detailedView_value" colspan="3"> Add new members to this project: </TD> </TR> <TR> <TD class="detailedView_value" colspan="3"> Laboratory: <SELECT id="labList" name="labs" onChange="showLabMembersList()"> ''' # fetch lab list - Updated August 90/7: Fetch ALL labs, with any access - then if a read-only lab has members with higher access, would show these members in list #labs = lHandler.findAllLabs('Writer', '<=') labs = lHandler.findAllLabs() # sort lab names alphabetically labNames = [] labsDict = {} # name, id for labID in labs.keys(): labName = labs[labID] labNames.append(labName) labsDict[labName] = labID labNames.sort() currLab = projectOwner.getLab() currLabID = currLab.getID() #for labID in labs.keys(): for labName in labNames: #labName = labs[labID] labID = labsDict[labName] if labID == currLabID: content += "<OPTION SELECTED id='" + `labID` + "' NAME='lab_optn' value=" + `labName` + ">" + labName + "</OPTION>" else: content += "<OPTION id='" + `labID` + "' NAME='lab_optn' value=" + `labName` + ">" + labName + "</OPTION>" content += ''' </SELECT> </TD> </TR> <TR> <TD width="100px"> ''' # For each lab, print a list of its members for labID in labs.keys(): # First, fetch a list of users # These are **User instances** - need to get their names and IDs for comparison # August 9/07: Don't fetch only writers, fetch readers too - it's up to the project owner to grant them access to the project #writers = uHandler.findAllMembersInCategory('Writer', True, '<=', labID) writers = uHandler.findAllMembersInCategory('Reader', True, '<=', labID) writersDict = {} # name, uid writersObjDict = {} # id, User object # Fetch user IDs and sort their names alphabetically for writer in writers: name = writer.getFullName() uid = writer.getUserID() labID = (writer.getLab()).getID() writersDict[name] = uid writersObjDict[uid] = writer names = writersDict.keys() names.sort() # Show members for one lab at a time if labID == currLabID: display = "inline" else: display = "none" content += "<SELECT MULTIPLE id=\"lab_source_list_" + `labID` + "\" name=\"labSourceMembers_" + `labID` + "\" SIZE=\"10\" style=\"display:" + display + "\">" for name in names: uid = writersDict[name] labID = writersObjDict[uid].getLab().getID() if uid not in currReaderIDs and uid not in currWriterIDs: #content += "<OPTION value=" + `uid` + ">" + name + "</OPTION>" content += "<OPTION id=\"user_" + `uid` + "_lab_" + `labID` + "\" value=" + `uid` + ">" + name + "</OPTION>" content += "</SELECT>" content += ''' <BR/> <INPUT TYPE="checkbox" style="margin-top:8px" onClick="selectAll(this.id, 'lab_source_list_' + getSelectedLab())" id="add_all_chkbx"> Select All Members</INPUT> </TD> <TD colspan="2" style="vertical-align:top"> Add selected members to: <P style="font-size:9pt; margin-top:5px;"> <input type="radio" id="access_level_radio_read" name="access_levels" value="read" checked>Readers list</INPUT><BR/> <input type="radio" id="access_level_radio_write" name="access_levels" value="write">Writers list</INPUT><BR/> <input style="margin-top:8px" onclick="addMembers('lab_source_list_' + getSelectedLab(), getSelectedRole('1'))" value="Go" type="button"></INPUT> <BR/> </P> </TD> </TR> </TABLE> </FORM> ''' content += gOut.printFooter() page_content = content % (hostname + "cgi/project_request_handler.py", project.getNumber(), project.getNumber(), project.getName(), project.getDescription()) print "Content-type:text/html" # THIS IS PERMANENT; DO NOT REMOVE print # DITTO print page_content
def printMainMenu(self): dbConn = DatabaseConn() hostname = dbConn.getHostname() # to define form action URL db = dbConn.databaseConnect() cursor = db.cursor() uHandler = UserHandler(db, cursor) # Aug. 20, 2010 pageMapper = SystemModuleMapper(db, cursor) pageLinkMap = pageMapper.mapPageNameLink() # Array of section names currentSectionNames = [] # Dictionary of links to names, with names as dictionary keys and links as values currentSectionLinks = {} # Added Nov. 10/06 by Marina - Classify each header as to what OF section it belongs menuTypes = {} # June 04/07 - Differentiate between 'public' and 'private' pages publicSectionNames = [] publicSectionLinks = [] publicSections = {} # Feb. 2, 2010: change menu layout (reflect HeaderFunctions.php code changes Jan. 12/10) submenu_links = {} submenu_types = {} menuitems = {} # Home currentSectionNames.append("Home") currentSectionLinks["Home"] = "../index.php" publicSections["Home"] = "index.php" # Reagent currentSectionNames.append("Reagent Tracker") currentSectionLinks["Reagent Tracker"] = "../Reagent.php?View=1" menuTypes["Reagent Tracker"] = "Reagent" publicSections["Reagent Tracker"] = "../Reagent.php?View=1" # Feb. 2, 2010 tmp_list = [] tmp_list.append("Reagents") tmp_list.append("Reagent Types") submenu_types["Reagent Tracker"] = tmp_list tmp_order_list = {} tmp_order_list[0] = "Add" tmp_order_list[1] = "Search" tmp_order_list[2] = "Statistics" submenu_order = {} submenu_order["Reagents"] = tmp_order_list tmp_list = {} tmp_list["Add"] = "../Reagent.php?View=2" tmp_list["Search"] = "../search.php?View=1" tmp_list["Statistics"] = "../Reagent.php?View=4" submenu_links["Reagents"] = tmp_list tmp_list = {} tmp_list["Add"] = "Add reagents" tmp_list["Search"] = "Search reagents" tmp_list["Statistics"] = "Statistics" menuitems["Reagents"] = tmp_list tmp_order_list = {} tmp_order_list[0] = "Add" tmp_order_list[1] = "Search" submenu_order["Reagent Types"] = tmp_order_list tmp_list = {} tmp_list["Add"] = "../Reagent.php?View=3" tmp_list["Search"] = "../Reagent.php?View=5" submenu_links["Reagent Types"] = tmp_list tmp_list = {} tmp_list["Add"] = "Add reagent types" tmp_list["Search"] = "Search reagent types" menuitems["Reagent Types"] = tmp_list # Locations currentSectionNames.append("Location Tracker") currentSectionLinks["Location Tracker"] = "../Location.php?View=1" menuTypes["Location Tracker"] = "Location" publicSections["Location Tracker"] = "../Location.php?View=1" # Feb. 2/10 tmp_list = [] tmp_list.append("Containers") tmp_list.append("Container Sizes") tmp_list.append("Container Types") submenu_types["Location Tracker"] = tmp_list tmp_order_list = {} tmp_order_list[0] = "Add" tmp_order_list[1] = "Search" submenu_order["Container Types"] = tmp_order_list tmp_order_list = {} tmp_order_list[0] = "Add" # tmp_order_list[1] = "Search" submenu_order["Container Sizes"] = tmp_order_list tmp_order_list = {} tmp_order_list[0] = "Add" tmp_order_list[1] = "Search" submenu_order["Containers"] = tmp_order_list tmp_list = {} tmp_list["Add"] = "../Location.php?View=6&Sub=2" tmp_list["Search"] = "../Location.php?View=6&Sub=4" submenu_links["Container Types"] = tmp_list tmp_list = {} tmp_list["Add"] = "Add container types" tmp_list["Search"] = "Search container types" menuitems["Container Types"] = tmp_list tmp_list = {} tmp_list["Add"] = "../Location.php?View=6&Sub=1" tmp_list["Search"] = "../Location.php?View=6&Sub=5" submenu_links["Container Sizes"] = tmp_list tmp_list = {} tmp_list["Add"] = "Add container sizes" # tmp_list["Search"] = "Search container sizes" menuitems["Container Sizes"] = tmp_list tmp_list = {} tmp_list["Add"] = "../Location.php?View=6&Sub=3" tmp_list["Search"] = "../Location.php?View=2" submenu_links["Containers"] = tmp_list tmp_list = {} tmp_list["Add"] = "Add containers" tmp_list["Search"] = "Search containers" menuitems["Containers"] = tmp_list # Projects currentSectionNames.append("Project Management") currentSectionLinks["Project Management"] = "../Project.php?View=1" menuTypes["Project Management"] = "Project" # Feb. 2/10 tmp_list = [] tmp_list.append("Projects") submenu_types["Project Management"] = tmp_list tmp_order_list = {} tmp_order_list[0] = "Add" tmp_order_list[1] = "Search" submenu_order["Projects"] = tmp_order_list tmp_list = {} tmp_list["Add"] = "../Project.php?View=1" tmp_list["Search"] = "../Project.php?View=2" submenu_links["Projects"] = tmp_list tmp_list = {} tmp_list["Add"] = "Add projects" tmp_list["Search"] = "Search projects" menuitems["Projects"] = tmp_list # Users and Labs currentSectionNames.append("User Management") currentSectionLinks["User Management"] = "../User.php" menuTypes["User Management"] = "User" currentSectionNames.append("Lab Management") currentSectionLinks["Lab Management"] = "../User.php" menuTypes["Lab Management"] = "Laboratories" tmp_order_list = {} tmp_order_list[0] = "Add" tmp_order_list[1] = "Search" submenu_order["Laboratories"] = tmp_order_list # Jan. 7/09: Chemicals currentSectionNames.append("Chemical Tracker") currentSectionLinks["Chemical Tracker"] = "../Chemical.php?View=1" menuTypes["Chemical Tracker"] = "Chemical" # Feb. 2, 2010 tmp_list = [] tmp_list.append("Chemicals") submenu_types["Chemical Tracker"] = tmp_list tmp_order_list = {} tmp_order_list[0] = "Add" tmp_order_list[1] = "Search" submenu_order["Chemicals"] = tmp_order_list tmp_list = {} tmp_list["Add"] = "../Chemical.php?View=2" tmp_list["Search"] = "../Chemical.php?View=1" submenu_links["Chemicals"] = tmp_list tmp_list = {} tmp_list["Add"] = "Add Chemicals" tmp_list["Search"] = "Search Chemicals" menuitems["Chemicals"] = tmp_list # Feb. 2/10 tmp_list = [] tmp_list.append("Users") submenu_types["User Management"] = tmp_list tmp_list = {} tmp_list["Add"] = "../User.php?View=1" tmp_list["Search"] = "../User.php?View=2" tmp_list["Change your password"] = "******" tmp_list["Personal page"] = "../User.php?View=7" tmp_list["View your orders"] = "../User.php?View=8" submenu_links["Users"] = tmp_list tmp_order_list = {} tmp_order_list[0] = "Add" tmp_order_list[1] = "Search" tmp_order_list[2] = "Change your password" tmp_order_list[3] = "Personal page" tmp_order_list[4] = "View your orders" submenu_order["Users"] = tmp_order_list tmp_list = {} tmp_list["Add"] = "Add users" tmp_list["Search"] = "Search users" tmp_list["Change your password"] = "******" tmp_list["Personal page"] = "Personal page" tmp_list["View your orders"] = "View your orders" menuitems["Users"] = tmp_list tmp_list = [] tmp_list.append("Laboratories") submenu_types["Lab Management"] = tmp_list tmp_list = {} tmp_list["Add"] = "../User.php?View=3" tmp_list["Search"] = "../User.php?View=4" submenu_links["Laboratories"] = tmp_list tmp_order_list = {} tmp_order_list[0] = "Add" tmp_order_list[1] = "Search" submenu_order["Laboratories"] = tmp_order_list tmp_list = {} tmp_list["Add"] = "Add laboratories" tmp_list["Search"] = "Search laboratories" menuitems["Laboratories"] = tmp_list currentSectionNames.append("Documentation") currentSectionLinks["Documentation"] = "../docs.php" publicSections["Documentation"] = "docs.php" currentSectionNames.append("Terms and Conditions") currentSectionLinks["Terms and Conditions"] = "../copyright.php" publicSections["Terms and Conditions"] = "copyright.php" currentSectionNames.append("Help and Support") currentSectionLinks["Help and Support"] = "../bugreport.php" publicSections["Help and Support"] = "bugreport.php" currentSectionNames.append("Contact Us") currentSectionLinks["Contact Us"] = "../contacts.php" publicSections["Contact Us"] = "contacts.php" # Aug. 20/10: Quick links tmp_ql = [] quickLinks = {} tmp_ql.append("Add reagents") tmp_ql.append("Search reagents") quickLinks["Reagent Tracker"] = tmp_ql tmp_ql = [] tmp_ql.append("Add containers") tmp_ql.append("Search containers") quickLinks["Location Tracker"] = tmp_ql tmp_ql = [] tmp_ql.append("Add projects") tmp_ql.append("Search projects") quickLinks["Project Management"] = tmp_ql tmp_ql = [] tmp_ql.append("Change your password") tmp_ql.append("View your orders") quickLinks["User Management"] = tmp_ql content = """ <div class="sidemenu" ID="mainMenu"> <div class="menu-content"> <ul class="menulist"> <!-- menu goes here --> """ # Output the menu link IFF the user is authorized to access that page currUser = Session.getUser() if currUser: ucMapper = UserCategoryMapper(db, cursor) category_Name_ID_Map = ucMapper.mapCategoryNameToID() currUserCategory = category_Name_ID_Map[currUser.getCategory()] # print "Content-type:text/html" # print allowedSections = uHandler.getAllowedSections(currUserCategory) # print `allowedSections` for name in currentSectionNames: if name in allowedSections: # added Jan. 7/09 if name in menuTypes: # print "Content-type:text/html" # print # print name content += '<DIV style="border-top:3px double #FFF8DC; border-right:6px double #FFF8DC; border-bottom:3px double #FFF8DC; border-left:6px double #FFF8DC; margin-top:2px; width:162px; padding-top:5px; padding-bottom:0;">' content += "<DIV style=\"background-image:url('../pictures/small_bg.png'); width:166px; height:30px;\">" content += '<select style="cursor:pointer; width:150px; background:#FFF8DC; font-weight:bold; color:#555; font-size:9pt; margin-top:3px; margin-left:2px; font-family:Helvetica; border:0;" onChange="openPage(this.options[this.options.selectedIndex]);">' content += ( '<option selected style="cursor:pointer; font-weight:bold; color:#555; font-size:9pt; border:0; font-family:Helvetica;" value=""> ' + name + "</option>" ) for st_val in submenu_types[name]: numDisallowed = 0 # Jan. 13, 2010: Don't print category heading if user has no access to any of its subitems for s_ord in submenu_order[st_val]: linkName = submenu_order[st_val][s_ord] linkURL = submenu_links[st_val][linkName] if not menuitems[st_val][linkName] in allowedSections: numDisallowed += 1 if numDisallowed == len(submenu_links[st_val]): continue # print st_val.upper() content += ( '<option style="cursor:pointer; font-weight:bold; color:#555; background:#EFEFEF; font-size:9pt; border:0; font-family:Helvetica;" onclick""> ' + st_val.upper() + "</option>" ) # Now: since Python dictionaries are not ordered, arrays with > 2 items (e.g. Users - has more than 'add' and 'search') would appear scrambled. Use an 'order' array instead for s_ord in submenu_order[st_val]: linkName = submenu_order[st_val][s_ord] linkURL = submenu_links[st_val][linkName] # print st_val # print linkName if menuitems[st_val][linkName] in allowedSections: content += ( '<option style="padding-left:15px; font-weight:bold; color:#555; font-size:8pt; border:0; font-family:Helvetica; cursor:pointer;" value="' + linkURL + '"> ' + linkName + "</option>" ) content += "</SELECT>" content += "</DIV>" # Quick links if quickLinks.has_key(name): content += ( '<div id="quick_links_' + name + '" style="font-family:Helvetica; width:166px; padding-bottom:0; margin-top:0; padding-top:0; padding-left:2px;">' ) content += '<UL style="padding-bottom:2px; padding-top:2px; padding-left:10px; position:relative;">' for qlName in quickLinks[name]: if qlName in allowedSections: content += ( '<LI style="list-style:none;"><img src="../pictures/silvermenubullet.png" width="7" height="6" style="padding-bottom:2px;"> <a style="font-weight:bold; font-size:8pt; font-family:Helvetica; text-decoration:none; color:#555; margin-left:2px;" href="../' + pageLinkMap[qlName] + '">' + qlName + "</a></LI>" ) content += "</UL>" content += "</DIV>" content += "</DIV>" else: if name == "Home": content += "<DIV style=\"background:url('../pictures/small_bg.png') repeat-y; padding-top:7px; margin-top:0; width:162px; border-top:6px double #FFF8DC; border-left:6px double #FFF8DC; border-right:6px double #FFF8DC; padding-bottom:8px;\">" else: content += "<DIV style=\"background:url('../pictures/small_bg.png') repeat-y; padding-top:7px; margin-top:2px; width:162px; border-left:6px double #FFF8DC; border-right:6px double #FFF8DC; padding-bottom:8px;\">" content += '<img src="../pictures/silvermenubullet.png" style="width:11px; height:9px; margin-left:5px;">' content += ( '<a style="font-weight:bold; color:#555; font-size:9pt; padding-left:3px; text-decoration:none;" href="' + currentSectionLinks[name] + '">' + name + "</a>" ) content += "</DIV>" else: # WRITE THIS FUNCTION!!!!!!!!!! # content += self.printGeneralMenu(publicSections) print "Content-type:text/html" print print "Unknown user" content += """ </UL> <!-- moved form down here on Aug. 20, 2010 --> <form name="curr_user_form" style="display:none" method="post" action="user_request_handler.py">" """ content += ( '<INPUT type="hidden" ID="curr_username_hidden" NAME="curr_username" VALUE="' + currUser.getFullName() + '">' ) content += ( '<INPUT TYPE="hidden" id="curr_user_hidden" name="view_user" VALUE="' + ` currUser.getUserID() ` + '">' ) content += """ </FORM> <div class="login"> """ content += self.printLoginBlock() content += """ </div> </div> </div> """ return content
def update(): dbConn = DatabaseConn() db = dbConn.databaseConnect() cursor = db.cursor() hostname = dbConn.getHostname() form = cgi.FieldStorage(keep_blank_values="True") print "Content-type:text/html" # REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! print # DITTO #print `form` # Aug 29/07 uHandler = UserHandler(db, cursor) if form.has_key("curr_username"): # store the user ID for use throughout the session; add to other views in addition to create in PHP currUname = form.getvalue("curr_username") currUser = uHandler.getUserByDescription(currUname) Session.setUser(currUser) #else: # debug #currUname = 'Administrator' #currUser = uHandler.getUserByDescription(currUname) #Session.setUser(currUser) if form.has_key("cloning_method"): cloning_method = form.getvalue("cloning_method") #else: # debug #cloning_method = '1' # Handlers and mappers rHandler = ReagentHandler(db, cursor) #sHandler = SystemSetHandler(db, cursor) pHandler = ReagentPropertyHandler(db, cursor) raHandler = ReagentAssociationHandler(db, cursor) aHandler = AssociationHandler(db, cursor) dnaHandler = DNAHandler(db, cursor) commHandler = CommentHandler(db, cursor) protHandler = ProteinHandler(db, cursor) propMapper = ReagentPropertyMapper(db, cursor) assocMapper = ReagentAssociationMapper(db, cursor) # August 29/07: Restrict creation by user and project access packetHandler = ProjectDatabaseHandler(db, cursor) ######################################################## # Various maps ######################################################## prop_Alias_ID_Map = propMapper.mapPropAliasID() # (propAlias, propID) - e.g. ('insert_type', '48') --> represents 'type of insert' property prop_Name_Alias_Map = propMapper.mapPropNameAlias() # (propName, propAlias) prop_Name_ID_Map = propMapper.mapPropNameID() # (prop name, prop id) # Restriction sites fpcs_prop_id = pHandler.findPropID("5' cloning site") tpcs_prop_id = pHandler.findPropID("3' cloning site") newFivePrime = form.getvalue("fpcs") newThreePrime = form.getvalue("tpcs") gatewaySites = ['attb', 'attl', 'attp', 'attr'] # nov. 16/07 # resulting sequence newSeq = "" # Fetch projects the user has AT LEAST Read access to (i.e. if he is explicitly declared a Writer on a project but not declared a Reader, include that project, plus all public projects) currReadProj = packetHandler.findMemberProjects(currUser.getUserID(), 'Reader') currWriteProj = packetHandler.findMemberProjects(currUser.getUserID(), 'Writer') publicProj = packetHandler.findAllProjects(isPrivate="FALSE") # list of Packet OBJECTS currUserWriteProjects = utils.unique(currReadProj + currWriteProj + publicProj) uPackets = [] for p in currUserWriteProjects: uPackets.append(p.getNumber()) # Get project IDs of parents packetPropID = pHandler.findPropID("packet id") # August 29/07: Need to verify parent project access AND (Sept. 12/07) reconstruct the sequence IFF parent values are changed newSeq = "" # Fetch projects the user has AT LEAST Read access to (i.e. if he is explicitly declared a Writer on a project but not declared a Reader, include that project, plus all public projects) currReadProj = packetHandler.findMemberProjects(currUser.getUserID(), 'Reader') currWriteProj = packetHandler.findMemberProjects(currUser.getUserID(), 'Writer') publicProj = packetHandler.findAllProjects(isPrivate="FALSE") # list of Packet OBJECTS currUserWriteProjects = utils.unique(currReadProj + currWriteProj + publicProj) uPackets = [] for p in currUserWriteProjects: uPackets.append(p.getNumber()) # Get project IDs of parents packetPropID = pHandler.findPropID("packet id") if form.has_key("PV"): pvVal = form.getvalue("PV") if len(pvVal) > 0: pvID = rHandler.convertReagentToDatabaseID(pvVal) try: pvProjectID = int(rHandler.findSimplePropertyValue(pvID, packetPropID)) pvSeqID = rHandler.findDNASequenceKey(pvID) # get sequence for reconstitution later except TypeError: #pvProjectID = 0 e = PVProjectAccessException("You are not authorized to use this Parent Vector, since you do not have Read access to its project.") print `e.err_code()` else: e = UnknownPVIDException("Unknown Parent Vector value") print `e.err_code()` return # else don't do anything, maybe want to delete parents!!! #else: #e = MissingPVException("No Parent Vector provided") #print `e.err_code()` if pvProjectID > 0 and currUser.getCategory() != 'Admin' and pvProjectID not in uPackets: e = PVProjectAccessException("Not authorized to access parent") print `e.err_code()` return if cloning_method == '1': # Non-recombination vector - Get the Insert if form.has_key("I"): insertVal = form.getvalue("I") if len(insertVal) > 0: insertID = rHandler.convertReagentToDatabaseID(insertVal) insertSeqID = rHandler.findDNASequenceKey(insertID) # fetch Insert sequence for reconstitution later try: insertProjectID = int(rHandler.findSimplePropertyValue(insertID, packetPropID)) except TypeError: #insertProjectID = 0 e = InsertProjectAccessException("You are not authorized to use this Insert, since you do not have Read access to its project.") print `e.err_code()` else: #insertID = -1 #insertProjectID = 0 #print "Invalid Insert value" e = UnknownInsertIDException("Unknown Insert value") print `e.err_code()` return #else: # NO!!!!!!!! #e = MissingInsertException("No Insert provided") #print `e.err_code()` if insertProjectID > 0 and currUser.getCategory() != 'Admin' and insertProjectID not in uPackets: e = InsertProjectAccessException("You are not authorized to use this Insert, since you do not have Read access to its project.") print `e.err_code()` return if pvID > 0 and insertID > 0 : # try to reconstruct sequence and issue warning if unable if pvSeqID > 0 and insertSeqID > 0: # fetch insert cloning sites insertCloningSites = [] fpcs_prop_id = pHandler.findPropID("5' cloning site") tpcs_prop_id = pHandler.findPropID("3' cloning site") fp_insert_cs = rHandler.findSimplePropertyValue(insertID, fpcs_prop_id) tp_insert_cs = rHandler.findSimplePropertyValue(insertID, tpcs_prop_id) # Determine if this is a Gateway clone from sites gwSites = False; if fp_insert_cs and tp_insert_cs and fp_insert_cs.lower() == 'attl' and tp_insert_cs.lower() == 'attl': gwSites = True elif not fp_insert_cs or not tp_insert_cs: gwSites = True # nov. 16/07: added this for check elif fp_insert_cs.lower() in gatewaySites or tp_insert_cs.lower() in gatewaySites: gwSites = True else: gwSites = False; if gwSites: # this is a gateway clone # if sites were changed to something other than gateway, clear sequence if newFivePrime.lower() != 'attl' or newThreePrime.lower() != 'attl': e = InsertSitesNotFoundOnParentSequenceException() print `e.err_code()` return else: pvSeqKey = rHandler.findDNASequenceKey(pvID) # For Gateway clones, linkers are found from primers - so find the sense and antisense Oligos for this Insert insertLinkers = [] # Find Sense and Antisense Oligos for this Insert # (not using antisense just yet - verify with Karen) iHandler = InsertHandler(db, cursor) senseOligoID = iHandler.findSenseOligoID(insertID) #antisenseOligoID = iHandler.findAntisenseOligoID(insert_db_id) # Find Oligo sequences seqPropID = pHandler.findPropID("sequence") senseOligoSeqID = rHandler.findIndexPropertyValue(senseOligoID, seqPropID) senseOligoSequence = dnaHandler.findSequenceByID(senseOligoSeqID) # Fetch Insert sequence and find linkers from Oligo and Insert sequences insertSequence = dnaHandler.findSequenceByID(insertSeqID) attB_const = "ggggacaactttgtacaaaaaagttggc" fwd_primer_seq = senseOligoSequence[len(attB_const):] # First, find linkers from Oligos fwd_linker = dnaHandler.linker_from_oligo(insertSequence, fwd_primer_seq) #rev_linker = sHandler.linker_from_oligo(insertSequence, rev_primer_seq) rev_linker = "" # Now see if the Insert had its own linkers stored and append them to the Oligo linker fpLinkerPropID = pHandler.findPropID("5' linker") tpLinkerPropID = pHandler.findPropID("3' linker") fp_insert_linker = rHandler.findSimplePropertyValue(insertID, fpLinkerPropID) tp_insert_linker = rHandler.findSimplePropertyValue(insertID, tpLinkerPropID) if fp_insert_linker and len(fp_insert_linker) > 0 and fp_insert_linker != 0 and fp_insert_linker != '0': fp_insert_linker = fwd_linker + fp_insert_linker else: fp_insert_linker = fwd_linker tp_insert_linker = rev_linker insertLinkers.append(fp_insert_linker) insertLinkers.append(tp_insert_linker) try: newSeq = dnaHandler.entryVectorSequence(pvSeqKey, insertSeqID, insertLinkers) print newSeq except MultipleSiteOccurrenceException: e = MultipleSiteOccurrenceException("Sites found more than once on parent vector sequence") print `e.err_code()` except FivePrimeAfterThreePrimeException: e = FivePrimeAfterThreePrimeException("5' after 3'") print `e.err_code()` except InsertSitesNotFoundOnParentSequenceException: e = InsertSitesNotFoundOnParentSequenceException("Gateway sites not found on parent vector sequence") print `e.err_code()` else: # Non-Gateway non-recombination Vector fp_insert_cs = newFivePrime tp_insert_cs = newThreePrime if fp_insert_cs: insertCloningSites.append(fp_insert_cs) else: insertCloningSites.append("") if tp_insert_cs: insertCloningSites.append(tp_insert_cs) else: insertCloningSites.append("") # get linkers if there are any insertLinkers = [] fpLinkerPropID = pHandler.findPropID("5' linker") tpLinkerPropID = pHandler.findPropID("3' linker") fp_insert_linker = rHandler.findSimplePropertyValue(insertID, fpLinkerPropID) tp_insert_linker = rHandler.findSimplePropertyValue(insertID, tpLinkerPropID) # sept. 3/07 fwd_linker = "" if fp_insert_linker and len(fp_insert_linker) > 0 and fp_insert_linker != 0 and fp_insert_linker != '0': fp_insert_linker = fwd_linker + fp_insert_linker else: fp_insert_linker = fwd_linker insertLinkers.append(fp_insert_linker) insertLinkers.append(tp_insert_linker) try: newSeq = dnaHandler.constructNonRecombSequence(pvSeqID, insertSeqID, insertCloningSites, insertLinkers) print newSeq except (InsertSitesException): e = InsertSitesException("Could not reconstitute sequence: Unknown sites on Insert.") print e.err_code() except (InsertSitesNotFoundOnParentSequenceException): e = InsertSitesNotFoundOnParentSequenceException("Could not reconstitute sequence: Parent vector sequence does not contain restriction sites.") print e.err_code() except (MultipleSiteOccurrenceException): e = MultipleSiteOccurrenceException("Could not reconstitute sequence: Restriction sites occur more than once on parent vector sequence") print e.err_code() except (HybridizationException): e = HybridizationException("Could not reconstitute sequence: Restriction sites cannot be hybridized.") print e.err_code() except (FivePrimeAfterThreePrimeException): e = FivePrimeAfterThreePrimeException("Could not reconstitute sequence: 5' site occurs after 3' site on parent vector sequence.") print e.err_code() else: e = InvalidSequenceException("Invalid parent sequence") print `e.err_code()` else: e = UnknownPVIDException("Unknown PV ID") print `e.err_code()` elif cloning_method == '2': # Recombination vector - check IPV ipvVal = form.getvalue("IPV") if len(ipvVal) > 0: ipvID = rHandler.convertReagentToDatabaseID(ipvVal) ipvProjectID = int(rHandler.findSimplePropertyValue(ipvID, packetPropID)) else: e = UnknownIPVIDException("Unknown IPV ID") print `e.err_code()` if ipvProjectID > 0 and currUser.getCategory() != 'Admin' and ipvProjectID not in uPackets: e = IPVProjectAccessException("Not authorized to view IPV") print `e.err_code()` if ipvID > 0 and pvID > 0: # If restriction sites were modified to anything other than LoxP or gateway att sites, clear the sequence if not (newFivePrime == newThreePrime and (newFivePrime.lower() == 'loxp' and newThreePrime.lower() == 'loxp') or (newFivePrime.lower() == 'attb' and newThreePrime.lower() == 'attb')): e = InsertSitesNotFoundOnParentSequenceException("Invalid restriction sites for Non-Recombination Clone - must be LoxP only") print `e.err_code()` else: # get internal db IDs pv_db_id = rHandler.convertReagentToDatabaseID(pvVal) ipv_db_id = rHandler.convertReagentToDatabaseID(ipvVal) # Get the Insert that belongs to the donor vector ipvInsertAssocID = raHandler.findReagentAssociationID(ipv_db_id) insertAssocPropID = aHandler.findAssocPropID("insert id") insert_db_id = aHandler.findAssocPropValue(ipvInsertAssocID, insertAssocPropID) # Construct a sequence for the new vector from the sequences of its parents pvSeqKey = rHandler.findDNASequenceKey(pv_db_id) #print "pv seq " + `pvSeqKey` ipvSeqKey = rHandler.findDNASequenceKey(ipv_db_id) #print "ipv seq " + `ipvSeqKey` insertSeqKey = rHandler.findDNASequenceKey(insert_db_id) #print "i seq " + `insertSeqKey` if pvSeqKey > 0 and ipvSeqKey > 0 and insertSeqKey > 0: # See if there are linkers, although there most likely aren't any insertLinkers = [] fpLinkerPropID = pHandler.findPropID("5' linker") tpLinkerPropID = pHandler.findPropID("3' linker") fp_insert_linker = rHandler.findSimplePropertyValue(insert_db_id, fpLinkerPropID) tp_insert_linker = rHandler.findSimplePropertyValue(insert_db_id, tpLinkerPropID) # sept. 3/07 fwd_linker = "" if fp_insert_linker and len(fp_insert_linker) > 0 and fp_insert_linker != 0 and fp_insert_linker != '0': fp_insert_linker = fwd_linker + fp_insert_linker else: fp_insert_linker = fwd_linker insertLinkers.append(fp_insert_linker) insertLinkers.append(tp_insert_linker) # Differentiate by cloning sites whether this is a recombination vector or a Gateway Expression Vector if newFivePrime == 'LoxP' and newThreePrime == 'LoxP': # recombination try: newSeq = dnaHandler.constructRecombSequence(pvSeqKey, ipvSeqKey, insertSeqKey, insertLinkers) newSeqID = dnaHandler.matchSequence(newSeq) print newSeq except InsertSitesNotFoundOnParentSequenceException: e = InsertSitesNotFoundOnParentSequenceException("LOXP sites not found on parent vector sequence") print `e.err_code()` except MultipleSiteOccurrenceException: e = MultipleSiteOccurrenceException("LOXP found more than once on parent vector sequence") print `e.err_code()` elif newFivePrime == 'attB' and newThreePrime == 'attB': # Gateway Expression iHandler = InsertHandler(db, cursor) senseOligoID = iHandler.findSenseOligoID(insert_db_id) #antisenseOligoID = iHandler.findAntisenseOligoID(insert_db_id) # Find Oligo sequences seqPropID = pHandler.findPropID("sequence") senseOligoSeqID = rHandler.findIndexPropertyValue(senseOligoID, seqPropID) senseOligoSequence = dnaHandler.findSequenceByID(senseOligoSeqID) # Fetch Insert sequence and find linkers from Oligo and Insert sequences insertSequence = dnaHandler.findSequenceByID(insertSeqKey) attB_const = "ggggacaactttgtacaaaaaagttggc" fwd_primer_seq = senseOligoSequence[len(attB_const):] # First, find linkers from Oligos fwd_linker = dnaHandler.linker_from_oligo(insertSequence, fwd_primer_seq) #rev_linker = sHandler.linker_from_oligo(insertSequence, rev_primer_seq) rev_linker = "" # Now see if the Insert had its own linkers stored and append them to the Oligo linker fpLinkerPropID = pHandler.findPropID("5' linker") tpLinkerPropID = pHandler.findPropID("3' linker") fp_insert_linker = rHandler.findSimplePropertyValue(insert_db_id, fpLinkerPropID) tp_insert_linker = rHandler.findSimplePropertyValue(insert_db_id, tpLinkerPropID) if fp_insert_linker and len(fp_insert_linker) > 0 and fp_insert_linker != 0 and fp_insert_linker != '0': fp_insert_linker = fwd_linker + fp_insert_linker else: fp_insert_linker = fwd_linker tp_insert_linker = rev_linker insertLinkers.append(fp_insert_linker) insertLinkers.append(tp_insert_linker) try: newSeq = dnaHandler.expressionVectorSequence(pvSeqKey, insertSeqKey, insertLinkers) print newSeq except MultipleSiteOccurrenceException: e = MultipleSiteOccurrenceException("Sites found more than once on parent vector sequence") print `e.err_code()` except FivePrimeAfterThreePrimeException: e = FivePrimeAfterThreePrimeException("5' after 3'") print `e.err_code()` except InsertSitesNotFoundOnParentSequenceException: e = InsertSitesNotFoundOnParentSequenceException("Gateway sites not found on parent vector sequence") print `e.err_code()` else: e = InvalidSequenceException("Invalid parent sequence") print `e.err_code()` else: e = ReagentDoesNotExistException("Unknown parent values") print `e.err_code()`
def __init__(self): self.template_renderer = Renderer('process.html') self.user_handler = UserHandler() self.user_obj = None
def saveUser(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname # print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! # print # DITTO # print `form` uHandler = UserHandler(db, cursor) lHandler = LabHandler(db, cursor) pHandler = ProjectDatabaseHandler(db, cursor) ucMapper = UserCategoryMapper(db, cursor) category_ID_Name_Map = ucMapper.mapCategoryIDToName() newProps = {} # Get form values userID = int(form.getvalue("userID")) newUser = uHandler.getUserByID(userID) labID = int(form.getvalue("labs")) tmpLab = lHandler.findLabByID(labID) # rest of user properties username = form.getvalue("username") firstName = form.getvalue("firstName") lastName = form.getvalue("lastName") description = firstName + " " + lastName email = form.getvalue("email") category = category_ID_Name_Map[int(form.getvalue("system_access_level"))] newProps["labID"] = labID newProps["username"] = username newProps["firstname"] = firstName newProps["lastname"] = lastName newProps["description"] = description newProps["email"] = email newProps["category"] = category try: # Now do an update on database level AND on class level: uHandler.updateUserProperties(userID, newProps) # database update # Interface level newUser.setUsername(username) newUser.setFirstName(firstName) newUser.setLastName(lastName) newUser.setDescription(description) newUser.setEmail(email) newUser.setLab(tmpLab) newUser.setCategory(category) # update list of user's projects if form.has_key("userProjectsReadonly"): # list of IDs readonlyProjects = utils.unique(form.getlist("userProjectsReadonly")) pHandler.updateUserProjects(userID, readonlyProjects, "Reader") else: # safe to assume should delete projects? pHandler.deleteMemberProjects(userID, "Reader") if form.has_key("userProjectsWrite"): writeProjects = utils.unique(form.getlist("userProjectsWrite")) pHandler.updateUserProjects(userID, writeProjects, "Writer") else: # safe to assume should delete projects? pHandler.deleteMemberProjects(userID, "Writer") # think about this # newUser.setReadProjects(readProjects) # newUser.setWriteProjects(writeProjects) # return to detailed view self.printUserInfo("view", newUser) # utils.redirect(hostname + "User.php?View=3&fd=" + filename) except DuplicateUsernameException: # return to the view with input values and error message # Need to construct a dummy User instance to save form values for error output on the next page (otherwise they're lost as soon as Submit is pressed and creation view is exited) newLab = lHandler.findLabByID(labID) newUser = User(userID, username, firstName, lastName, description, newLab, category, email, "") self.printUserInfo("edit", newUser, "Dup_un")
def addUser(self, form): db = self.__db cursor = self.__cursor hostname = self.__hostname mail_server = self.__mail_server # August 19, 2011 mail_programmer = self.__mail_programmer # July 30, 2010 mail_biologist = self.__mail_biologist mail_admin = self.__mail_admin # print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! # print # DITTO # print `form` uHandler = UserHandler(db, cursor) lHandler = LabHandler(db, cursor) pHandler = ProjectDatabaseHandler(db, cursor) ucMapper = UserCategoryMapper(db, cursor) category_Name_ID_Map = ucMapper.mapCategoryNameToID() # Get form values labID = int(form.getvalue("labs")) username = form.getvalue("username") firstName = form.getvalue("firstName") lastName = form.getvalue("lastName") description = firstName + " " + lastName to_email = form.getvalue("email") from_email = mail_admin # Change July 30, 2010 - random password generator # passwd = form.getvalue("password") chars = string.letters + string.digits passwd = "" for i in range(10): passwd += choice(chars) # System access level: Lab default or override? # if form.getvalue("privChoiceRadio") == 'override': accessLevel = category_Name_ID_Map[form.getvalue("system_access_level")] # else: # accessLevel = lHandler.findDefaultAccessLevel(labID) newProps = {} try: # Insert User information userID = uHandler.insertUser( username, firstName, lastName, description, accessLevel, to_email, passwd, labID ) # newUser = uHandler.getUserByID(userID) tmpLab = lHandler.findLabByID(labID) # print tmpLab.getName() # Insert Project info # Sept. 11/07: Differentiate between user categories Reader and Writer - different field names if form.has_key("userProjectsReadonly"): # list of IDs readonlyProjects = utils.unique(form.getlist("userProjectsReadonly")) # print `readonlyProjects` pHandler.insertMemberProjects(userID, readonlyProjects, "Reader") elif form.has_key("userProjectsReadonlyWrite"): # list of IDs readonlyProjects = utils.unique(form.getlist("userProjectsReadonlyWrite")) # print `readonlyProjects` pHandler.insertMemberProjects(userID, readonlyProjects, "Reader") # Write projects exist only for Writers if form.has_key("userProjectsWrite"): writeProjects = utils.unique(form.getlist("userProjectsWrite")) pHandler.insertMemberProjects(userID, writeProjects, "Writer") # don't assign projects to a User instance - will retrieve them from db in output function newUser = User( userID, username, firstName, lastName, description, tmpLab, form.getvalue("system_access_level"), to_email, passwd, [], [], ) email_subject = "OpenFreezer User Account" msg = email.MIMEMultipart.MIMEMultipart("alternative") msg["Subject"] = email_subject msg["To"] = to_email msgText = ( "Hi " + firstName + ",<BR><BR>An OpenFreezer account has been created for you. Your access level is " + form.getvalue("system_access_level") + ", so you can " ) if form.getvalue("system_access_level") == "Reader": msgText += "search for clones. If you wish to add/modify reagents or create projects, please contact the administrator to upgrade your access level.<BR>" elif form.getvalue("system_access_level") == "Writer": msgText += "search, add, and modify reagents. If you wish to create projects, please contact the administrator to upgrade your access level.<BR>" elif form.getvalue("system_access_level") == "Creator": msgText += "search for clones, add and modify reagents, as well as create your own projects.<BR>" ##################################################### # CHANGE TEXT AS NEEDED ##################################################### msgText += ( "<BR>The URL to access the system is <a href='" + hostname + "'>" + hostname + "</a>. Your username is <b>" + username + "</b>, and your temporary password is <b>" + passwd + "</b>. Please <u>change the temporary password as soon as you log into the website</u> - you can do it through the 'Change your password' link under the 'User Management' menu section.<BR><BR>Please refer to http://openfreezer.org for additional support.<BR><BR>Sincerely,<BR>OpenFreezer support team.<BR><BR><span style='font-family:Courier; font-size:10pt;'><HR>This is an automatically generated e-mail message. Please do not reply to this e-mail. All questions should be directed to your local administrator.</span>" ) msgText = email.MIMEText.MIMEText(msgText, "html") msg.attach(msgText) server = smtplib.SMTP(mail_server) server.set_debuglevel(1) server.sendmail(from_email, [to_email], msg.as_string()) server.quit() self.printUserInfo("view", newUser) except DeletedUserException: # Without asking too many questions, reactivate the deleted user and overwrite his/her attributes with the form input values userID = uHandler.findUserIDByUsername(username) newProps["firstname"] = firstName newProps["lastname"] = lastName newProps["description"] = description newProps["email"] = email newProps["status"] = "ACTIVE" newProps["password"] = passwd # Insert new database values and create new object uHandler.updateUserProperties(userID, newProps) # database update newUser = uHandler.getUserByID(userID) # Insert Project info readProjects = [] writeProjects = [] if form.has_key("userProjectsReadonly"): # list of IDs readonlyProjects = form.getlist("userProjectsReadonly") for r in readonlyProjects: pHandler.addProjectMember(r, userID, "Reader") # tmpReadProject = pHandler.findPacket(r) # readProjects.append(tmpReadProject) # newUser.addProject(tmpReadProject, 'read') if form.has_key("userProjectsWrite"): writeProjects = form.getlist("userProjectsWrite") for w in writeProjects: pHandler.addProjectMember(w, userID, "Writer") # tmpWriteProject = pHandler.findPacket(w) # writeProjects.append(tmpWriteProject) # newUser.addProject(tmpWriteProject, 'write') # newUser.setReadProjects(readProjects) # newUser.setWriteProjects(writeProjects) self.printUserInfo("view", newUser) # utils.redirect(hostname + "User.php?View=3&fd=" + filename) except DuplicateUsernameException: # return to the view with input values and error message # Need to construct a dummy User instance to save form values for error output on the next page (otherwise they're lost as soon as Submit is pressed and creation view is exited) newLab = lHandler.findLabByID(labID) newUser = User(0, username, firstName, lastName, description, newLab, "", email, passwd) self.printUserInfo("create", newUser)
def printSubmenuHeader(self, submenu_type): dbConn = DatabaseConn() hostname = dbConn.getHostname() # to define form action URL db = dbConn.databaseConnect() cursor = db.cursor() uHandler = UserHandler(db, cursor) current_selection_names = [] # plain list of section names current_selection_links = {} # dictionary, where section names are keys and their URLs are values if submenu_type == "Location": location_submenu_names = [] location_submenu_links = {} location_submenu_names.append("Add container types") location_submenu_links["Add container types"] = "../Location.php?View=6&Sub=3" location_submenu_names.append("Add container sizes") location_submenu_links["Add container sizes"] = "../Location.php?View=6&Sub=1" location_submenu_names.append("Add containers") location_submenu_links["Add containers"] = "../Location.php?View=6&Sub=3" location_submenu_names.append("Search containers") location_submenu_links["Search containers"] = "../Location.php?View=2" current_selection_names = location_submenu_names current_selection_links = location_submenu_links elif submenu_type == "Reagent": reagent_submenu_names = [] reagent_submenu_links = {} reagent_submenu_names.append("Add reagents") reagent_submenu_links["Add reagents"] = "../Reagent.php?View=2" reagent_submenu_names.append("Search reagents") reagent_submenu_links["Search reagents"] = "../search.php?View=1" # June 3/09 reagent_submenu_names.append("Add reagent types") reagent_submenu_links["Add reagent types"] = "../Reagent.php?View=3" reagent_submenu_names.append("Search reagent types") reagent_submenu_links["Search reagent types"] = "../Reagent.php?View=5" current_selection_names = reagent_submenu_names current_selection_links = reagent_submenu_links elif submenu_type == "Chemical": chemical_submenu_names = [] chemical_submenu_links = {} chemical_submenu_names.append("Add Chemicals") chemical_submenu_links["Add Chemicals"] = "../Chemical.php?View=2" chemical_submenu_names.append("Search Chemicals") chemical_submenu_links["Search Chemicals"] = "../Chemical.php?View=1" current_selection_names = chemical_submenu_names current_selection_links = chemical_submenu_links elif submenu_type == "Prediction": prediction_submenu_names = [] prediction_submenu_links = {} prediction_submenu_names.append("Search predictions") prediction_submenu_links["Search predictions"] = "../Prediction.php?View=1" current_selection_names = prediction_submenu_names current_selection_links = prediction_submenu_links elif submenu_type == "Project": project_submenu_names = [] project_submenu_links = {} project_submenu_names.append("Add projects") project_submenu_links["Add projects"] = "../Project.php?View=1" project_submenu_names.append("Search projects") project_submenu_links["Search projects"] = "../Project.php?View=2" current_selection_names = project_submenu_names current_selection_links = project_submenu_links elif submenu_type == "User": user_submenu_names = [] user_submenu_links = {} user_submenu_names.append("Add users") user_submenu_links["Add users"] = "../User.php?View=1" user_submenu_names.append("Search users") user_submenu_links["Search users"] = "../User.php?View=2" user_submenu_names.append("Change your password") user_submenu_links["Change your password"] = "******" user_submenu_names.append("Personal page") user_submenu_links["Personal page"] = "User.php?View=7" user_submenu_names.append("View your orders") user_submenu_links["View your orders"] = "../User.php?View=8" current_selection_names = user_submenu_names current_selection_links = user_submenu_links elif submenu_type == "Lab": lab_submenu_names = [] lab_submenu_links = {} lab_submenu_names.append("Add laboratories") lab_submenu_links["Add laboratories"] = "../User.php?View=3" lab_submenu_names.append("Search laboratories") lab_submenu_links["Search laboratories"] = "../User.php?View=4" current_selection_names = lab_submenu_names current_selection_links = lab_submenu_links # There can be permission differentiations within a menu section as well (e.g. Projects - only Creators can create, buit Writers can view) currUser = Session.getUser() ucMapper = UserCategoryMapper(db, cursor) category_Name_ID_Map = ucMapper.mapCategoryNameToID() currUserCategory = category_Name_ID_Map[currUser.getCategory()] allowedSections = uHandler.getAllowedSections(currUserCategory) # print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! # print # DITTO # print `allowedSections` content = "" for name in current_selection_names: if name in allowedSections: if name == "Personal page": content += '<LI class="submenu">' content += '<IMG SRC="../pictures/star_bullet.gif" WIDTH="10" HEIGHT="10" BORDER="0" ALT="plus" class="menu-leaf">' content += ( '<span class="linkShow" style="font-size:9pt" onClick="redirectToCurrentUserDetailedView(' + ` currUser.getUserID() ` + ');">' + name + "</span>" ) content += "</LI>" content += '<form name="curr_user_form" style="display:none" method="post" action="user_request_handler.py">' content += ( '<INPUT type="hidden" ID="curr_username_hidden" NAME="curr_username" VALUE="' + currUser.getFullName() + '">' ) content += '<INPUT type="hidden" id="curr_user_hidden" name="view_user">' content += "</FORM>" else: content += '<LI class="submenu">' content += '<IMG SRC="../pictures/star_bullet.gif" WIDTH="10" HEIGHT="10" BORDER="0" ALT="plus" class="menu-leaf">' content += '<a class="submenu" href="' + current_selection_links[name] + '">' + name + "</a>" content += "</LI>" return content
def handle(self): db = self.__db cursor = self.__cursor hostname = self.__hostname mail_server = self.__mail_server # August 19, 2011 mail_admin = self.__mail_admin # August 19, 2011 clone_request = self.__clone_request form = cgi.FieldStorage(keep_blank_values="True") uHandler = UserHandler(db, cursor) # print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! # print # DITTO # print `form` if form.has_key("curr_username"): # store the user ID for use throughout the session; add to other views in addition to create in PHP currUname = form.getvalue("curr_username") currUser = uHandler.getUserByDescription(currUname) Session.setUser(currUser) elif form.has_key("curr_user_id"): currUID = form.getvalue("curr_user_id") currUser = uHandler.getUserByID(currUID) Session.setUser(currUser) if form.has_key("add_user"): self.addUser(form) elif form.has_key("modify_user"): self.modifyUser(form) elif form.has_key("cancel_user"): self.cancelUserModification(form) elif form.has_key("save_user"): self.saveUser(form) elif form.has_key("delete_user"): self.deleteUser(form) elif ( form.has_key("view_user") and form.getvalue("view_user") != "" and not form.has_key("modify_lab") and not form.has_key("delete_lab") ): self.viewUser(form) # Nov. 17/07 - Personal user page elif ( form.has_key("view_user") and form.getvalue("view_user") == "" and not form.has_key("modify_lab") and not form.has_key("delete_lab") ): self.printUserInfo("view", currUser) elif form.has_key("add_lab"): self.addLab(form) elif form.has_key("view_lab"): self.viewLab(form) elif form.has_key("modify_lab"): self.modifyLab(form) elif form.has_key("save_lab"): self.saveLab(form) elif form.has_key("cancel_lab"): self.cancelLabModification(form) elif form.has_key("delete_lab"): self.deleteLab(form) elif form.has_key("bug_report"): self.submitBug(form) elif form.has_key("send_order"): ###################################################################### # CHANGE SERVER NAME AND EMAIL TO YOUR LOCAL CREDENTIALS ###################################################################### userID = form.getvalue("curr_user_id") userDescr = form.getvalue("curr_username") from_email = uHandler.findEmail(userID) if not from_email: from_email = userDescr to_email = clone_request email_subject = userDescr + ": Clone Request" f_in = form.getvalue("outputContent") infile = open(f_in, "rb") msg = email.MIMEMultipart.MIMEMultipart() # msg.attach(email.MIMEText.MIMEText(infile.read())) # no, this attaches plain text msg["Subject"] = email_subject part = email.MIMEBase.MIMEBase("application", "octet-stream") part.set_payload(infile.read()) email.Utils.base64.standard_b64encode(infile.read()) part.add_header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(f_in)) msg.attach(part) server = smtplib.SMTP(mail_server) server.set_debuglevel(1) # Send a request to your clone request address server.sendmail(from_email, to_email, msg.as_string()) # AND send a copy to the user (change the subject) # msg['Subject'] = "Clone request confirmation" # doesn't change, investigate later # Return email text changed March 31/08 ####################################### # CHANGE TEXT AS NEEDED ####################################### msg.attach( email.MIMEText.MIMEText( "This is a copy of your clone request. Please retain for your records. You will be notified by e-mail when your clone is ready." ) ) server.sendmail(to_email, from_email, msg.as_string()) server.quit() # Method 2 # sendmail = "/usr/sbin/sendmail" # o = os.popen("%s -t" % sendmail,"w") # o.write("To: %s\r\n" % to_email) # if from_email: # o.write("From: %s\r\n" % from_email) # o.write("Subject: %s\r\n" % email_subject) # o.write("\r\n") # o.write("%s\r\n" % msg) # o.close() os.remove(f_in) # delete the file from /tmp dir utils.redirect(hostname + "User.php?View=8&Sent=1") # June 1, 2010: Automated password reset elif form.has_key("reset_pw"): # change June 2, 2010: Don't enter email, rather, ask users to enter their username - more secure # to_email = form.getvalue("email") from_email = mail_admin # success = True chars = string.letters + string.digits new_passwd = "" for i in range(10): new_passwd += choice(chars) # reset it in the database if form.has_key("uName"): u_name = form.getvalue("uName") userID = uHandler.findUserIDByUsername(u_name) if userID > 0: u_descr = uHandler.findDescription(userID) to_email = uHandler.findEmail(userID) uHandler.setUserPropertyValue(userID, "password", new_passwd) email_subject = "OpenFreezer Password Change" msg = email.MIMEMultipart.MIMEMultipart() # msg.attach(email.MIMEText.MIMEText(infile.read())) # no, this attaches plain text msg["Subject"] = email_subject ################################### # CHANGE TEXT AS NEEDED ################################### msg.attach( email.MIMEText.MIMEText( "Dear " + u_descr + ",\n\nYour password for OpenFreezer has been changed.\n\nYour temporary new password is: " + new_passwd + ".\n\nPlease change the temporary password as soon as you log into the system.\n\nYour username for OpenFreezer is '" + u_name + "'.\n\nFor any questions, please refer to http://openfreezer.org. \n\nSincerely,\nOpenFreezer support team.\n--------------------------------\nThis is an automatically generated e-mail message. Please do not reply to this e-mail. All questions should be directed to your local administrator." ) ) server = smtplib.SMTP(mail_server) server.set_debuglevel(1) server.sendmail(from_email, to_email, msg.as_string()) server.quit() utils.redirect(hostname + "User.php?View=6&Reset=1&uid=" + ` userID `) else: # retry by description if form.has_key("uDesc"): u_descr = form.getvalue("uDesc") # but account for whitespace toks = u_descr.split(" ") tmp_descr = "" for tok in toks: tmp_descr += tok.strip() + " " # strip extra whitespace from end tmp_descr = tmp_descr.strip() userID = uHandler.findUserIDByDescription(tmp_descr) if userID > 0: u_name = uHandler.findUsername(userID) to_email = uHandler.findEmail(userID) uHandler.setUserPropertyValue(userID, "password", new_passwd) email_subject = "OpenFreezer Password Change" msg = email.MIMEMultipart.MIMEMultipart() # msg.attach(email.MIMEText.MIMEText(infile.read())) # no, this attaches plain text msg["Subject"] = email_subject ############################## # CHANGE TEXT AS NEEDED ############################## msg.attach( email.MIMEText.MIMEText( "Dear " + u_descr + ",\n\nYour password for OpenFreezer has been changed.\n\nYour temporary new password is: " + new_passwd + ".\n\nPlease change the temporary password as soon as you log into the system.\n\nYour username for OpenFreezer is '" + u_name + "'.\n\nPlease refer to http://openfreezer.org for additional support.\n\nSincerely,\nOpenFreezer support team.\n--------------------------------\nThis is an automatically generated e-mail message. Please do not reply to this e-mail. All questions should be directed to <a href='mailto:" + mail_admin + "'>" + mail_admin + "</a>" ) ) server = smtplib.SMTP(mail_server) server.set_debuglevel(1) server.sendmail(from_email, to_email, msg.as_string()) server.quit() utils.redirect(hostname + "User.php?View=6&Reset=1&uid=" + ` userID `) else: utils.redirect(hostname + "User.php?View=6&Reset=0") else: utils.redirect(hostname + "User.php?View=6&Reset=0") else: utils.redirect(hostname + "User.php?View=6&Reset=0") cursor.close() db.close()
def deleteMember(self, labID, memberID): db = self.db cursor = self.cursor uHandler = UserHandler(db, cursor) uHandler.deleteUser(memberID)