def post(self, *args): doctor = Doctor() user = User() order = Order() self.set_header("Content-Type", "application/json") if args[0] == 'addorderpeople': self.write(user.update_order_people_info( self.current_user, self.get_argument('name'), self.get_argument('id_card'), self.get_argument('telephone'), self.get_argument('hospital_card') )) elif args[0] == 'getordersize': self.write(doctor.get_ordersize_by_date(self.get_argument("date"), self.get_argument("doctor_id"))) elif args[0] == 'createorder': order_info = { 'user_id': self.current_user, 'doctor_id': self.get_argument('doctor_id'), 'community': self.get_argument('community'), 'doctor': self.get_argument('doctor'), 'hospital_card': self.get_argument('hospital_card'), 'id_card': self.get_argument('id_card'), 'name': self.get_argument('name'), 'telephone': self.get_argument('telephone'), 'time': self.get_argument('time') } self.write(order.create_order(order_info))
def get(self): #statusCodes: #200 ok #201 invalid email #202 other error statusCode = 202 getTrainer = self.request.get('getTrainer') emailAddress = self.request.get('emailAddress') user = User.query(User.emailAddress == emailAddress).get() if user: statusCode = 201 if getTrainer != '': trainers = [] for trainerTuple in Trains.query(Trains.traineeEmail == user.emailAddress): trainer = User.query(User.emailAddress==trainerTuple.trainerEmail).get() if trainer: trainers.append(trainer.getViewableInfo()) statusCode = 200 self.response.write(json.dumps({'statusCode': statusCode, 'trainers': trainers})) else: trainees = [] for traineeTuple in Trains.query(Trains.trainerEmail == user.emailAddress): trainee = User.query(User.emailAddress==traineeTuple.traineeEmail).get() if trainee: trainees.append(trainee.getViewableInfo()) statusCode = 200 self.response.write(json.dumps({'statusCode': statusCode, 'trainees': trainees})) self.response.write(json.dumps({'statusCode': statusCode}))
def fetchActiveUsers(bot): # Check for new members params = {"token": USER_TOKEN_STRING, "channel": bot.channel_id} response = requests.get("https://slack.com/api/channels.info", params=params) user_ids = json.loads(response.text, encoding="utf-8")["channel"]["members"] active_users = [] for user_id in user_ids: user = User(user_id) # Excludes bots and deleted users if user.isActive(): active_users.append(user) # Add user to the cache if not already if user_id not in bot.user_cache: bot.user_cache[user_id] = user if not bot.first_run: # Push our new users near the front of the queue! bot.user_queue.insert(2, bot.user_cache[user_id]) print "New user to the cache: " + user.real_name if bot.first_run: bot.first_run = False return active_users
def adminSessionsPost(handler, p_key, p_action, p_value = None): handler.title('Sessions') requirePriv(handler, 'Admin') print "<script src=\"/static/admin-sessions.js\" type=\"text/javascript\"></script>" if not p_key in Session.getIDs(): ErrorBox.die("Retrieve session", "No session exists with key <b>%s</b>" % stripTags(p_key)) session = Session.load(p_key) for case in switch(p_action): if case('reassign'): handler.title('Reassign Session') if p_value: user = User.load(int(p_value)) if not user: ErrorBox.die("Load user", "No user exists with ID <b>%s</b>" % stripTags(p_value)) session['user'] = user redirect('/admin/sessions') else: print "<form method=\"post\" action=\"/admin/sessions\">" print "<input type=\"hidden\" name=\"action\" value=\"reassign\">" print "<input type=\"hidden\" name=\"key\" value=\"%s\">" % p_key print "<select id=\"selectUser\" name=\"value\">" for user in sorted(User.loadAll()): print "<option value=\"%d\">%s</option>" % (user.id, user.safe.username) print "</select><br>" print Button('Reassign', type = 'submit').positive() print Button('Cancel', id = 'cancel-button', type = 'button', url = '/admin/sessions').negative() print "</form>" break if case('destroy'): Session.destroy(p_key) redirect('/admin/sessions') break break
def operate(self): self.show_item_info() while True: op = raw_input("Question Answer Item$ ") if op == "voteup": self.vote_up_answer() elif op == "votedown": self.vote_down_answer() elif op == "votecancle": self.vote_cancle_answer() elif op == "answer": from Answer import Answer answer = Answer(zhihu + self.get_answer_link()) if answer.operate(): return True elif op == "author": author_link = self.get_author_link() if author_link: user = User(zhihu + self.get_author_link()) if user.operate(): return True else: print termcolor.colored("回答者为匿名用户", "red") elif op == "pwd": self.show_item_info() elif op == "help": self.help() elif op == "break": break elif op == "clear": clear() elif op == "quit": return True else: error()
def purgeGroup(self): users = System.groupMember(Config.group) if users is None: return False ret = True for user in users: if user == Config.dav_user: continue Logger.debug("FileServer:: deleting user '%s'"%(user)) u = User(user) u.clean() if u.existSomeWhere(): Logger.error("FS: unable to del user %s"%(user)) ret = False htgroup = HTGroup(Config.dav_group_file) htgroup.purge() try: groups = [g.gr_name for g in grp.getgrall() if g.gr_name.startswith("ovd_share_")] for g in groups: System.groupDelete(g) except Exception: Logger.exception("Failed to purge groups") ret = False return ret
def api_token_request(): username = request.form.get('email') password = request.form.get('password') token = request.form.get('token') if len([x for x in [username,password,token] if x == None]) > 1: return Response(response=jfail("missing required parameters"), status=200) user = User(username) if user.is_valid(): if password: if user.check_pass_hash(password): return Response(response=jsuccess_with_token(user.get_token()), status=200) else: return Response(response=jfail("incorrect password"), status=200) else: checked = user.check_token(token) if checked == 1: return Response(response=jsuccess(), status=200) elif checked == 0: return Response(response=jfail("expired token"), status=200) else: return Response(response=jfail("invalid token"), status=200) else: return Response(response=jfail("user does not exist"), status=200)
def incoming_letter_email(): body = EmailReplyParser.parse_reply(unicode(request.form.get('text')).encode('ascii','xmlcharrefreplace')) body = '\n'.join(body.split('\n')).replace("\n","<br />") regexp = re.findall(r'[\w\.-]+@[\w\.-]+',request.form.get('from')) try: attachments = int(request.form.get('attachments')) except Exception: attachments = 0 if len(regexp) > 0 and len(regexp[-1]) > 0: username = regexp[-1].lower() else: return_bad_params(username) return Response(response=jfail("missing parameters"), status=200) to_name = request.form.get('to') to_address = unicode(request.form.get('subject')).encode('ascii','xmlcharrefreplace').lower().replace("fw:","").replace("re:","").strip() if None in [body,username,to_name,to_address]: return_bad_params(username) return Response(response=jfail("missing parameters"), status=200) user = User(username) if user.is_valid(): send_letter(user,to_name,to_address,body,attachments) else: return_unknown_sender(username) return Response(response=jfail("unknown sender"), status=200) return Response(response=jsuccess(), status=200)
def getRangeId(self, uid): user = User(uid) tid = self.key_ now = int(time.time()) (entry_time, range_id) = user.getRangeInfo(tid) cfg = CfgTable(CfgTable.CFG_TOURNAMENT, tid) total_time = int(cfg.time) if self.start_time <= entry_time < self.start_time + total_time: return range_id else: # update lv = user.level range_id = 0 for i, r in enumerate(self.LV_RANGE): if lv <= r: range_id = i + 1 break user.setRangeInfo(tid, now, range_id) return range_id
def createUser(self, request, addr, name, port): data = request.recv(1048576) files = pickle.loads(data) user = User(name,addr,int(port),files) User.printUsers([user]) with user_lock: users.append(user)
def create(self, master_address=None, master_seed=None): user = User(master_address, master_seed) logging.debug("Created user: %s" % user.master_address) if user.master_address: # If successfully created self.users[user.master_address] = user user.save() return user
def test_create_user(self): repo = UserRepository() u1 = User(USERNAME) u1.birthdate = datetime.strptime("1990-11-11 00:00:00", '%Y-%m-%d %H:%M:%S') u2 = repo.create_user(u1) #repo.commit(USERNAME) self.assertEqual(u2.username, USERNAME)
def insert_user(): name = request.form.get('name') surname = request.form.get('surname') email = request.form.get('email') password = request.form.get('password') bday = request.form.get('bday') try: role = request.form.get('role') city = request.form.get('city') rate = float(request.form.get('rate')) active = 0 description = "Inserisci qui la tua descrizione" avatar = int(request.form.get('avatar')) user = User(name, surname, email, password, bday, role, city, rate, active, description, avatar) except TypeError: user = User(name, surname, email, password) user_manager.insert(user) user = user_manager.get_user_by_email(email) r_token = RefreshToken(1, user.get("id_user")) a_token = RefreshToken(2, user.get("id_user")) token_manager.insert_refresh_token(r_token) token_manager.insert_access_token(a_token) return "OK"
def signup(): if request.method == 'GET': return render_template("signup.html", entries=[]) elif request.method == 'POST': username = request.form['username'] pass1 = request.form['password'] pass2 = request.form['verify'] failed = False if not valid_email(username): failed = True flash(u"Neustrezno uporabniško ime.") if not valid_password(pass1): failed = True flash(u"Neustrezno geslo.") if pass1 != pass2: failed = True flash(u"Geslo se ne ujema.") if not failed: user = User.get_by_user(username) if user is not None: failed = True flash(u"Uporabnik že obstaja.") if failed: return render_template("signup.html", username=username, password=pass1, verify=pass2) user = User(username=username, password=pass1) user.put() login_user(user) session['user'] = None log_info("Audit: New user %s created." % user.username) flash(u"Kreiran in prijavljen nov uporabnik.") return redirect(request.args.get("next") or url_for("tennis_events_old"))
def get_page(self, params): """Handle parameters for changing the password. param params: A dictionary that is expected to contain user_id and password entries. TypeError will be thrown when params is None. ValueError will be thrown if user_id or password are None/empty. """ def validate(): if params is None: raise TypeError def throw_if_empty(x): if params.get(x, "") =="": raise ValueError(x) ps = ["user_id", "password"] list(map(throw_if_empty, ps)) validate() interactor = self.interactor_factory.create("ChangePasswordInteractor") interactor.interactor_factory = self.interactor_factory interactor.set_hash_provider(BCryptHashProvider()) u = User() u.user_id = params["user_id"] u.password = params["password"] interactor.execute(u)
def post(self): statusCode = 200 recurrenceRate = self.request.get('recurrenceRate') senderEmail = self.request.get('senderEmail') receiverEmail = self.request.get('receiverEmail') sender = User.query(User.emailAddress == senderEmail).get() if sender: receiver = User.query(User.emailAddress == receiverEmail).get() if receiver: ''' A lot of this is a repeat of above. One thing that is different is I look for both receiverId and receiverAddress. This is because I am not sure what the user will send to the API. Basically, I look for receiverId first, if it does exist I move on, if not, then I look for the receiverAddress, use that to get the user, and then set the Id. It just adds a little bit of flexibility for the user. below is an example of using the request body to populate contents. In this we use json.loads. It is the reverse of json.dumps, it takes a string and returns a json object (really just a map with stuff in it). Now that I am looking at it, I am not sure if I need to loads and then dumps. I think it is because self.request.body is not written in actual characters so we need to load and then dump into an actual string object but I haven't tested enough to know either way. But I know this works. ''' contents = json.dumps(json.loads(self.request.body)) ''' This is how you create a new entity row. Use the constructor and pass whatever variables you want to it. There are some variables that are auto filled (like creationDate) these should not be given a value. There are attributes that have a default value, these can be given values but is not required, if a value is not given it uses the default value. Everything else needs a value or it is null. The constructor returns a key to the newly created object but it has not been added to the table yet. You need to call .put() to add it. This is also how you update rows. Call notification.query().get() to get the row, make any changes, and then call .put() to update the table. ''' notification = Notification(contents=contents, recurrenceRate=recurrenceRate, senderEmail=senderEmail, receiverEmail=receiverEmail) notification.put() self.response.write(json.dumps({'statusCode': statusCode}))
def main(): print("starting") user = User(-36.854134, 174.767841) stop = Stop(-36.843574, 174.766931) print(user.calculate_walking_time(stop))
def startcoinservers(coincontroller, exenames , envars, startupstatcheckfreqscnds, appdata): userfile = appdata + '\\' + 'stakenanny' + '\\' + 'user.sav' if path.exists(userfile): user = deserialize(userfile ) else: user = User() user.set_pwd(getpasswd()) serialize(user, userfile) #starteachserver(coincontroller, exenames, envars, user.get_pwd(), appdata, startupstatcheckfreqscnds, rpcports) gevent.joinall([ gevent.spawn(starteachserver(coincontroller, exenames, envars, user.get_pwd(), appdata, startupstatcheckfreqscnds)), gevent.spawn(enablestake(coincontroller, user.get_pwd())), ]) #continuekey=input('press a key to continue:') #-server -daemon #-rpcuser=stakenanny #rpcallowip=127.0.0.1 #listen=1 #-server #-daemon=1 #conn = bitcoinrpc.connect_to_local(filename='C:\\Users\\Noe\\AppData\\Roaming\\TurboStake\\turbostake.conf', rpcuser='******', rpcpassword=password) #conn = bitcoinrpc.connect_to_local(filename='C:\\Users\\Noe\\AppData\\Roaming\\TurboStake\\turbostake.conf') #best_block_hash = rpc_connection.getbestblockhash() #print(rpc_connection.getblock(best_block_hash)) #best_block_hash = rpc_connection.getinfo() #Checking the wallet status every halfsecond would be reasonable #the connectino error happens at the print line #info = conn.getinfo() #print(info) #blkage = timelapse.BlockAge(1446916630) #print(str(blkage.age())) #trans = conn.listtransactions #print("Blocks: %i" % info.blocks) #print("Connections: %i" % info.connections) #for tran in trans(): print("transactoins %s" % tran)
def __handle(self): while self.connected(): letter = self.__client.require() if letter is None: break if letter.name == "PRIVMSG": mess = letter.args text = Brain.clear_string(mess) snd_nick = letter.nick if snd_nick == self.__nick: continue public = letter.channel is not None for nick, user in self.__users.items(): if isinstance(user.action, UpdAction): user.action.update(snd_nick, public, mess) tags = set(Brain.get_tags(text).keys()) if len(tags) == 0: continue dst_nicks = Brain.get_dst(text, self.__client.names()) bot_nick = self.__nick.lower() for foo in self.__commands: if foo[0] & tags: foo[1](tags, bot_nick, snd_nick, dst_nicks, public, mess) elif letter.name == "JOIN": user = User(letter.nick) if letter.nick in self.__masters: user.master = True self.__users[letter.nick] = user elif letter.name == "NICK": user = self.__users[letter.nick] del self.__users[letter.nick] user.name = letter.args self.__users[letter.args] = user
def create_user(cls, key_id, id_map): uid = Redis().incr(cls.ID_CTR) Redis().hset(id_map, key_id, uid) User.create(uid) return uid
def test_user_tv(self): john = User("John") command = "tv_mood" john.tv_switch(command) self.assertEquals(john.name, "John") self.assertEquals(john.tv_switch(command), TV.tv_display(TV))
def operate(self): if not self.parse(): return True print self.get_title() while True: op = raw_input("zhuanlan$ ") if op == "content": self.get_content() elif op == "author": url = self.get_author_info() if not url: print termcolor.colored("当前用户为匿名用户", "red") else: from User import User user = User(url) if user.operate(): return True elif op == "voteup": self.vote(type=1) elif op == "votecancle": self.vote(type=2) elif op == "pwd": print self.get_title() elif op == "browser": self.open_in_browser() elif op == "clear": clear() elif op == "break": break elif op == "help": self.help() elif op == "quit": return True else: error()
def get_users_intouch(self, message): connection = MySQLConn() query = """select tu.* ,tud.bday, tud.role, tud.city,tud.rate, tud.active, tud.description, tud.avatar from (select * from tbl_user_dettail where role is not null) as tud join (select * from tbl_user where email != '%s' order by rand() limit 7) as tu on tu.id_user = tud.id_user""" % () connection.open() connection.get_session().execute(query) users_data = connection.get_session().fetchall() desc = connection.get_session().description connection.get_connection().commit() print("#DB# -execute-\n") print("#DB# %s \n" % (query)) users = [] for user_data in users_data: user = User() for data, col in zip(range(0, len(desc)), desc): print("> > > %s = %s" % (col[0], user_data[data])) if isinstance(user_data[data], datetime.date): user.set(col[0], str(user_data[data])) else: user.set(col[0], user_data[data]) users.append(user.__dict__) connection.close() return users
def post(self): username = self.request.get('username') password = self.request.get('password') verify = self.request.get('verify') email = self.request.get('email') uError = pError = vError = eError = '' if not validUser(username): uError = 'That is not a valid user name.' else: q = db.GqlQuery('select * from User where name = :1', username) user = q.get() if user: uError = 'That user name already exists' if not validPassword(password): pError = 'That is not a valid password.' if password != verify: vError = 'The passwords do not match.' if email and not validEmail(email): eError = 'That is not a valid email address.' if uError or pError or vError or eError: self.render_signup(username, uError, pError, vError, email, eError) else: pwHasher = PasswordHash() pwHash = pwHasher.make_pw_hash(username, password) user = User(name = username, pwHash = pwHash, email = email) user.put() cookieHasher = CookieHash() cookieHash = cookieHasher.make_secure_val(str(user.key().id())) self.response.set_cookie('user_id', cookieHash) url = self.request.url url = url[:url.rfind('/signup')] url = url[url.rfind('/') + 1:] self.redirect('/%s/' % url)
def test3_UserName1(self): print("testUserName1") sock = setupServer(2010) start_new_thread(connectClient, (2010,)) conn, addr = sock.accept() user1 = User(name="User", connection=conn, address=addr, id=0) tearDownServer(sock) self.assertEqual(user1.__str__(), "name : User")
def create_indexes(): User.ensure_indexes() Charity.ensure_indexes() DropoffLocation.ensure_indexes() Donation.ensure_indexes() Pledge.ensure_indexes() Collection.ensure_indexes() Transaction.ensure_indexes()
def routines(userId): try: thisUser = User(userId=userId) if thisUser == None : return jsonify(error="User not found") return thisUser.getRoutines() except : raise
def create(self, master_address=None, master_seed=None): self.list() # Load the users if it's not loaded yet user = User(master_address, master_seed) self.log.debug("Created user: %s" % user.master_address) if user.master_address: # If successfully created self.users[user.master_address] = user user.saveDelayed() return user
def documents(): if session.get('userid') == None: return redirect(url_for('index')) user = User(None,userid=session["userid"]) if user.is_valid(): return render_template('documents.html',user=user) else: return redirect(url_for('logout'))
def test_add_coached_by(self): one = User(0) two = User(0) one.add_coached_by(two) self.assertIn(two, one.coached_by) self.assertIn(one, two.coaches)
class MessageModel(colander.MappingSchema): src_user = User() room = Room() msg = colander.SchemaNode(colander.String())
def update_userList(self, us, name, organization, email, password, skill_level, type): us = User(name, organization, email, password, skill_level, type) us.set_name(name) us.set_organization(organization) us.set_email(email) us.set_password(password) us.set_skill(skill_level)
def mainMenu(): choice = -1 current_user = -1 while choice != '4': print('\n') print('1.Sign Up') print('2.Sign In') print('3.Admin Sign In') print('4.Quit') choice = raw_input('Enter your choice: ') if choice == '1': first_name = raw_input('First Name: ') last_name = raw_input('Last Name: ') password = raw_input('Password: '******'Address: ') city = raw_input('City: ') state = raw_input('State: ') pincode = raw_input('Pincode: ') new_user = User(first_name, last_name, password, address, city, state, pincode) if new_user.save(): print('Thanks for signing up!') else: print('Cannot create an account for you') elif choice == '2': attempts = 1 while attempts <= 3: print("Attempt %d: " % (attempts)) id = raw_input('User Id: ') password = raw_input('Password: '******'Invalid credentials!') attempts += 1 else: print('Max sign in attempts reached') elif choice == '3': attempts = 1 while attempts <= 3: print("Attempt %d: " % (attempts)) username = raw_input('Username: '******'Password: '******'Invalid credentials!') attempts += 1 else: print('Max sign in attempts reached') elif choice == '4': pass else: print('Invalid option!')
def load_user(user_id): return User.get(user_id)
def main(): global mailBox global verified global seen global knownUsers global outUser global seenMail while True: toClean = raw_input("command: ") command = toClean.strip() if (command[:4] == "exit"): print("exiting program, bye...") break elif (command[:5] == "-user"): myUser = knownUsers[getpass.getpass("Username: "******"-alias"): values = command.split(" ") outUser = values[values.index("-alias") + 1] elif (command[:5] == "--new"): #for optimal security we would calculate a random mod and base that #match values = command.split(" ") userName = values[values.index("-user") + 1] random = string_to_int(os.urandom(9999)[:4]) newUser = User(userName, 23, 5, random, -1) if ("-gen" in command): #create new key for the user curve = SECP_256k1() privateKey = string_to_int(os.urandom(curve.coord_size)) privateKey2 = int_to_string(privateKey) newUser.setShared(string_to_int(privateKey2[:4])) else: key = getpass.getpass("Input your private key: ") newUser.setShared(key) knownUsers[newUser.getName()] = newUser elif (command[:3] == "-eU"): rest = command[3:].strip() tempUser = User(None, -1, -1, -1, -1) #-name -mod -base -pub -shared things = rest.split(" ") while (len(things) > 0): temp = things.pop(0) if (temp == "-name"): tempUser.setName(things.pop(0)) elif (temp == "-mod"): tempUser.setMod(things.pop(0)) elif (temp == "-base"): tempUser.setBase(things.pop(0)) elif (temp == "-pub"): tempUser.setPub(things.pop(0)) elif (temp == "-shared"): tempUser.setShared(things.pop(0)) if (tempUser.getName() in knownUsers): targetUser = knownUsers[tempUser.getName()] if (tempUser.getMod() > 0): targetUser.setMod(tempUser.getMod()) if (tempUser.getBase() > 0): targetUser.setBase(tempUser.getBase()) if (tempUser.getPub() > 0): targetUser.setPub(tempUser.getPub()) if (tempUser.getShared() > 0): targetUser.setShared(tempUser.getShared()) else: knownUsers[tempUser.getName()] = tempUser elif (command[:6] == "-agree"): values = command.split(" ") user = knownUsers[values[values.index("-u") + 1]] user.setShared( keyAgreement(user.getMod(), myUser.getShared(), user.getPub())) elif (command[:5] == "-load"): values = command.split(" ") fileLoc = values[values.index("-f") + 1] newList = pickle.load(open(fileLoc, "r")) knownUsers.update(newList) elif (command[:5] == "-save"): values = command.split(" ") fileLoc = values[values.index("-f") + 1] pickle.dump(knownUsers, open(fileLoc, "w")) elif (command[:4] == "-pub"): values = command.split(" ") if ("-u" in values): user = knownUsers[values[values.index("-u") + 1]] print( createPublic(user.getMod(), user.getBase(), myUser.getShared())) else: mod = values[values.index("-mod") + 1] base = values[values.index("-base") + 1] print(createPublic(mod, base, myUser.getShared())) elif (command[:8] == "-connect"): values = command.split(" ") user = "" ip = "" if ("-new" in values): ip = values[values.index("-ip") + 1] username = values[values.index("-u") + 1] user = knownUsers[username] fakeRuth = 23 encRuth = encrypt(fakeRuth, user.getShared()) authPair = authenticate(11) request = authPair[0] seen[ip] = [username, authPair[1]] encReq = encrypt(request, user.getShared()) #INCLUDE AUTHENTICATION ORIGINAL MESSAGE sending = "||user||" + outUser + "||auth||" sending += encReq + "||ruth||" + str(encRuth) do_one(ip, 1, sending) mailBox[user.getName()] = [] elif ("-u" in values): user = knownUsers[values[values.index("-u") + 1]] for a in seen.keys(): if (seen[a][0] == user): ip = a break else: user = knownUsers[raw_input("Target's username: "******"-ip" in values): ip = values[values.index("-ip") + 1] else: ip = raw_input("Please input IP: ") if (user.getName() not in seenMail): seenMail[user.getName()] = [] if (user.getName() not in mailBox): mailBox[user.getName()] = [] while (len(mailBox[user.getName()]) > 0): temp = mailBox[user.getName()].pop(0) seenMail[user.getName()].append(temp) print(temp) e = Thread(target=threadSniffer, args=(user.getShared(), )) e.start() while True: while (len(mailBox[user.getName()]) > 0): temp = mailBox[user.getName()].pop(0) print(temp) seenMail[user.getName()].append(temp) message = raw_input("\n") if (message == "exit"): break seenMail[user.getName()].append(message) enc = encrypt("||msg||" + message, user.getShared()) do_one(ip, 1, enc) elif (command[:6] == "-check"): print("User : New Message(s) : Verified") for user in mailBox: if (len(mailBox[user]) > 0): printing = user + " : " if (mailBox[user][-1][:2] == ">:"): printing += "yes : " else: printing += "no : " if (user in verified): printing += "yes" else: printing += "no" print(printing) elif (command[:5] == "-help"): help = "" if ("new" in command): help += helpNew() elif ("load" in command.lower()): help += helpLoad() elif ("save" in command.lower()): help += helpSave() elif ("edit" in command.lower()): help += helpEdit() elif ("agree" in command.lower()): help += helpAgree() elif ("all" in command.lower()): help += helpAll() else: help += "--new: creates a new username for you\n" help += "-load: loads the list of known users from memory\n" help += "-save: saves the list of known users to a file\n" help += "-eU: edits an existing user or creates a new one\n" help += "-agree: creates key agreement between you and a user\n" print(help) else: print(command + " is not a valid command, please retry or type " + "-help for the list of commands")
def main(): #Original Admin world_A = "Mars" world_B = "Jupiter" currentUser = User("Admin", "123456", "true", 0, 0, 0, 0) currentState = State(currentUser.userName, "Admin", 0, world_A) adminMenu = { '1': create_user, '2': delete_user, '3': create_file, '4': read_file, '5': write_to_file, '6': change_world, '7': change_password, '8': logout } userMenu = { '1': create_file, '2': read_file, '3': write_to_file, '4': change_password, '5': change_world, '6': logout } userChoice = 0 print("WELCOM!!") while userChoice != "9": if userChoice == "Invalid choice": print("Invalid choice, try again") print("Choos what you want to do from the following options: ") print("1. Create new user. ") print("2. Delete user. ") print("3. Create new file. ") print("4. Read a file.") print("5. Write to an existing file. ") print("6. Enter a new world. ") print("7. Change your password. ") print("8. Logout. ") print("9. Exit. ") userChoice = input("Enter your choice") func = adminMenu.get(userChoice, "Invalid choice") if userChoice == "4" or userChoice == "5": currentUser = func(currentUser, currentState) else: currentUser = func(currentUser) if currentUser.isAdmin == 'false': userChoice = "9" x = convertToInt(worldToValue(currentState.world, currentUser)) currentState = State(currentUser.userName, worldToValue(currentState.world, currentUser), x, currentState.world) print(currentState.userName, currentState.world, currentState.classification) userChoice = "0" while userChoice != "7": if userChoice == "Invalid choice": print("Invalid choice, try again") if currentUser.isAdmin == 'true': break print("Choos what you want to do from the following options: ") print("1. Create new file. ") print("2. Read file. ") print("3. Write to file. ") print("4. Change your password. ") print("5. Enter a new world. ") print("6. Logout. ") print("7. Exit. ") userChoice = input("Enter your choice") func = userMenu.get(userChoice, "Invalid choice") if userChoice == "3" or userChoice == "2": currentUser = func(currentUser, currentState) else: currentUser = func(currentUser) print("Bye")
def save_user(): ''' a function to save a user ''' User.save_user()
def create_user(username, password): ''' fuction that creates user accounts ''' new_user = User(username, password) return new_user
from User import User print('Practica 6 Seguridad Informatica apereg24.\n') print( '-------------------------------------------------------------------------------------------------\n' ) # Se obtiene el alfabeto de un fichero. alphabet = readTextFromFile('data/alphabet.txt') mod = len(alphabet) print('Alfabeto -> \'' + alphabet + '\'.') print('Modulo para operaciones: ' + str(mod) + '.') print() # Se mapean los usuarios con su clave publica RSA. pepa = User() pepa.name = 'Pepa' pepa.n = 62439738695706104201747 pepa.e = 356812573 pepa.p = 249879448303 pepa.q = 249879448349 benito = User() benito.name = 'Benito' benito.n = 743330222539755158153 benito.e = 80263681 benito.p = 27264083009 benito.q = 27264083017 maria = User() maria.name = 'Maria'
def setUp(self) -> None: self.ur = User() self.ad = Address() self.dbu = DBTools() self.logic = Logic()
class TestQunqian(unittest.TestCase): #初始化 def setUp(self) -> None: self.ur = User() self.ad = Address() self.dbu = DBTools() self.logic = Logic() def Test(self): info = self.logic.quQian(self.ur) self.dbu.update("DELETE FROM bank", []) return info def newUser(self): self.ur.setAccount("11111111") self.ur.setUsername("111") self.ur.setPassword("111111") self.ur.setMoney(1000) self.ur.setAddress(self.ad) self.ad.setCountry("中国") self.ad.setProvince("山东省青岛市") self.ad.setStreet("市北区错埠龄二路") self.ad.setDoor("一单元401户") self.logic.xinZeng(self.ur, self.ad) self.logic.cunQian(self.ur) #正常取钱 def test_Quqian1(self): self.newUser() inf = 0 self.ur.setMoney(1) info = self.Test() self.assertEqual(inf,info) #用户不正确密码正确 def test_Quqian2(self): self.newUser() inf = 1 self.ur.setAccount("22222222") self.ur.setMoney(1) info = self.Test() self.assertEqual(inf,info) #用户正确密码不正确 def test_Quqian3(self): self.newUser() inf = 2 self.ur.setPassword("222222") self.ur.setMoney(1) info = self.Test() self.assertEqual(inf,info) #用户密码皆不正确 def test_Quqian4(self): self.newUser() inf = 1 self.ur.setAccount("00000000") self.ur.setPassword("0000000") self.ur.setMoney(1) info = self.Test() self.assertEqual(inf,info) #边界值999 def test_Quqian5(self): self.newUser() inf = 0 self.ur.setMoney(999) info = self.Test() self.assertEqual(inf,info) #边界值1000 def test_Quqian6(self) : self.newUser() inf = 0 self.ur.setMoney(1000) info = self.Test() self.assertEqual(inf, info) # 边界值1 def test_Quqian7(self) : self.newUser() inf = 0 self.ur.setMoney(1) info = self.Test() self.assertEqual(inf, info) # 边界值0 def test_Quqian8(self) : self.newUser() inf = 3 self.ur.setMoney(0) info = self.Test() self.assertEqual(inf, info) # 边界值-1 def test_Quqian9(self) : self.newUser() inf = 3 self.ur.setMoney(-1) info = self.Test() self.assertEqual(inf, info) # 边界值1001 def test_Quqian10(self) : self.newUser() inf = 3 self.ur.setMoney(1001) info = self.Test() self.assertEqual(inf, info)
def update_user_data(verbose=False, start_point=0, max_users=10000): item_dict = open_db(max_users, 1, open_show_indices=True, open_show_data_aggregated=False, open_user_list_indexed=True, get_conn_n=True, get_conn_x=True) print('Update_user_data: length of master_map', len(item_dict['master_map'])) # print(item_dict['user_rating_table_list']) init_show_map_len = item_dict['master_map_max'] c_x = item_dict['conn_x'].cursor() c_n = item_dict['conn_n'].cursor() i = start_point cre_count = 0 for user_rating_table in item_dict['user_rating_table_list'][start_point:]: if verbose: print( str(i) + ':', 'Parsing entries for user: '******'HTTPError for user', user_rating_table) continue except ConnectionResetError as ex: print('ConnectionResetError for user', user_rating_table, ex) cre_count += 1 if cre_count < 5: time.sleep(60) elif cre_count < 6: print( 'Five ConnectionResetErrors have occured -- something is probably wrong.' ) time.sleep(300) else: print( 'Six ConnectionResetErrors have occured -- aborting task.') break continue # print(user.entry_list_tagged) try: init_show_map_len = item_dict['master_map_max'] for score_data, title_data in user.entry_list_tagged: score_data = score_data[1] title_data = title_data[1] if score_data == '-': score_data = 0 else: try: score_data = int(score_data) except Exception as ex: print('Exception for user ' + str(user), title_data, score_data, ex) score_data = 0 if title_data in item_dict[ 'master_dict_n'] or unescape_db_string( title_data) in item_dict['master_dict_n']: title_index = item_dict['master_dict_n'][title_data] else: # curr_len = item_dict['master_map_max'] # item_dict['master_dict_n'][title_data] = curr_len # item_dict['master_map'][curr_len] = title_data # item_dict['master_map_max'] = item_dict['master_map_max'] + 1 # # title_index = item_dict['master_dict_n'][title_data] # if verbose: # print('Added show', title_data, 'to master_map and master_dict') # # print('Master Dict now has size', len(item_dict['master_dict_n'])) # # print('Master Map now has size', len(item_dict['master_map'])) # # print(title_data, score_data) # # print(title_index, score_data) # print('Assigning show', title_data, 'to master_dict id', item_dict['master_dict_n'][title_data]) # # print() # c_n.execute('''INSERT OR REPLACE INTO show_map VALUES (?,?)''', # (item_dict['master_map'][curr_len], curr_len)) pass c_x.execute( '''INSERT OR REPLACE INTO [{}] VALUES (?,?)'''.format(user_rating_table), (title_index, score_data)) # IF loop is executed unto completion, success is true pass item_dict['conn_n'].commit() item_dict['conn_x'].commit() except ValueError as ve: print('ValueError for user ' + str(user), ve) pass except Exception as ex: print('Unknown Exception for user ' + str(user), ex) pass # for show_id in range(init_show_map_len, len(item_dict['master_map'])): # c_n.execute('''INSERT OR REPLACE INTO show_map # VALUES (?,?)''', (item_dict['master_map'][show_id], show_id)) # print(item_dict['master_map'][show_id], show_id) item_dict['conn_x'].commit() item_dict['conn_n'].commit() item_dict['conn_x'].close() item_dict['conn_n'].close() # update_user_data(verbose=True, start_point=4660)
def add_user(self, first_name: str, last_name: str, pesel: int, email:str): user = User(first_name, last_name, pesel, email) self.users.append(user) print(f'Dodano użytkownika {first_name} {last_name}.') return user
'gaming', 'cooking', 'cine', 'boardgame', 'basket', 'tennis', 'theater' ] Locations = { "Kalamaria": [40.57, 22.95], "Thermi": [40.54, 23.02], "Kentro": [40.64, 22.93], "Toumpa": [40.61, 22.97], "Evosmos": [40.67, 22.91], "Sykies": [40.64, 22.95], "Pylaia": [40.59, 22.99], "Triandria": [40.62, 22.97] } Users = [ User("John", "*****@*****.**", "dscdc", 20, "Toumpa", Types[4]), User("Helen", "*****@*****.**", "fvdfv", 24, "Thermi", Types[2]), User("Nick", "*****@*****.**", "dsccdsc", 21, "Triandria", Types[2]), User("Ron", "*****@*****.**", "dscdcdsc", 20, "Sykies", Types[1]), User("Paul", "*****@*****.**", "scsadwdsc", 19, "Toumpa", Types[6]), User("Emily", "*****@*****.**", "sxcdsc", 25, "Kentro", Types[9]), User("Rosa", "*****@*****.**", "cvfdsc", 36, "Kentro", Types[11]), User("George", "*****@*****.**", "dcsadsc", 18, "Thermi", Types[6]) ] Creators = [ Creator("Helen", "*****@*****.**", "dscdsc", 24, "Toumpa", Types[4]), Creator("John", "*****@*****.**", "dscdsc", 28, "Thermi", Types[2]), Creator("Helen", "*****@*****.**", "dscdsc", 21, "Kentro", Types[8]), Creator("Rosa", "*****@*****.**", "dscdsc", 20, "Thermi", Types[6]), Creator("John", "*****@*****.**", "dscdsc", 21, "Toumpa", Types[4]),
from User import User from State import State classification = { "1": "Top-secret", "2": "Secret", "3": "Confidential", "4": "Unclassified" } Worlds = {"1": "Mars", "2": "Jupiter", "3": "Saturn", "4": "Neptune"} currentUser = User("Admin", "123456", "true", 0, 0, 0, 0) currentState = State(currentUser.userName, "Admin", 0, "Mars") def create_user(user): user.create_user() return user def delete_user(user): userName = input("Please enter a user's name to be deleted.") user.delete_user(userName) return user def create_file(user): user.create_file(currentState) return user
def generatePassword(): ''' function to generate a password for the user ''' print(User.generatePassword())
print("Hola") variable1 = 'si' print(variable1) num = 1 print(num) if (1 < 0): print("Es menor") else: print("Es mayor") vector1 = ["Joel", "Eliud", "Ana", "La otra Ana", "Pancho", "Karen", "Pablito"] print(vector1[0]) movies = ["The warriors", "Amores Perros", "Emojis", "Toy Story", "Rattatouille", "Robert Pattison te odio"] print(movies) for m in movies: m = m + " (Clasificacion: R)" print(m) def showName(): print('nombre perron: Jesus') user1 = User("Pancho", 40, "*****@*****.**") print(user1.name) user1.getInfo() showName()
from User import User from Password import Password import hashlib #Example to trigger a sonar vulnerability #import socket #ip = '127.0.0.1' #sock = socket.socket() #sock.bind((ip, 9090)) #typical bandit findings #>>> bandit -r <folder> #deprecated md5 will not be found by sonar... password = "******" hash_object = hashlib.pbkdf2_hmac('sha256', b'123_x32&', b'salt', 10000) password = b"bobo" user1 = User() user1.set_name("Bert") p = Password() hashed_password = p.hash_password(password) user1.set_password(hashed_password) hashed_password = user1.get_password() p.hash_check(password, hashed_password)
with open("../config/record.json","r") as f: data = json.load(f) with open("../config/solve.json","r") as f: solve = json.load(f) towerName = {1:"汽油", 2:"瓶子", 3:"太阳", 4:"风扇", 5:"冰星"} enemyName = {1:"a", 2:"b", 3:"c"} gridMap = Map(data["Map"]["mapHeight"], data["Map"]["mapWidth"], data["Map"]["mapStart"], data["Map"]["mapEnd"], data["Road"]) roadInfo = data["Road"] lenRoad = len(roadInfo) # 道路格子编号从1到lenRoad-1 initWealth = data["UserInitialWealth"] user = User(initWealth) towerConfig = data["Tower"] enemyConfig = data["Enemy"] enemyWave = data["EnemyWave"] # 定义之后三种敌人每回合出来一个 towerMaxID, enemyMaxID = 0, 0 towerCount, enemyCount = 0, 0 towerIns, enemyIns = {}, {} # 存放的是塔的实例,表示的是 {id:instance} flag = 0 def place_tower(app, num): # 放置塔 global solve, gridMap, towerConfig, flag, user, towerCount, towerIns pT = solve[str(num)] tmp = pT.keys()
def authenticate(): output.delete('0.0', END) login = log_field.get() passw = hashlib.md5(pass_field.get().encode()).hexdigest() print(User.getUsersList()) '''
import db from User import User from Upload import Upload from Question import Question import urllib.request, urllib.parse import os f = open('test_data.json', encoding='utf-8') res = f.read() data = json.loads(res) #加载json数据 #取出json中第一个学生的cases数据cases = data['3544']['cases'] #遍历学生对象 for key, value in data.items(): cases = value["cases"] userId = int(key) student = User(userId, 0) #遍历做题信息 for case in cases: caseId = int(case["case_id"]) title = Question(caseId, case["case_type"], case["case_zip"]) db.insert_data(title) for upload in case["upload_records"]: uploadId = int(upload["upload_id"]) codeurl = upload["code_url"] if (len(codeurl) > 254): codeurl = codeurl[49:] record = Upload(uploadId, upload["upload_time"], userId, caseId, codeurl, upload["score"]) db.insert_data(record) #filename = urllib.parse.unquote(os.path.basename(case["case_zip"]))#获取文件名
def setUp(self) -> None: self.u = User() self.a = Address() self.b = Bank()
from flask import Flask from System import System from User import User app = Flask(__name__) app.secret_key = 'very-secret-123' # Used to add entropy system = System() u1 = User("Jaiki", "pw") u2 = User("Ajay", "pw") u3 = User("Takumi", "pw") system.addNewPost( "Sports Arts", "Sports are recreational activities played by competitors around the world. Popular team sports include soccer, basketball, and baseball. ... By incorporating pieces from our collection of sports art, you can represent athleticism and healthy forms of exercise.", u1, ["Arts", "Sports"]) system.addNewPost( "History Of Rugby", "The origin of rugby football is reputed to be an incident during a game of English school football at Rugby School in 1823, when William Webb Ellis is said to have picked up the ball and run with it. ... Old Rugbeian Albert Pell, a student at Cambridge, is credited with having formed the first rugby team.", u2, ["History", "Sports"]) system.addNewPost( "History Of Arts", "Art history is the study of objects of art in their historical development and stylistic contexts; that is genre, design, format, and style. The study includes painting, sculpture, architecture, ceramics, furniture, and other decorative objects.", u3, ["History", "Arts"])
def create_user(self, name, organization, email, password, skill_level, type): uList = self.get_userList() newUser = User(name, organization, email, password, skill_level, type) self.add_user(newUser, uList)
def getUser(self, email, textPassword): user = User(email, textPassword) user.encryptAndSetPassword() user.generateAndSetUserId() return user
class RunApp: def __init__(self, ): print(f.renderText("Welcome to Password Manager")) self.user = User() def sign_up(self): print(f.renderText("SignUp")) if not self.user.token: username = input('Enter Username: '******'Enter new password: '******'Account Name: ') username = input('Account Username: '******'Enter new password: '******'Account Name: ') account = self.user.get_account_details(account_name) datatable = [["Account Name", "Account Username", "Account Password"]] if account: datatable.append(account.values()) table = AsciiTable(datatable) print(table.table) def view_all_accounts(self): print(f.renderText("All Accounts")) accounts = self.user.view_all_accounts() datatable = [["Account Name", "Account Username", "Account Password"]] if accounts: for account in accounts: datatable.append(account.values()) table = AsciiTable(datatable) print(table.table) def dashboard(self): while True: print(f.renderText("Dashboard")) if self.user.token: print("1. Add Account\n" "2. View Specific Account\n" "3. View All Accounts\n" "4. Delete Account\n" "5. Logout") user_input = input('Your response: ') if user_input == '1': self.create_credentials_account() elif user_input == '2': self.view_credential_account() elif user_input == '3': self.view_all_accounts() elif user_input == '4': self.delete_credentials_account() elif user_input == '5': self.user.logout() pass pass else: print("1. Login\n" "2. Quit") response = input("Your Response: ") if response == '1': self.login() elif response == '2': print(f.renderText("Goodbye, see you soon")) sys.exit(0) def run(self): if __name__ == '__main__': Thread(target=self.sign_up()).start() if self.user.token: Thread(target=self.dashboard()).start()
def __init__(self, ): print(f.renderText("Welcome to Password Manager")) self.user = User()
class LeaveModel(colander.MappingSchema): src_user = User() room = Room()
class AddUser(colander.MappingSchema): kind = colander.SchemaNode(colander.String(), validator=colander.OneOf(['ADD_USER'])) model = User()
class InviteModel(colander.MappingSchema): src_user = User() dst_user = User()