def user_handle(email_address): body = {"email": email_address} user_object = User(body) result = user_object.get_user() if result['statusCode'] == 200: return result['response'], 200 return result['response'], 400
async def 공격(self, ctx, arg='NONE'): """ '!공격 @멘션'처럼 사용하여 다른 유저를 공격하는 명령어 예시예요! """ # 멘션을 ID로 변환 defender_id = arg.replace('<@', '').replace('>', '').replace('!', '') if not defender_id.isdigit(): return await ctx.send(f"공격 대상을 알 수 없습니다 : `{defender_id}`") defender = User(int(defender_id)) attacker = User(ctx.author) # 유저의 체력이 이미 없는 경우 if attacker.hp == 0: return await ctx.send("쓰러진 상태에서는 공격할 수 없어...") # 이미 공격 대상의 체력이 0이면 if defender.hp == 0: return await ctx.send("이미 쓰러진 사람을 공격하는 건 매너 위반이야...") logs = attacker.attack_to(defender) logdata = logs[0] window = await ctx.send(f"```diff\n{logdata}```", reference=ctx.message) for i in logs[1:]: logdata += '\n' + i await asyncio.sleep(1.5) await window.edit(content=f"```diff\n{logdata}```")
def create_event(self, users): self.name_event = input("Nome do evento: ") self.title = input("Digite uma sigla: ") self.description = input("De uma breve descricao do evento: ") self.local = input("Informe o local: ") self.start_date = input("Data de inicio: ") self.end_date = input("Data do fim do evento: ") self.cpf_admin_event = input( "Informe o CPF do adiministrador do evento: ") from classes.user import verify_event_adm_user_cpf from classes.user import User while not verify_event_adm_user_cpf(users, self.cpf_admin_event): print( "Não existe administrador de evento com esse CPF cadastrado!") print("Deseja cadastra-lo? ") print("SIM//NÂO") resposta = input() if resposta[0].upper() == "S": new_admim_event = User() new_admim_event.create_account(users) users.append(new_admim_event) else: break self.cpf_admin_event = input( "Informe o CPF do adiministrador do evento: ") self.value_pro = input( "Informe o valor para participantes profissional: ") self.value_est = input("Informe o valor para estudantes: ") self.participants = []
def register(self): """Get, validate and convert user input data""" first_name = self.first_name_entry.get() insertion = self.insertion_entry.get() last_name = self.last_name_entry.get() zip_code = self.zip_entry.get() streetnumber = self.streetnumber_entry.get() email = self.email_entry.get() # Validate input if self.is_valid(first_name, last_name, zip_code, streetnumber, email): d = self.convert(first_name, insertion, last_name, zip_code, streetnumber, email) check = User(self.ov).register(d['first_name'], d['insertion'], d['last_name'], d['zip_code'], d['streetnumber'], d['email']) if check: user = User(self.ov) self.frame.pack_forget() MainScreen(self.master, user) return True else: return False
def initialize_users(): # Need to create a datastructure that stores the user users = [] transactions = [] for i in range(utils.number_of_users): coinsList = [] newUser = User(i) for j in range(10): cID = str(i * 10 + j) signature = sign_message(scrooge_private, str(cID)) encoded = base64.b64encode(signature) no_bytes = encoded.decode('utf-8') coin_dict = {} coin_dict[cID] = no_bytes newUser.add_coin(coin_dict) transaction = {} transaction['previous_transaction'] = None transaction['sender'] = 'scrooge' transaction['receiver'] = newUser.user_id transaction['coin_id'] = json.dumps(coin_dict) transactions.append(transaction) utils.printLog( "User " + str(i) + "\n" + str(newUser.private_key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo))) utils.printLog("10 coins") users.append(newUser) return users, transactions
def __set_user(self, name, login, pwd): """ Metoda przypisująca dane logowania do pola user. :param name: podpis :param login: login :param pwd: hasło """ self.user = User(login, pwd, name)
def deletarusuario(self): login = raw_input('Digite o login do usuario que deseja deletar: ') user = User() user = user.get(login) if user: user.remove() else: print 'Usuario nao encontrado.'
def test_signup_user_returns_correct_id(self): self.app.signup_user(self.user) self.assertEqual(len(self.app.users), 1) self.user = User('*****@*****.**', 'henry123', 'Henry', 'Kato') self.app.signup_user(self.user) self.assertEqual(len(self.app.users), 2) self.user = User('*****@*****.**', 'henry0009', 'Henry', 'Mutunji') self.app.signup_user(self.user) self.assertEqual(len(self.app.users), 3)
def simulate_scan(self): """Simulate OV card scan by entering the serial key""" user = User(self.scan_simulation.get()) if user.is_registered(): self.frame.pack_forget() InfoScreen(self.master, user) else: self.frame.pack_forget() RegisterScreen(self.master, user.get_ov())
def test_doesnt_updateWip(self): a_user = User("The Shadow") story = Story({ "name":"Some Thigns", "id":"2222222", "current_state":"", "owned_by":"George", "updated_at":"2012/09/20 14:10:53 UTC"}) a_user.updateWip(story) self.assertEquals(a_user.wip, 0)
def autenticar(self): login = raw_input('Digite o seu login: '******'Digite a sua senha: ') user = User() user = user.get(login) if user: if user.nome == login and user.senha == senha: print 'Seja bem vindo %s!' % user.nome else: print 'Senha incorreta.' else: print 'Usuario nao encontrado.'
def searchBooksBy(section, filt): result = auth.checkData() if result['auth']: words = json.loads(request.data)['words'] if section == 'explore': result['books'] = sql.searchBooks(filt, words) elif section == 'readlater': user = User() result['books'] = sql.searchReadLater(words, user.idUser) elif section == 'readings': user = User() result['books'] = sql.searchPendings(words, user.idUser) return jsonify({'result': result})
def login(): print("Enter username : "******"Enter password : "******"Welcome - Access Granted") while True: menu() else: print('Invalid Creditails...')
def index(): """ Home page :return: html_documentation """ if 'user' in session: try: user = User(session['user']) except NameError: return redirect(url_for('login')) data = {'username': session['user'], 'keywords': user.get_full_data(), 'telegram_links': user.get_pretty_links('telegram'), 'twitter_links': user.get_pretty_links('twitter')} return render_template('index.html', username=session['user'], data=data) return redirect(url_for('login'))
def login(**kwargs): if 'data' in request.json: user_object = User(request.json['data']) result = user_object.login() else: return 'Poorly formed body', 400 if result['statusCode'] == 200: resp = make_response(result['response']) cookie = result['cookie'] resp.set_cookie(cookie['name'], cookie['value'], domain=cookie['domain'], expires=cookie['expires'], secure=cookie['secure'], httponly=cookie['httpOnly'], path=cookie['path']) resp.headers['x-access-tokens'] = cookie['value'] return resp return result['response'], 400
async def start(self, ctx): if self.tournament.status >= 3: raise commands.BadArgument("The tournament has already started.") req = ('name', 'host') missing = [] for attr in req: if getattr(self.tournament, attr) is None: missing.append("`" + attr + "`") if missing: items = " and ".join(item for item in missing) raise commands.BadArgument( f"You have not specified a {items} for the tournament.") if self.tournament.time is None: self.tournament.time = datetime.utcnow() await self.tournament.host.add_roles(self.roles.temp_host) host_id = self.tournament.host.id ign_cache[host_id] = User.fetch_attr_by_id(host_id, "IGN") User.fetch_attr_by_id(host_id, "IGN") await ctx.message.add_reaction(Emote.check) Log("Tournament Started", description= f"{ctx.author.mention} started **{self.tournament.name}**.", color=Color.green()) self.tournament.status = Status.Opened embed = UpdatedEmbed(self.tournament) try: msg = await self.channels.t_channel.fetch_message( self.channels.t_channel.last_message_id) await msg.delete() except (AttributeError, NotFound): pass self.tournament.msg = await self.channels.t_channel.send( f"Tournament **{self.tournament.name}** has started!" f" {self.roles.tournament.mention}", embed=embed) await self.tournament.msg.add_reaction(Emote.join) if ModifierCheck("SpectatorsAllowed", self.tournament.modifiers) is not False: await self.tournament.msg.add_reaction("📽️") self.checklist = await Checklist.create(ctx)
async def exec(self, ctx, *args): if ctx.author.id not in Config.admin: return await ctx.send( '권한이 부족해!' '\n`❗ 봇 관리자라면 config.py의 admin 리스트에 자신의 디스코드 id가 있는지 확인해 봐!`') text = ' '.join(args) me = User(ctx.author) logger.info(f'{me.name}이(가) exec 명령어 사용 : {text}') try: exec(text) except Exception as e: embed = discord.Embed(color=0x980000, timestamp=datetime.datetime.today()) embed.add_field(name="🐣 **Cracked!**", value=f"```css\n[입구] {text}\n[오류] {e}```", inline=False) logger.err(e) else: embed = discord.Embed(color=0x00a495, timestamp=datetime.datetime.today()) embed.add_field(name="🥚 **Exec**", value=f"```css\n[입구] {text}```", inline=False) embed.set_footer(text=f"{ctx.author.name} • exec", icon_url=str( ctx.author.avatar_url_as(static_format='png', size=128))) await ctx.send(embed=embed, reference=ctx.message)
def register_submit(): username = request.form.get("username") firstname = request.form.get("firstname") lastname = request.form.get("lastname") password = request.form.get("password") password_confirm = request.form.get("passwordConfirm") if ((not len(username)) or (not len(firstname)) or (not len(lastname)) or (not len(password)) or (not len(password_confirm))): return error_found("A field is empty") valid_username = unique_user(db, username) if valid_username is False: return error_found("Username already exists") valid_password = password_compare(password, password_confirm) if valid_password is False: return error_found("Passwords are not identical") user = User(username, firstname, lastname) create_user(db, user, password) return render_template("submit.html", username=username, firstname=firstname, lastname=lastname)
async def ign(self, ctx, ign=None): if ign is None: await ctx.send( "Please provide your Werewolf Online in-game name: `;ign example_name`" ) return user = User.fetch_by_id(ctx, ctx.author.id) old_ign = user.ign user.ign = ign self.client.get_cog("TOrganizer").cache_ign(ctx.author, ign) await ctx.send( f"{Emote.check} {ctx.author.mention}, your Werewolf Online IGN has been set to `{ign}`." ) Log("IGN Set", description=f"{ctx.author.mention} has set their IGN to `{ign}`.", color=0x6a0dad, fields=[{ 'name': 'Previous IGN', 'value': old_ign }])
def register(): """ """ if request.method == "POST": # read the posted values from the UI email = request.form.get('inputEmail', None) password = request.form.get('inputPassword', None) # validate received values if email and password and not user_exists(email): with db.ConnectionInstance() as queries: key = random_key(10) + email # TODO delete or merge previously created user if exists #adds new user to the database added = queries.add_user(datetime.utcnow(), email, hash_password(password), key) if (added): user = User(email) #adds default calendar to that user queries.add_calendar(datetime.utcnow(), user.user_id) #send verfication email send_verification(email, key) return render_template("verify_send.html", email=email) # reload if something not right # TODO maybe some error messages return redirect('/')
async def begin(self, ctx): if self.tournament.status != Status.Opened: raise commands.BadArgument( "The tournament cannot be closed right now.") if len(self.tournament.get_participants()) < 1: raise commands.BadArgument( "There are no participants in the tournament.") no_ign = "" for player in self.tournament.get_participants(): user = User.fetch_by_id(ctx, player.id) if user.ign is None: no_ign += f"**{player.name}**\n" if no_ign != "": raise commands.BadArgument( "Some players do not have an IGN set: \n" + no_ign) await ctx.send( f"{Emote.check} The tournament has been closed. Players can no longer join!" ) self.tournament.status = Status.Closed Log("Tournament Closed", description= f"{ctx.author.mention} closed **{self.tournament.name}**.", color=Color.dark_orange()) await self.tournament.msg.clear_reactions() embed = UpdatedEmbed(self.tournament) await self.tournament.msg.edit(embed=embed)
def load_user(email): """Returns an object of class User based on provided unique identifier if user in the database, otherwise None """ if user_exists(email): return User(email) return None
def profile(): # Variables locales error = None response = None id_client = None id_user = None try: # Revisar formato JSON valid_json_data = Utils.validateRequestJsonData(request) if valid_json_data: # Revisar existencia del token token = Utils.getTokenFromHeader(request) if token is not None: # Revisar validez del token auth = JWTAuth(__jwtPrivateKey, __jwtPublicKey) decoded_token = auth.decodeToken(token) if 'errno' not in decoded_token: # Revisar argumentos válidos json_data = request.get_json() validate_arguments = Utils.allPostArgumentsExists( json_data, ['id_user', 'id_client']) if validate_arguments[0]: # Crear db, tupla de args y llamada a SP db = Database.getInstance(__dbHost, __dbUser, __dbPswd, __dbName) id_user = json_data['id_user'] id_client = json_data['id_client'] args = (id_user, id_client) user_opt = db.callProc(Procedure.GET_USER_MENU_OPTIONS, args, True) # Obtención de opciones # Revisar que el usuario existe if user_opt: response = User.get_ordered_options(user_opt) else: # Usuario inválido error = Error.INVALID_USER else: # Argumentos inválidos error = copy.deepcopy(Error.REQUIRED_ARGUMENTS) error['errmsg'] = error['errmsg'].format( validate_arguments[1]) else: # Token inválido error = decoded_token else: # Token inexistente error = Error.TOKEN_NOT_FOUND else: # Formato JSON inválido error = Error.INVALID_REQUEST_BODY except: Utils.setLog() error = Error.PROGRAMMING_ERROR return wrappers.Response(json.dumps(response if error is None else error), 200, mimetype='application/json')
def sign_in(): """ Signs in user to their account """ if request.method == 'POST': # Pick form values email = request.form['email'] password = request.form['password'] user = User(email, password) # start session session['id'] = bucketApp.sign_in(user) if session['id']: global current_user user = [ user for user in bucketApp.all_users if user.id == session['id'] ] current_user = user[0] return redirect(url_for('buckets')) return render_template('signIn.html', error='Invalid username or password') else: return render_template('signIn.html')
def main_handler(message): user = User.find_user_and_delete_message(message, bot) text = message.text.lower() if 'играть' in text: lobbies_menu(user) elif 'настройки аккаунта' in text: account_settings_menu(user)
def index(): """Renders index or home page Returns: an index page template """ if request.method == 'POST': # getting form variables email = request.form['email'] password = request.form['password'] # signing in user global current_user current_user = User(email, password) # creating session session['id'] = recipe_app.signin_user(current_user) if session['id']: session['logged_in'] = True return redirect(url_for('dashboard')) else: error = 'Wrong email or password combination' return render_template('index.html', title='Home', error=error) return render_template('index.html', title='Home')
def signup(): """Renders signup page Returns: signup page template for user """ if 'logged_in' in session: return redirect(url_for('index')) if request.method == 'GET': return render_template('signup.html', title='Sign Up') else: # getting form variables firstname = request.form['firstname'] lastname = request.form['lastname'] email = request.form['email'] password = request.form['password'] # creating user object global current_user current_user = User(email, password, firstname, lastname) recipe_app.signup_user(current_user) flash( 'You have successfully created your account, \ please login into your account', 'success') return redirect(url_for('index'))
def lobby_menu_handler(self, message): user = User.find_user_and_delete_message(message, self.bot) if message.text == 'выход': lobby = user.lobby user.exit_lobby() for l_user in lobby.users: self.lobby_menu(l_user) self.lobbies_menu(user)
def next_clock_tick(self, users_clock_ticks): for user in range(users_clock_ticks): self.customer_management.allocate_user(User(self.ttask)) self.customer_management.remove_timeout_users() self.customer_management.optimize_servers() self.customer_management.save_state() self.customer_management.update_ttime()
def updateAlines(idbook, alines): result = auth.checkData() if result['auth']: user = User() result['update'] = sql.updateAlines(idbook, user.idUser, alines) return jsonify({'result': result})
def get_users(self): users = [] for user in self.get_data(self.USER_TABLE): user = User(user[0], user[1]) users.append(user) return users
def loginEvent(self): try: # create user object and validate user = User() user.setUsername(self.usernameEntry.get()) user.setPassword(self.passwordEntry.get()) if user.validate(): self.parent.destroy() root = tk.Tk() app = MainPage(root, user) app.focus_force() else: messagebox.showerror( "Login Failed!!!", "Somthing is wrong, could not login. Please check your username and password and try again." ) self.secondLabel["text"] = "Incorrect username or password" self.secondLabel["fg"] = "red" except: messagebox.showwarning( "Login Failed!!!", "Username and Password field can not be emplty, If you do not have account then press 'Signup' button to register." ) self.secondLabel["text"] = "Username or password cannot be empty" self.secondLabel["fg"] = "red"
def new_avatar_handler(message): user = User.find_user_and_delete_message(message, bot) new_avatar = message.text # 'o' if len(new_avatar) == 1 and new_avatar.isalpha(): user.avatar = new_avatar.lower() account_settings_menu(user) else: user.help_message = 'Аватар должен быть 1 буквой.' account_settings_menu(user)
def test_UserList_tojson(self): a_user = User("George") story_xml = ET.parse("data/story_2").getroot() story = Story(xml_to_dictonary(story_xml)) a_user.updateWip(story) user_list = [a_user] self.assertEquals( userlist_tojson(user_list), json.dumps([{ "name": "George", "current_stories": [{ "id": "22222222", "name": "The Rest Of the Things", "updated_at":"2012/09/20 14:10:53 UTC", "days_since_updated":_days_since_last_updated(_tracker_string_to_time(story.updated_at), datetime.today()) }], "wip": 1 }], sort_keys=True))
def server(): serialized={} serv = server_socket() host = socket.gethostname() port = 8999 serv.bind((host, port)) serv.listen(5) c, addr = serv.accept() while True: msg = c.recv(1024) #server_json = json() serialized = convert_from_json_object(msg) serialized_list = [None]*5 serialized_list[0]=serialized['action'] if serialized_list[0] == "signup": serialized_list[1]=serialized['username'] serialized_list[2]=serialized['password'] serialized_list[3]=serialized['DOB'] serialized_list[4]=serialized['email'] U = User(serialized_list[1], serialized_list[2], serialized_list[3], serialized_list[4]) validation = U.validate() if not isinstance(validation,str): #if project13_forums.model.memory.sign_up(U): if sign_up(U): c.send(U.deserializer("Succesful")) else: c.send(U.deserializer("Username already exists")) else: c.send(U.deserializer("Invalid Credentials " + validation)) pass elif serialized_list[0] == "login": serialized_list[1]=serialized['username'] serialized_list[2]=serialized['password'] UA = UserAuth(serialized_list[1], serialized_list[2]) validation = UA.validate() if not validation.isstring(): if sign_in(UA): c.send(UA.deserializer("login successful")) else: c.send(UA.deserializer("username password mismatch")) else: c.send(UA.deserializer("Invalid Credentials " + validation)) pass elif serialized_list[0] == "view_forum": serialized_list[1]=serialized['forum_name'] VF = ViewForum(serialized_list[1]) forum_list=view_forum(VF.forum_name) forum_json=convert_list(forum_list) c.send(VF.deserializer(forum_json)) pass elif serialized_list[0] == "new_sub_forum": serialized_list[1]=serialized['forum_name'] serialized_list[2]=serialized['new_sub_forum'] serialized_list[3]=serialized['created_by'] CSF=CreateSubForum(serialized_list[1],serialized_list[2],serialized_list[3]) if create_sub_forum(CSF): c.send(CSF.deserializer(serialized_list[2]+"subforum is created")) else: c.send(CSF.deserializer("subforum name already exists")) elif serialized[0] == "open_sub_forum": serialized_list[1]=serialized['forum_name'] serialized_list[2]=serialized['new_sub_forum'] VSF = ViewSubForum(serialized_list[1],serialized_list[2]) sub_forum_question_list=view_sub_forum(VSF) question_json=convert_list(sub_forum_question_list) c.send(question_json) elif serialized_list[0] == "post_question": serialized_list[1]=serialized['forum_name'] serialized_list[2]=serialized['sub_forum'] serialized_list[3]=serialized['created_by'] serialized_list[4:]=serialized['new_question'] PQ = PostQuestion(serialized_list[1],serialized_list[2],serialized_list[3],serialized_list[4:]) if post_question_in_sub_forum(PQ): c.send(PQ.deserializer("successfully posted")) elif serialized[0] == "post_answer": serialized_list[1]=serialized['forum_name'] serialized_list[2]=serialized['sub_forum'] serialized_list[3]=serialized['created_by'] serialized_list[4]=serialized['question_new'] PC=PostComment(serialized_list[1],serialized_list[2],serialized_list[3]) if post_comment(PC): c.send(PC.deserializer("successfully posted")) elif serialized_list[0] == "view_question": serialized_list[1]=serialized['forum_name'] serialized_list[2]=serialized['sub_forum'] serialized_list[3:]=serialized['question'] VQ=viewQuestion(serialized_list[1],serialized_list[2],serialized_list[3]) reply_list=view_ques_in_sub_forum(VQ) c.send(VQ.deserializer(reply_list)) pass elif serialized_list[0] == 'exit': c.close() serv.close()
def cadastrarusuario(self): login = raw_input('Digite o login do usuario: ') senha = raw_input('Digite a senha do usuario: ') novo_usuario = User(login, senha) novo_usuario.save()
def listarusuarios(self): all_users = User() all_users = all_users.listall() for user in all_users: print user.id, ' - ' , user.nome