def addUser(self, user): if not isinstance(user, User): raise TypeError('%s is not a User object' % (user,)) user.setSerialNum(self.nextSerialNum()) user.externalId() # set unique id UserManager.addUser(self, user) user.save()
def addUser(self, user): if user.externalId() is None: user.setExternalId(uniqueId(user)) self._store.addObject(user) if self._saveNewUsers: self._store.saveChanges() UserManager.addUser(self, user)
def test4_login_username_false(self): """Checks if a user login is successful with wrong username""" umanager = UserManager() response = umanager.registerUser(self.username + "4", "Root@123", "admin") response = umanager.logIn(self.username + "789", "Root@123") self.assertEquals(response, "Unknown user")
def test5_login_password_false(self): """Checks if a user login is successful with wrong password""" umanager = UserManager() response = umanager.registerUser(self.username + "5", "Root@123", "admin") response = umanager.logIn(self.username + "5", "Root123") self.assertEquals(response, "Password incorrect")
def test_login(self): ''' This function will test if we can login as an existing user. ''' userbase = UserManager() username = "******" password = "******" salt = Authenticator.generate_salt() # Create a new user creator = UserCreation(userbase, username, password, salt) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() assert (userbase.is_existing_user(username) == True) # Login to that user salt = userbase.get_user_salt(username) auther = Authenticator(userbase, username, password, salt) auther.collect_user_credentials = MagicMock(return_value=True) token = auther.login() auther.collect_user_credentials.assert_called_once() assert (token is not None) assert (token != "") assert (userbase.get_user_from_token(token) == username)
def __init__(self, userClass=None, store=None, useSQL=None): """ @@ 2001-02-18 ce: docs """ # If no userClass was specified, try to pull 'User' # out of the object model. if userClass is None: userClass = store.model().klasses('User', None) UserManager.__init__(self, userClass) if store is None: from MiddleKit.ObjectStore.Store import Store store = Store assert store, 'MiddleKit store is None.' self._store = store # If the user didn't say whether or not to useSQL, then # we'll check if this looks like a SQLObjectStore. If so, # then using SQL server side queries will speed up our # operation: if useSQL is None: useSQL = getattr(self._store, 'executeSQL') is not None self._useSQL = useSQL # _saveNewUsers: if true, then we do a store.saveChanges() # whenever a new user is added. This helps with the # integrity of accessors like users(). # @@ 2001-02-18 ce: But perhaps that's a problem because # manager is not a MiddleKit object... self._saveNewUsers = 1
def __init__(self, userClass=None, store=None, useSQL=None): """ @@ 2001-02-18 ce: docs """ # If no userClass was specified, try to pull 'User' # out of the object model. if userClass is None: userClass = store.model().klass('User', None) UserManager.__init__(self, userClass) if store is None: from MiddleKit.ObjectStore.Store import Store store = Store assert store, 'MiddleKit store is None.' self._store = store # If the user didn't say whether or not to useSQL, then # we'll check if this looks like a SQLObjectStore. If so, # then using SQL server side queries will speed up our # operation: if useSQL is None: useSQL = getattr(self._store, 'executeSQL') is not None self._useSQL = useSQL # _saveNewUsers: if true, then we do a store.saveChanges() # whenever a new user is added. This helps with the # integrity of accessors like users(). # @@ 2001-02-18 ce: But perhaps that's a problem because # manager is not a MiddleKit object... self._saveNewUsers = 1
def openUserManagement(self): self.alertMessage( "User Manager.", "This feature is still in development, some features may not work as expected." ) self.user_manager = UserManager(self.user_id, self.password) self.user_manager.show()
def test_many_bad_logins(self): ''' This test will check if we can login to an existing user with an incorrect password. ''' userbase = UserManager() username = "******" password = "******" wrong_pass = "******" salt = Authenticator.generate_salt() # Create a new user creator = UserCreation(userbase, username, password, salt) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() assert (userbase.is_existing_user(username) == True) # Try to login many times to the same user. for xx in range(0, 10): salt = userbase.get_user_salt(username) auther = Authenticator(userbase, username, wrong_pass, salt) auther.collect_user_credentials = MagicMock(return_value=True) token = auther.login() auther.collect_user_credentials.assert_called_once() assert (token is not None) assert (token == "") assert (userbase.get_user_from_token(token) == "")
def test6_delete_user(self): """Checks if a user is deleted successfully""" umanager = UserManager() response = umanager.registerUser(self.username + "6", "Root@123", "admin") response = umanager.deleteUser(self.username + "6") self.assertEquals(response, "User deleted")
def test3_login_user(self): """Checks if a user login is successful""" umanager = UserManager() response = umanager.registerUser(self.username + "3", "Root@123", "admin") response = umanager.logIn(self.username + "3", "Root@123") self.assertEquals(response, "Log In Success")
def test2_register_user_exists(self): """Checks if a user is created when same username already exists""" umanager = UserManager() response = umanager.registerUser(self.username + "2", "Root@123", "admin") response = umanager.registerUser(self.username + "2", "Root@123", "user") self.assertEquals(response, "user already exists")
def test_logout_while_not_logged_in(self): ''' This function will test that we can "logout" while not in an active session and no failures will occur. ''' active_token = "" userbase = UserManager() assert (userbase.logout_user(active_token) == "")
def __init__(self): """Initialize the server manager object. The parameters are passed on to the init function of server manager """ self.user = User("") self.usermanager = UserManager() self.absolutePath = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe()))) self.fileManager = FileManager(self.absolutePath) super().__init__()
def __init__(self, sleep, bot_controller_factory, debug_mode): self.__stop = threading.Event() self.sleep = sleep self.debug_mode = debug_mode self.bot_logger = logging.getLogger('Bot_Sender') self.logger = logging.getLogger('Sending_Manager') self.user_manager = UserManager(bot_controller_factory, self.debug_mode) self.users = self.user_manager.users self.user_card_manager = {}
def __init__(self, bot_controller_factory, debug_mode): self.cycles = 0 #self.max_idle_time = max_idle_time self.debug_mode = debug_mode self.bot_controller_factory = bot_controller_factory self.logger = logging.getLogger('Message_Handler') self.bot_logger = logging.getLogger('Bot_Sender') self.bot = None self.user_manager = UserManager(self.bot_controller_factory, self.debug_mode) self.user_manager.reset_all_states() self.__stop = threading.Event()
def logout_current_user(active_token, userbase: UserManager) -> str: ''' This function will swiftly log the user out based on active_token usage. This removes the active token from the UserManager which is acting as our "server" in this case. ''' if not userbase.is_active_token(): print("There is no active session!") return "" return userbase.logout_user(active_token)
def login_existing_user(active_token, userbase: UserManager) -> str: ''' In this function, we log the user in based on collected username and password. On success we recieve an active token, on failure we recieve no token. Prompts to user will be printed from class on failure. ''' if userbase.is_active_token(): userbase.logout_user(active_token) auther = Authenticator(userbase) return auther.login()
def signIn(self): confirmUser = None userManager = UserManager(self.registeredUser, self.databaseFilename) username = input('Please enter the your username: '******'Please enter the your password: ') confirmUser = userManager.confirmUser(username, password) return confirmUser
def loadFutureTools(self, range_start, range_end_days = 42): functionName = 'loadFutureTools' # empty list returnedToolList = [] try: # calculationg range_end range_end = range_start + timedelta(days = range_end_days) userManager = UserManager(self.registeredUser, self.databaseFilename) # Connecting to the DB databaseConnection = DatabaseConnection.CreateDBConnection(self.databaseFilename) cursor = databaseConnection.cursor() cursor.execute("SELECT tool_id, duration FROM Bookings WHERE start_date BETWEEN ? AND ?", (range_start, range_end)) tool_rows = cursor.fetchall() for tool in tool_rows: # Read our values from the record tool_id = tool[0] cust_id = tool[1] tool_name = tool[2] tool_cat = tool[3] tool_desc = tool[4] price = tool[5] halfDayPrice = tool[6] # get ID user = userManager.LoadUserId(cust_id) # create tool singleTool = Tools(tool_id, user, tool_name, tool_cat, tool_desc, price, halfDayPrice) returnedToolList.append(singleTool) # Disconnecting from the DB DatabaseConnection.CloseDBConnection(databaseConnection) return returnedToolList except Error as e: print(__name__, ':', functionName, ':', e) raise
class SendingManager(): def __init__(self, sleep, bot_controller_factory, debug_mode): self.__stop = threading.Event() self.sleep = sleep self.debug_mode = debug_mode self.bot_logger = logging.getLogger('Bot_Sender') self.logger = logging.getLogger('Sending_Manager') self.user_manager = UserManager(bot_controller_factory, self.debug_mode) self.users = self.user_manager.users self.user_card_manager = {} def upd_users(self): self.user_manager.update_users() self.users = self.user_manager.users for user_id, user in self.users.items(): if user.get_active() == 0: continue if not (user_id in self.user_card_manager.keys()): self.user_card_manager[user_id] = UserSendingCardManager(user) def stop(self): self.__stop.set() def run(self): self.__stop.clear() cycles = 0 while not self.__stop.wait(self.sleep): try: if cycles % 2 == 0: self.logger.warning("Collect garbage") gc.collect() self.logger.warning("SM Woke Up - Cycles: {}".format(cycles)) cycles += 1 self.upd_users() for user_id, user_card_manager in self.user_card_manager.items( ): if self.users[user_id].get_active() == 0: continue user_card_manager.run() self.logger.info("Sleep {}".format(self.sleep)) except Exception as e: self.bot_logger.error("EXCEPTION on SM", exc_info=True) self.logger.error("EXCEPTION on SM", exc_info=True) self.logger.warning("SM turned off") self.bot_logger.warning("SM turned off")
def test_create_new_user(self): ''' This function will test if we can correctly create a new user. ''' userbase = UserManager() username = "******" password = "******" salt = Authenticator.generate_salt() creator = UserCreation(userbase, username, password, salt) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() assert (userbase.is_existing_user(username) == True)
def createBooking(self, tool, returnedUser): functionName = 'createBooking' try: # Connecting to the DB databaseConnection = DatabaseConnection.CreateDBConnection(self.databaseFilename) cursor = databaseConnection.cursor() # get IDs cust_id = UserManager.LoadUserId(self, returnedUser) tool_id = Tools.getId(tool) cursor.execute('INSERT INTO Bookings (tool_id, cust_id) VALUES (?, ?)', (tool_id, cust_id)) databaseConnection.commit() book_id = cursor.lastrowid returnedBooking = Bookings(book_id, tool, returnedUser) # Diconnecting from the DB DatabaseConnection.CloseDBConnection(databaseConnection) return returnedBooking except Error as e: print(__name__, ':', functionName, ':', e) raise
def main(): ''' This function is the driver function and runs the basic loop that controls program interaction. Functions are stored in a list for easy access via a UI input collector function. active_token is used to store the current active session token. Normal ''' active_token = "" option_functions = { "new_user": create_new_user, "login": login_existing_user, "logout": logout_current_user, "input_error": input_error, "exit": exit_application } # Having no access to database usage, we use a class that manages our # userbase. We will pass this to all of our methods. userbase = UserManager() while (True): show_ui_options(active_token, userbase) active_token = option_functions[gather_user_input()](active_token, userbase) #UI formatting to clear up space. print("\n\n\n\n\n\n")
def test_create_duplicate_new_users(self): ''' This test case will ensure that only 1 unique user exists per username. ''' userbase = UserManager() usernames = ["chad", "chad"] passwords = ["password", "hockey"] salts = [Authenticator.generate_salt()] * 2 for xx in range(0, len(usernames)): creator = UserCreation(userbase, usernames[xx], passwords[xx], salts[xx]) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() assert (userbase.get_total_users() == len(usernames) - 1)
def __init__(self, parent=None): QMainWindow.__init__(self, parent) Ui_MainWindow.setupUi(self, self) self.manager = UserManager() self.users = {} self.lineEdit_appid.setText('wxaafc0692eca7f8d6') self.lineEdit_secret.setText('077b4e1bed2b773c1014efa4512cd652') self.progressBar.setValue(0) self.pushButton_get_openids.setEnabled(False) self.pushButton_dump_all_user.setEnabled(False) self.pushButton_connect.clicked.connect(self.onConnect) self.pushButton_get_openids.clicked.connect(self.onGetOpenids) self.listWidget.currentItemChanged.connect(self.onOpenidFocus) self.manager.connected.connect(self.onConnected) self.manager.openidGot.connect(self.onOpenidGot) self.manager.info.connect(self.onInfo) self.manager.error.connect(self.onError) self.manager.onUser.connect(self.onUserInfo) self.manager.progress.connect(self.onProgressUpdate) self.pushButton_dump_all_user.clicked.connect(self.manager.dump_all_users) self.pushButton_statistics.clicked.connect(self.manager.do_statistic) self.pushButton_gender.clicked.connect(self.manager.show_stat_sex) self.pushButton_language.clicked.connect(self.manager.show_stat_language) self.pushButton_city.clicked.connect(self.manager.show_stat_city) self.pushButton_province.clicked.connect(self.manager.show_stat_province) self.pushButton_country.clicked.connect(self.manager.show_stat_country)
def searchToolByCategory(self, search_criteria): functionName = 'searchToolByCategory' # empty list returnedToolList = [] try: userManager = UserManager(self.registeredUser, self.databaseFilename) # Connecting to the DB databaseConnection = DatabaseConnection.CreateDBConnection(self.databaseFilename) cursor = databaseConnection.cursor() cursor.execute("SELECT tool_id, cust_id, tool_name, tool_cat, price, tool_desc, half_price FROM Tools WHERE tool_cat = ?", (search_criteria)) tool_rows = cursor.fetchall() for tool in tool_rows: tool_id = tool[0] cust_id = tool[1] tool_name = tool[2] tool_cat = tool[3] price = tool[4] tool_desc = tool[5] half_price = tool[6] # get user user = userManager.LoadUserId(cust_id) # create tool single_tool = Tools(tool_id, user, tool_name, tool_cat, price, tool_desc, half_price) returnedToolList.append(single_tool) # Disconnecting from the DB DatabaseConnection.CloseDBConnection(databaseConnection) return returnedToolList except Error as e: print(__name__, ':', functionName, ':', e) raise
def reloadUsers(self): # Remove everything from the list while self.usersView.count() > 0: self.usersView.takeItem(0) # For each user add their name to the view for user in UserManager(): self.usersView.addItem(user['name'])
def attempt(self): if UserManager().verifyPassword(self.userid, self.field.text()): global coursesWindow coursesWindow = CoursesWindow(self.loginWindow.application) self.close() self.loginWindow.close() coursesWindow.show() else: QMessageBox.warning(self, "Hasło", "Wprowadzone złe hasło")
def handle(self): if self.field.text() and self.fieldPass.text(): # Field are not empty call the user manager and reload the view UserManager().addUser(self.field.text(), self.fieldPass.text()) self.loginWindow.reloadUsers() self.close() else: # Prompt the user that the one of the fields is empty QMessageBox.warning(self, "Puste Pole", "Pola nie mogą być puste.")
def test_create_many_users(self): ''' This test case will ensure that multiple users can be created in one session. ''' userbase = UserManager() usernames = ["chad", "jay", "dylan", "ellen", "pat", "jon"] passwords = [ "password", "hockey", "cooking", "teaching", "painting", "swimming" ] salts = [Authenticator.generate_salt()] * 6 for xx in range(0, len(usernames)): creator = UserCreation(userbase, usernames[xx], passwords[xx], salts[xx]) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() assert (userbase.is_existing_user(usernames[xx]) == True) assert (userbase.get_total_users() == len(usernames))
def test_gather_user_credentials_called(self): ''' This function will test if we are correctly calling the gather_user_creation_details. ''' userbase = UserManager() creator = UserCreation(userbase) creator.gather_user_creation_details = MagicMock(return_value=False) creator.create() creator.gather_user_creation_details.assert_called_once()
class GithubMobile: """ The main class and interface """ def __init__(self): lock=e32.Ao_lock() self.directory=DIRECTORY if not os.path.exists(self.directory): os.makedirs(self.directory) os.chdir(self.directory) self.Users=UserManager(self.directory) self.start() self.RequestHost=NetworkManager self.RepositoryHost=RepositoryManager(self.RequestHost) self.mainlock=lock lock.wait() def start(self): items=[u'Create User'] items+=self.Users.listUsers() appuifw.app.body=appuifw.Listbox(items,self.choose) appuifw.app.menu=[ (u'Login',self.choose), (u'Delete',lambda:self.Users.deleteUser(items[appuifw.app.body.current()])), (u'Exit',self.quit)] appuifw.app.title=u'Github Mobile' appuifw.app.exit_key_handler=self.quit def quit(self): self.mainlock.signal() self.RequestHost.close() self.Users.forgetAll() self.RepositoryHost.closeAll() def choose(self): i=appuifw.app.body.current() if i==0: n=appuifw.multi_query(u'Displayname',u'Username') if n is None:return p=appuifw.query(u'Password','code') if p is None:return self.Users.addUser(n[0],n[1],p) self.start() return user=self.Users.listUsers()[i-1] uname=self.Users.getUser(user)[0] self.RequestHost.headers['Authorization']=self.Users.HTTPBasicUser(user) resp=self.RequestHost.GET('/user/repos') try:json=resp.parseJson() except resp.ClientError,e: appuifw.note(unicode(e.json['message']),'error') return util.mkdir([uname]) os.chdir(uname) self.RepositoryHost.loadRepos(json) self.displayRepos()
def __init__(self): lock=e32.Ao_lock() self.directory=DIRECTORY if not os.path.exists(self.directory): os.makedirs(self.directory) os.chdir(self.directory) self.Users=UserManager(self.directory) self.start() self.RequestHost=NetworkManager self.RepositoryHost=RepositoryManager(self.RequestHost) self.mainlock=lock lock.wait()
def main(): user_id = sys.argv[1] ip_addr, port = user_id.split(":") if len(ip_addr) == 0: ip_addr = '0.0.0.0' port = int(port) #Port = 10000 + index ip_addr = (ip_addr, port) localaddr = ip_addr user_id = str(ip_addr).ljust(20) user_id = user_id.replace(',', ':') remote_ip, remote_port = sys.argv[2].split(":") remote_port = int(remote_port) remote_ip_addr = (remote_ip, remote_port) remote_uid = str(remote_ip_addr).ljust(20) remote_uid = remote_uid.replace(',', ':') b = BroadCast() um = UserManager(b, localaddr, user_id) #Daemon threading for keeping adding the users ua = user_add(um) ua.setDaemon(True) ua.start() #auto UserManager update user list #Try to connect the other members #Testing version 1 ''' for i in range(20): if i == index: continue #don't need to connect itself remote_uid = str(i).ljust(20) port = 10000 + i addr = (ip_addr, port) sock = um.add_user(addr, remote_uid) #if sock != None: #add_new_user_abcast_list(remote_uid) ''' #offset = int(sys.argv[2]) #remote_ip_addr = ("localhost", 10000 + offset) #remote_uid = str(offset).ljust(20) sock = um.add_user(remote_ip_addr, remote_uid) ''' user_list = um.temp_user_list um.update_user_list(user_list.keys(), um.view_id + 1) user_list, view_id = um.get_user_list() ''' #Init CASTSelecter t_cast_s = CASTSelecter(b) t_cast_s.setDaemon(True) t_cast_s.start() #Init ABCAST #fake ab_m = ABCASTManager(user_id, t_cast_s, um, LogManager()) ab_m.start() #ABCAST Reader t_ab_reader = read_from_abcast(ab_m) t_ab_reader.setDaemon(True) t_ab_reader.start() #Init GBCAST gb_m = GBCASTManager(user_id,t_cast_s, um, ab_m) t_gbcast = Thread_GBCAST(gb_m) t_gbcast.setDaemon(True) t_gbcast.start() print '=====================================================' #message count = 0 while True: message = raw_input() if (message == "sync"): gb_m.send_user_dict_request() elif message == "clock": gb_m.test_clock(str(count)) count += 1 elif message == "userlist": #print gb_m.user_m.temp_user_list.keys() print gb_m.user_m.get_user_list() elif message == "prepare": gb_m.send_prepare() elif message == "prepare-ok": gb_m.send_prepare_ok() elif message == "abcast": print 'abcast' for i in xrange(10): ab_m.write(str(i)) elif message == "command": while True: message = raw_input() if (message == "exit"): break try: exec(message) except: print 'error' else: ab_m.write(message)
def __init__(self): self.article_manager = ArticleManager() self.community_manager = CommunityManager() self.user_manager = UserManager()
class Framework: def __init__(self): self.article_manager = ArticleManager() self.community_manager = CommunityManager() self.user_manager = UserManager() # def get_article_by_id(self, aid): # return self.article_manager.get_article_by_id(aid) # Article methods def get_articles(self): return self.user_manager.get_articles() def get_article_url(self, aid): return self.user_manager.get_article_url(aid) def get_article_title(self, aid): return self.article_manager.get_article_title(aid) def get_article_score(self, aid): return self.article_manager.get_article_score(aid) def post_article(self, title, url, uid, cid): aid = self.article_manager.post_article(title, url, uid, cid) self.community_manager.post_article(uid, aid) self.user_manager.add_user_article(uid, aid) def upvote(self, aid): self.article_manager.upvote(aid) def downvote(self, aid): self.article_manager.downvote(aid) def get_top_articles(self): aids = self.get_articles() top_aids = rank_articles(aids)[:20] return get_articles(top_aids) def get_random_article(self): return self.article_manager.get_random_article() # User methods def add_user(self, username): return self.user_manager.add_user(username) def get_users(self): return self.user_manager.get_all_users() def get_user_communities(self, uid): return self.user_manager.get_user_communities(self, uid) def get_user_articles(self, uid): aids = self.user_manager.get_user_articles(uid) return self.get_articles(aids) def add_user_community(self, uid, cid): self.user_manager.add_user_community(uid, cid) self.community_manager.add_user_community(uid, cid) def remove_user_community(self, uid, cid): self.user_manager.remove_user_community(uid, cid) self.community_manager.remove_user_community(uid, cid) # Community methods def get_communities(self): return self.community_manager.get_communityIds() def add_community(self, name): self.community_manager.add_new_community(name) def get_community_users(self, cid): return self.community_manager.get_community_users(cid) def get_community_articles(self, cid): aids = self.community_manager.get_community_articles(cid) return self.get_articles(aids) # Helper methods def rank_articles(aids): return sorted(aids, key=self.get_article_score) def get_articles(self, aids): articles = [] for aid in aids: article = (self.get_article_title(aid), self.get_article_url(aid), self.get_article_score(aid)) articles.append(article) return articles
def main(): user_id = sys.argv[1] index = int(user_id) #Port = 10000 + index ip_addr = "localhost" port = 10000 + index localaddr = (ip_addr, port) user_id = user_id.ljust(20) b = BroadCast() um = UserManager(b, localaddr, user_id) #Daemon threading for keeping adding the users #auto UserManager update user list #Try to connect the other members #Testing version 1 for i in range(20): if i == index: continue #don't need to connect itself remote_uid = str(i).ljust(20) port = 10000 + i addr = (ip_addr, port) sock = um.add_user(addr, remote_uid) #if sock != None: #add_new_user_abcast_list(remote_uid) user_list = um.temp_user_list um.update_user_list(user_list.keys(), um.view_id + 1) user_list, view_id = um.get_user_list() #Init CASTSelecter t_cast_s = CASTSelecter(b) t_cast_s.setDaemon(True) t_cast_s.start() #Init ABCAST #fake ab_m = ABCASTManager(user_id, t_cast_s, um, LogManager()) ab_m.start() ab_m.addUser("123") ua = user_add(um, ab_m) ua.setDaemon(True) ua.start() print 'user_list', um.fetch_user_list() #ab_m = None #Init GBCAST gb_m = GBCASTManager(user_id,t_cast_s, um, ab_m) t_gbcast = Thread_GBCAST(gb_m) t_gbcast.setDaemon(True) t_gbcast.start() print '=====================================================' #ABCAST READER t_ab_reader = read_from_abcast(ab_m) t_ab_reader.setDaemon(True) t_ab_reader.start() #message while True: message = raw_input() if message is "": continue if (message == "userlist"): print "userManager", um.fetch_user_list() print "abcast", ab_m.clientList continue if (message == "sync"): gb_m.send_user_dict_request() continue for i in range(100): ab_m.write(message + str(i))
def main(): global threshold threshold = 0 user_id = sys.argv[1] index = int(user_id) #Port = 10000 + index ip_addr = "localhost" port = 10000 + index localaddr = (ip_addr, port) user_id = user_id.ljust(20) b = BroadCast() um = UserManager(b, localaddr, user_id) #Try to connect the other members for i in range(20): if i == index: continue #don't need to connect itself remote_uid = str(i).ljust(20) port = 10000 + i addr = (ip_addr, port) sock = um.add_user(addr, remote_uid) # if sock != None: # add_new_user_abcast_list(remote_uid) user_list = um.temp_user_list um.update_user_list(user_list.keys(), um.view_id + 1) user_list, view_id = um.get_user_list() #Init CASTSelecter t_cast_s = CASTSelecter(b) t_cast_s.setDaemon(True) t_cast_s.start() #Init GBRecver t_gb_recv = Thread_recvGB(t_cast_s) t_gb_recv.setDaemon(True) t_gb_recv.start() print '=====================================================' #Init ABCASTManager am = ABCASTManager(user_id, t_cast_s, um, LogManager()) am.start() #Code from Tao #Daemon threading for keeping adding the users am.addUser("321") #call for update print 'user_list', um.fetch_user_list() ua = user_add(um, am) ua.setDaemon(True) ua.start() #auto UserManager update user list #Init recvCB() #t_cb_recv = Thread_recvCB(t_cast_s) #t_cb_recv.setDaemon(True) #t_cb_recv.start() t_ab_reader = read_from_abcast(am) t_ab_reader.setDaemon(True) t_ab_reader.start() ''' for k in range(1000): am.write(str(k)) time.sleep(20) ''' send = 0 while True: if threshold > 20: continue am.write(str(send)) send += 1 threshold += 1 #message ''' while True: message = raw_input() if (message == "userlist"): print "userManager", um.fetch_user_list() print "abcast", am.clientList if (message == ""): continue #t_cast_s.sendCB(message) am.write(message) ''' #Init abcast while True: message = raw_input() if (message == "sync"): print [x.uniqueId() for x in am.processQueue.objects] try: exec(message) except: print 'error'
def home(request): dicToResponse = {} if not check_root(): dicToResponse['no_root'] = True dicToResponse.update(update_state('dhcp', False)) dicToResponse.update(update_state('sip', False)) dicToResponse.update(update_state('ntp', False)) return render_to_response('home.html', dicToResponse, context_instance=RequestContext(request)) dhcp = DHCPServer() sip = ServerManager() ntp = NTPServer() usersdb = UserManager() dicToResponse.update(update_state('dhcp', dhcp.is_start)) dicToResponse.update(update_state('sip', sip.is_start)) dicToResponse.update(update_state('ntp', ntp.is_start)) dicToResponse.update(update_users(usersdb)[0]) if request.method == 'POST': if 'start_sip' in request.POST: runserver = run_server(sip) if runserver[1] == 0: dicToResponse.update(update_state('sip', True)) else: dicToResponse.update(update_state('sip', False)) dicToResponse["server_error"] = runserver[0] elif 'stop_sip' in request.POST: stopserver = stop_server(sip) if stopserver[1] == 0: dicToResponse.update(update_state('sip', False)) else: dicToResponse.update(update_state('sip', True)) dicToResponse["server_error"] = stopserver[0] if 'start_dhcp' in request.POST: runserver = run_server(dhcp) if runserver[1] == 0: dicToResponse.update(update_state('dhcp', True)) else: dicToResponse.update(update_state('dhcp', False)) dicToResponse["server_error"] = runserver[0] elif 'stop_dhcp' in request.POST: stopserver = stop_server(dhcp) if stopserver[1] == 0: dicToResponse.update(update_state('dhcp', False)) dicToResponse["server_error"] = stopserver[0] else: dicToResponse.update(update_state('dhcp', True)) dicToResponse["server_error"] = stopserver[0] if 'start_ntp' in request.POST: runserver = run_server(ntp) if runserver[1] == 0: dicToResponse.update(update_state('ntp', True)) else: dicToResponse.update(update_state('ntp', False)) dicToResponse["server_error"] = runserver[0] elif 'stop_ntp' in request.POST: stopserver = stop_server(ntp) if stopserver[1] == 0: dicToResponse.update(update_state('ntp', False)) else: dicToResponse.update(update_state('ntp', True)) dicToResponse["server_error"] = stopserver[0] if 'add_user' in request.POST: if usersdb.connect and usersdb.table_ok: name = request.POST.get('user_name') passw = request.POST.get('user_pass') data_base_msg = usersdb.add_user(name, passw) if data_base_msg[0] == 0: dicToResponse.update(update_users(usersdb)[0]) else: dicToResponse["add_user_fault"] = data_base_msg[1] else: dicToResponse["add_user_fault"] = 'Database connection refused, read log file' if 'del_user' in request.POST: if usersdb.connect and usersdb.table_ok: name = request.POST.get('actual_user') dicToResponse.update(update_users(usersdb)[0]) return render_to_response('home.html', dicToResponse, context_instance=RequestContext(request))
def usershow(req): return UserManager.usershow(req)
def enter(req): return UserManager.enter(req)
def modify(req): return UserManager.modify(req);
def logout(req): return UserManager.logout(req)
def login(req): return UserManager.login(req)
def regist(req): return UserManager.regist(req)
def oj(req): return UserManager.index(req)
def main(): import hashlib #user_id = sys.argv[1] a_ip_addr = sys.argv[1] a_port = int(sys.argv[2]) #user_id = hashlib.md5(str(localaddr)).hexdigest()[:20] #b_user_id = sys.argv[4] b_ip_addr = sys.argv[3] b_port = int(sys.argv[4]) #Port = 10000 + index ip_addr = a_ip_addr port = a_port localaddr = (ip_addr, port) user_id = hashlib.md5(str(localaddr)).hexdigest()[:20] print user_id print localaddr user_id = user_id.ljust(20) b = BroadCast() um = UserManager(b, localaddr, user_id) #Daemon threading for keeping adding the users ua = user_add(um) ua.setDaemon(True) ua.start() #auto UserManager update user list #Try to connect the other members #Testing version 1 ''' for i in range(20): if i == index: continue #don't need to connect itself remote_uid = str(i).ljust(20) port = 10000 + i addr = (ip_addr, port) sock = um.add_user(addr, remote_uid) #if sock != None: #add_new_user_abcast_list(remote_uid) ''' if sys.argv[3] == 'n': um.new_group = True else: remote_ip_addr = (b_ip_addr, b_port) remote_uid = hashlib.md5(str(remote_ip_addr)).hexdigest()[:20] #remote_uid = b_user_id.ljust(20) print remote_ip_addr print remote_uid sock = um.add_user(remote_ip_addr, remote_uid) ''' user_list = um.temp_user_list um.update_user_list(user_list.keys(), um.view_id + 1) user_list, view_id = um.get_user_list() ''' #Init CASTSelecter t_cast_s = CASTSelecter(b) t_cast_s.setDaemon(True) t_cast_s.start() #Init ABCAST #fake ab_m = ABCASTManager(user_id, t_cast_s, um, LogManager()) #ab_m.start() #ABCAST Reader t_ab_reader = read_from_abcast(ab_m) t_ab_reader.setDaemon(True) #t_ab_reader.start() #Init GBCAST gb_m = GBCASTManager(user_id,t_cast_s, um, ab_m) t_gbcast = Thread_GBCAST(gb_m) t_gbcast.setDaemon(True) t_gbcast.start() print '=====================================================' #message count = 0 gb_m.send_user_dict_request() ''' while True: message = raw_input() if (message == "sync"): gb_m.send_user_dict_request() break; elif message == "clock": gb_m.test_clock(str(count)) count += 1 elif message == "userlist": #print gb_m.user_m.temp_user_list.keys() print gb_m.user_m.get_user_list() elif message == "prepare": gb_m.send_prepare() elif message == "prepare-ok": gb_m.send_prepare_ok() elif message == "abcast": print 'abcast' for i in xrange(10): ab_m.write(str(i)) elif message == "command": while True: message = raw_input() if (message == "exit"): break try: exec(message) except: print 'error' else: ab_m.write(message) ''' while True: if ab_m.startFlag: break time.sleep(0.1) #print 'started' #testing code #while True: # message = raw_input() # ab_m.write(message) # init editor name = user_id filename = '' coops = {} stdscr = curses.initscr() init_colors() stdscr.bkgd(1, curses.COLOR_BLACK) gui = EditorGUI(stdscr, name, filename) coop = cooperator(gui, 1) coops[name] = coop gui._cooperators.append(coop) gui.set_pipe(ab_m) execute_msg_t = execute_msg(ab_m, coops, gui) execute_msg_t.setDaemon(True) execute_msg_t.start() gui.main()
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) Ui_MainWindow.setupUi(self, self) self.manager = UserManager() self.users = {} self.lineEdit_appid.setText('wxaafc0692eca7f8d6') self.lineEdit_secret.setText('077b4e1bed2b773c1014efa4512cd652') self.progressBar.setValue(0) self.pushButton_get_openids.setEnabled(False) self.pushButton_dump_all_user.setEnabled(False) self.pushButton_connect.clicked.connect(self.onConnect) self.pushButton_get_openids.clicked.connect(self.onGetOpenids) self.listWidget.currentItemChanged.connect(self.onOpenidFocus) self.manager.connected.connect(self.onConnected) self.manager.openidGot.connect(self.onOpenidGot) self.manager.info.connect(self.onInfo) self.manager.error.connect(self.onError) self.manager.onUser.connect(self.onUserInfo) self.manager.progress.connect(self.onProgressUpdate) self.pushButton_dump_all_user.clicked.connect(self.manager.dump_all_users) self.pushButton_statistics.clicked.connect(self.manager.do_statistic) self.pushButton_gender.clicked.connect(self.manager.show_stat_sex) self.pushButton_language.clicked.connect(self.manager.show_stat_language) self.pushButton_city.clicked.connect(self.manager.show_stat_city) self.pushButton_province.clicked.connect(self.manager.show_stat_province) self.pushButton_country.clicked.connect(self.manager.show_stat_country) def onInfo(self, msg): self.statusBar().showMessage(msg) def onError(self, errmsg): self.statusBar().showMessage(errmsg) def onConnect(self): self.statusBar().showMessage('Connecting WeChat Server'); appid = self.lineEdit_appid.text() secret = self.lineEdit_secret.text() self.manager.connect(appid, secret) def onConnected(self, msg): self.pushButton_get_openids.setEnabled(True) self.statusBar().showMessage(msg) def onGetOpenids(self): self.statusBar().showMessage('Getting openids'); self.manager.get_openids() def onOpenidGot(self, msg): self.statusBar().showMessage(msg) self.listWidget.addItems(self.manager.openids) self.progressBar.setValue(0) self.lcdNumber_totalUsers.display(len(self.manager.openids)) self.pushButton_dump_all_user.setEnabled(True) def onOpenidFocus(self, target): openid = target.text().__str__() self.manager.get_user(openid) def onUserInfo(self, user): self.tableWidget.setItem( 0, 0, QTableWidgetItem(str(user.subscribe)) ) self.tableWidget.setItem( 1, 0, QTableWidgetItem(user.openid) ) self.tableWidget.setItem( 2, 0, QTableWidgetItem(user.nickname) ) self.tableWidget.setItem( 3, 0, QTableWidgetItem(str(user.sex)) ) self.tableWidget.setItem( 4, 0, QTableWidgetItem(user.language) ) self.tableWidget.setItem( 5, 0, QTableWidgetItem(user.city) ) self.tableWidget.setItem( 6, 0, QTableWidgetItem(user.province) ) self.tableWidget.setItem( 7, 0, QTableWidgetItem(user.country) ) self.tableWidget.setItem( 8, 0, QTableWidgetItem(user.headimgurl) ) self.tableWidget.setItem( 9, 0, QTableWidgetItem(str(user.subscribe_time))) self.tableWidget.setItem(10, 0, QTableWidgetItem(user.remark) ) self.tableWidget.setItem(11, 0, QTableWidgetItem(str(user.groupid)) ) self.statusBar().showMessage(user.openid) def onProgressUpdate(self, loaded, total): self.lcdNumber_totalUsers.display(total) self.lcdNumber_loadedUsers.display(loaded) percentage = 100 * loaded / total self.progressBar.setValue(percentage)
def main(): user_id = sys.argv[1] index = int(user_id) #Port = 10000 + index ip_addr = "localhost" port = 10000 + index localaddr = (ip_addr, port) user_id = user_id.ljust(10) b = BroadCast() um = UserManager(b, localaddr, user_id) #Try to connect the other members for i in range(20): if i == index: continue #don't need to connect itself remote_uid = str(i).ljust(10) port = 10000 + i addr = (ip_addr, port) sock = um.add_user(addr, remote_uid) # if sock != None: # add_new_user_abcast_list(remote_uid) user_list = um.temp_user_list um.update_user_list(user_list.keys(), um.view_id + 1) user_list, view_id = um.get_user_list() #Init CASTSelecter t_cast_s = CASTSelecter(b) t_cast_s.setDaemon(True) t_cast_s.start() #Init GBRecver t_gb_recv = Thread_recvGB(t_cast_s) t_gb_recv.setDaemon(True) t_gb_recv.start() print '=====================================================' #Init ABCASTManager am = ABCASTManager(user_id, t_cast_s, um) #am.start() #Code from Tao #Daemon threading for keeping adding the users #am.addUser("321") #call for update print 'user_list', um.fetch_user_list() ua = user_add(um, am) ua.setDaemon(True) ua.start() #auto UserManager update user list #Init recvCB() t_cb_recv = Thread_recvCB(t_cast_s) t_cb_recv.setDaemon(True) t_cb_recv.start() ''' t_ab_reader = read_from_abcast(am) t_ab_reader.setDaemon(True) t_ab_reader.start() ''' #message while True: message = raw_input() if (message == ""): continue t_cast_s.sendCB(message)
def addUser(self, user): self._store.addObject(user) if self._saveNewUsers: self._store.saveChanges() UserManager.addUser(self, user)
def main(): user_id = sys.argv[1] ip_addr = "localhost" index = int(user_id) #Port = 10000 + index ip_addr = "localhost" port = 10000 + index localaddr = ('0.0.0.0', port) user_id = user_id.ljust(10) b = BroadCast() um = UserManager(b, localaddr, user_id) #Try to connect the other members for i in range(20): if i == index: continue #don't need to connect itself remote_uid = str(i).ljust(10) port = 10000 + i addr = (ip_addr, port) sock = um.add_user(addr, remote_uid) # if sock != None: # add_new_user_abcast_list(remote_uid) user_list = um.temp_user_list um.update_user_list(user_list.keys(), um.view_id + 1) user_list, view_id = um.get_user_list() #Init CASTSelecter t_cast_s = CASTSelecter(b) t_cast_s.setDaemon(True) t_cast_s.start() print '=====================================================' #Init ABCASTManager am = ABCASTManager(user_id, t_cast_s, um) # init editor name = user_id filename = '' coops = {} stdscr = curses.initscr() init_colors() stdscr.bkgd(1, curses.COLOR_BLACK) gui = EditorGUI(stdscr, name, filename) coop = cooperator(gui, 1) coops[name] = coop gui._cooperators.append(coop) gui.set_pipe(am) execute_msg_t = execute_msg(am, coops, gui) execute_msg_t.start() am.start() #Code from Tao #Daemon threading for keeping adding the users am.addUser("321") #call for update print 'user_list', um.fetch_user_list() ua = user_add(um, am) ua.setDaemon(True) ua.start() #auto UserManager update user list #message ''' while True: message = raw_input() if (message == ""): continue #t_cast_s.sendCB(message) am.write(message) ''' #Init recvCB() #t_cb_recv = Thread_recvCB(t_cast_s) #t_cb_recv.setDaemon(True) #t_cb_recv.start() #t_ab_reader = read_from_abcast(am) #t_ab_reader.setDaemon(True) #t_ab_reader.start() gui.main()
def setUserClass(self, userClass): """ Overridden to verify that our userClass is really a MiddleObject. """ from MiddleKit.Run.MiddleObject import MiddleObject assert issubclass(userClass, MiddleObject) UserManager.setUserClass(self, userClass)
def __init__(self, userClass=None): UserManager.__init__(self, userClass) RoleUserManagerMixIn.__init__(self)