async def handleMessage(self, twitchUser: User, message: Message) -> bool: if twitchUser is None: raise ValueError( f'twitchUser argument is malformed: \"{twitchUser}\"') elif message is None: raise ValueError(f'message argument is malformed: \"{message}\"') generalSettings = await self.__generalSettingsRepository.getAllAsync() if not generalSettings.isDeerForceMessageEnabled(): return False elif not twitchUser.isDeerForceMessageEnabled(): return False text = utils.cleanStr(message.content) if text.lower() == self.__deerForceMessage.lower( ) and self.__lastDeerForceMessageTimes.isReadyAndUpdate( twitchUser.getHandle()): await twitchUtils.safeSend(message.channel, self.__deerForceMessage) self.__timber.log( 'DeerForceMessage', f'Handled Deer Force message for {message.author.name} in {twitchUser.getHandle()}' ) return True return False
async def handleMessage(self, twitchUser: User, message: Message) -> bool: if twitchUser is None: raise ValueError( f'twitchUser argument is malformed: \"{twitchUser}\"') elif message is None: raise ValueError(f'message argument is malformed: \"{message}\"') generalSettings = await self.__generalSettingsRepository.getAllAsync() if not generalSettings.isCatJamMessageEnabled(): return False elif not twitchUser.isCatJamEnabled(): return False splits = utils.getCleanedSplits(message.content) if self.__catJamMessage in splits and self.__lastCatJamMessageTimes.isReadyAndUpdate( twitchUser.getHandle()): await twitchUtils.safeSend(message.channel, self.__catJamMessage) self.__timber.log( 'CatJamMessage', f'Handled catJAM message for {message.author.name} in {twitchUser.getHandle()}' ) return True return False
async def handleMessage(self, twitchUser: User, message: Message) -> bool: if twitchUser is None: raise ValueError( f'twitchUser argument is malformed: \"{twitchUser}\"') elif message is None: raise ValueError(f'message argument is malformed: \"{message}\"') generalSettings = await self.__generalSettingsRepository.getAllAsync() if not generalSettings.isChatBandEnabled(): return False elif not twitchUser.isChatBandEnabled(): return False if await self.__chatBandManager.playInstrumentForMessage( twitchChannel=twitchUser.getHandle(), author=message.author.name, message=utils.cleanStr(message.content)): self.__timber.log( 'ChatBandMessage', f'Handled chat band message for {message.author.name} in {twitchUser.getHandle()}' ) return True return False
def set_photo(): params = assert_data_has_keys(request, {'email', 'password', 'patient_id'}, data_type='form') User.authenticate(params['email'], params['password']) if 'photo' not in request.files: raise WebError('photo must be provided', 400) base_filename = store_photo(request.files['photo']) set_patient_filename(params['patient_id'], base_filename) return jsonify({'message': 'ok'})
def get_photo(): params = assert_data_has_keys(request, {'email', 'password', 'patient_id'}) User.authenticate(params['email'], params['password']) base_filename = photo_filename_by_patient(params['patient_id']) if base_filename is None: raise WebError('Patient photo unavailable', 404) filename = retrieve_photo(base_filename) if filename is None: raise WebError('Patient photo unavailable', 404) return send_file(filename)
async def handlePointRedemption(self, twitchChannel: Channel, twitchUser: User, redemptionMessage: str, rewardId: str, userIdThatRedeemed: str, userNameThatRedeemed: str) -> bool: if twitchChannel is None: raise ValueError( f'twitchChannel argument is malformed: \"{twitchChannel}\"') elif twitchUser is None: raise ValueError( f'twitchUser argument is malformed: \"{twitchUser}\"') elif not utils.isValidStr(rewardId): raise ValueError(f'rewardId argument is malformed: \"{rewardId}\"') elif not utils.isValidStr(userIdThatRedeemed): raise ValueError( f'userIdThatRedeemed argument is malformed: \"{userIdThatRedeemed}\"' ) elif not utils.isValidStr(userNameThatRedeemed): raise ValueError( f'userNameThatRedeemed argument is malformed: \"{userNameThatRedeemed}\"' ) if not twitchUser.isPkmnEnabled(): return False splits = utils.getCleanedSplits(redemptionMessage) if not utils.hasItems(splits): await twitchUtils.safeSend( twitchChannel, f'⚠ Sorry @{userNameThatRedeemed}, you must specify the exact user name of the person you want to fight' ) return False opponentUserName = utils.removePreceedingAt(splits[0]) generalSettings = await self.__generalSettingsRepository.getAllAsync() actionCompleted = False if generalSettings.isFuntoonApiEnabled(): if await self.__funtoonRepository.pkmnBattle( userThatRedeemed=userNameThatRedeemed, userToBattle=opponentUserName, twitchChannel=twitchUser.getHandle()): actionCompleted = True if not actionCompleted and generalSettings.isFuntoonTwitchChatFallbackEnabled( ): await twitchUtils.safeSend( twitchChannel, f'!battle {userNameThatRedeemed} {opponentUserName}') actionCompleted = True self.__timber.log( 'PkmnBattleRedemption', f'Redeemed pkmn battle for {userNameThatRedeemed}:{userIdThatRedeemed} in {twitchUser.getHandle()}' ) return actionCompleted
def generate_user(nums,write_into_database=True): user_list = [] fake = Faker() id = 0 while id <= nums: user = User(fake.name(), fake.address(), fake.job(),random.randint(10,100)) if write_into_database: repo = UserRepository() repo.insert_document(DAO,user_data=user.serialize(),collection='user_collection') user_list.append(user) id += 1 return user_list
def sync(): params = assert_data_has_keys(request, {'email', 'password'}, data_type='form') User.authenticate(params['email'], params['password']) if 'db' not in request.files: raise WebError('db must be provided', 400) synchronizer = DbSynchronizer(request.files['db']) if not synchronizer.prepare_sync(): raise WebError("Synchronization failed", 500) synchronizer.execute_server_side_sql() return jsonify({'to_execute': synchronizer.get_client_sql()})
def registerUser(): """ Use the given username and password to create a user if it doesn't already exist """ if User.user_name_exists(request.args['username']): return "-1" else: user = User(user_name=request.args['username'], password=request.args['password'], recent_results=['1', '2', '3']) db.session.add(user) db.session.commit() login_user(user) return "ok"
def test_taken_email(browser_is_opened): github_main_page = MainPage(*browser_is_opened) assert "GitHub" in github_main_page.title id_check_input = github_main_page.email( User(email="*****@*****.**")).get_attribute("aria-describedby") assert not github_main_page.check_input_field( id_check_input, "Email is invalid or already taken")
def __init__(self, **kwargs): super().__init__(**kwargs) self.votes = [] self.comments = [] self.upvote_percentage = [] if self.author: self.author = User(**self.author)
def test_incorrect_password(browser_is_opened): github_main_page = MainPage(*browser_is_opened) assert "GitHub" in github_main_page.title github_main_page.password(User(password="******")) join_github_page = JoinGithubPage(*browser_is_opened) assert join_github_page.message_found( "Password is weak and can be easily guessed")
async def handleMessage(self, twitchUser: User, message: Message) -> bool: if twitchUser is None: raise ValueError( f'twitchUser argument is malformed: \"{twitchUser}\"') elif message is None: raise ValueError(f'message argument is malformed: \"{message}\"') if not twitchUser.isChatLoggingEnabled(): return False self.__chatLogger.logMessage(twitchChannel=twitchUser.getHandle(), userId=str(message.author.id), userName=message.author.name, msg=utils.cleanStr(message.content)) return True
def delete(self, post_id): result = main_app.post_repo.request_delete(post_id, User(**get_jwt_identity())) if result is not None: abort(400, message=result) else: return jsonify({"message": "success"})
async def handleMessage(self, twitchUser: User, message: Message) -> bool: if twitchUser is None: raise ValueError( f'twitchUser argument is malformed: \"{twitchUser}\"') elif message is None: raise ValueError(f'message argument is malformed: \"{message}\"') generalSettings = await self.__generalSettingsRepository.getAllAsync() if not generalSettings.isCynanMessageEnabled(): return False elif not twitchUser.isCynanMessageEnabled(): return False elif message.author.name.lower() != self.__cynanUserName.lower(): return False now = datetime.now(timezone.utc) if now > self.__lastCynanMessageTime + self.__cooldown: self.__lastCynanMessageTime = now await twitchUtils.safeSend( message.channel, f'/me waves to @{self.__cynanUserName} 👋') self.__timber.log( 'CynanMessage', f'Handled Cynan message for {message.author.name} in {twitchUser.getHandle()}' ) return True return False
async def handleEvent(self, twitchChannel: Channel, twitchUser: User, tags: Dict[str, Any]) -> bool: if twitchChannel is None: raise ValueError( f'twitchChannel argument is malformed: \"{twitchChannel}\"') elif twitchUser is None: raise ValueError( f'twitchUser argument is malformed: \"{twitchUser}\"') elif tags is None: raise ValueError(f'tags argument is malformed: \"{tags}\"') if not twitchUser.isChatLoggingEnabled(): return False raidedByName = tags.get('msg-param-displayName') if not utils.isValidStr(raidedByName): raidedByName = tags.get('display-name') if not utils.isValidStr(raidedByName): raidedByName = tags.get('login') if not utils.isValidStr(raidedByName): self.__timber.log( 'RaidLogEvent', f'{twitchUser.getHandle()} was raided, but the tags dictionary seems to have strange values: {tags}' ) return False raidSize = utils.getIntFromDict(tags, 'msg-param-viewerCount', 0) self.__chatLogger.logRaid(raidSize=raidSize, fromWho=raidedByName, twitchChannel=twitchChannel) return True
def generate_random_user(): fake = Faker() profile = fake.simple_profile() last_name = profile["name"].split(' ')[1] return User(username=profile["username"] + last_name, email=last_name + profile["mail"], password=fake.password())
def put(self, post_id): args = parser.parse_args() post = Post(**dict(args)) post.author = User(**get_jwt_identity()) result = main_app.post_repo.request_update(post_id, post.author, post) if result is not None: return abort(400, message=result) return jsonify({'message': 'success'})
def current_user_top_tracks(): ''' Get the current user's top tracks ''' try: return endpoint_response(User.current_user_top_tracks()) except Exception as e: return error_endpoint_response(e)
def __contains__(self, uid): ''' Checks if user is in the queue :param: uid User/UID that identifies who we are looking up :return: True if the UID is found, False otherwise ''' uid = User.get_uid(uid) return (uid in self.busy_queue) or (uid in self.free_queue)
def test_not_available_username_input(browser_is_opened): github_main_page = MainPage(*browser_is_opened) assert "GitHub" in github_main_page.title user = User(username="******") id_check_input = github_main_page.username(user).get_attribute( "aria-describedby") assert not github_main_page.check_input_field( id_check_input, f"Username {user.username} is not available")
def current_user_playlists(): ''' Get current user playlists without getting their profile parameters ''' try: return endpoint_response(User.current_user_playlists()) except Exception as e: return error_endpoint_response(e)
def create_user(_admin_user): params = assert_data_has_keys(request, {'email', 'password', 'name', 'role'}) if params['role'] not in ['admin', 'provider']: raise WebError('Role must be either "admin" or "provider"', 400) id = str(uuid.uuid4()) language = params.get('language', 'en') name_str = LanguageString(id=str(uuid.uuid4()), content_by_language={language: params['name']}) hashed_password = bcrypt.hashpw(params['password'].encode(), bcrypt.gensalt()).decode() user = User(id, name_str, params['role'], params['email'], hashed_password) try: add_user(user) except psycopg2.errors.UniqueViolation: raise WebError('User already exists', 409) all_users = [User.from_db_row(r).to_dict() for r in all_user_data()] return jsonify({'users': all_users})
def request_create(self, username, password): found = self.get_by_name(username) if found is not None: return None new_user = User(id=self.next_id, username=username, password=password) self.by_id[new_user.id] = new_user self.next_id += 1 return new_user
def getUser(): print "\nWelcome to our Casino! Please enter your credentials below.\n" #determine whether to create new account or load old one create = "blah" while create not in ['','create']: create = raw_input("Type 'create' to make a new account" " or hit Enter to proceed to log in\n").lower() if create=='create': #new user; get name name = raw_input("name: ") #get account credentials uname = raw_input("username: "******"password (nothing will appear on screen) : ") if create=='create': #create new account password2 = getpass("confirm password: "******"\nPasswords did not match, please re enter." password = getpass("password: "******"confirm password: "******"\nusername '%s' already taken, try a different one." %uname uname = raw_input("new username: "******"Account creation successful." else: #load account data from disk while True: try: myUser = User(uname,password) break except RuntimeError: print "Invalid username or password. Please try again." uname = raw_input("username: "******"password: "******"Welcome back,", myUser.getName() return myUser
def test_incorrect_username_input(browser_is_opened): github_main_page = MainPage(*browser_is_opened) assert "GitHub" in github_main_page.title id_check_input = github_main_page.username( User(username="******")).get_attribute("aria-describedby") assert not github_main_page.check_input_field( id_check_input, "Username may only contain alphanumeric characters or single hyphens," " and cannot begin or end with a hyphen.")
def user_profile_data(): ''' Get details profile information about the current user. If this is the user's first time logging onto our system, create a User entry with their spotify ID ''' try: return endpoint_response(User.user_profile_data()) except Exception as e: return error_endpoint_response(e)
def add_post(): if not request.json: return make_resp(jsonify({'message': 'Empty request'}), 400) elif not check_keys(request.json, ("category", "type", "title")): return make_resp(jsonify({'message': 'Bad request'}), 400) post = Post(**request.json) post.author = User(**get_jwt_identity()) post = app.post_repo.request_create(post) return make_resp(jsonify(post), 200)
async def handlePointRedemption(self, twitchChannel: Channel, twitchUser: User, redemptionMessage: str, rewardId: str, userIdThatRedeemed: str, userNameThatRedeemed: str) -> bool: if twitchChannel is None: raise ValueError( f'twitchChannel argument is malformed: \"{twitchChannel}\"') elif twitchUser is None: raise ValueError( f'twitchUser argument is malformed: \"{twitchUser}\"') elif not utils.isValidStr(rewardId): raise ValueError(f'rewardId argument is malformed: \"{rewardId}\"') elif not utils.isValidStr(userIdThatRedeemed): raise ValueError( f'userIdThatRedeemed argument is malformed: \"{userIdThatRedeemed}\"' ) elif not utils.isValidStr(userNameThatRedeemed): raise ValueError( f'userNameThatRedeemed argument is malformed: \"{userNameThatRedeemed}\"' ) if not twitchUser.isPkmnEnabled(): return False generalSettings = await self.__generalSettingsRepository.getAllAsync() actionCompleted = False if generalSettings.isFuntoonApiEnabled(): if await self.__funtoonRepository.pkmnGiveShiny( userThatRedeemed=userNameThatRedeemed, twitchChannel=twitchUser.getHandle()): actionCompleted = True if not actionCompleted and generalSettings.isFuntoonTwitchChatFallbackEnabled( ): await twitchUtils.safeSend(twitchChannel, f'!freeshiny {userNameThatRedeemed}') actionCompleted = True self.__timber.log( 'PkmnShinyRedemption', f'Redeemed pkmn shiny for {userNameThatRedeemed}:{userIdThatRedeemed} in {twitchUser.getHandle()}' ) return actionCompleted
def is_stu(uid): ''' Checks if a UID or User is a student UID :param: uid UID string or User to extract a UID out of :return: True if the UID is a Student, False otherwise ''' uid = User.get_uid(uid) if (type(uid) is str): return UID_PREFIX_STU == uid[:len(UID_PREFIX_STU)] return False
def request_create(self, username, password): """Create new user""" found = self.get_by_name(username) if found is not None: return None # user with this name already created new_user = User(id=self.next_id, username=username, password=password) self.by_id[new_user.id] = new_user self.next_id += 1 return new_user
def listUsers(request): forum = request.GET.get('forum') since = request.GET.get('since_id') limit = request.GET.get('limit') order = request.GET.get('order') sql = "SELECT DISTINCT user,name from Post where Post.forum = '%s'" % forum if since is not None: sql += "and Post.user_id>=%s " % since if order is not None: if order == "asc": sql += "order by Post.name ASC " else: sql += "order by Post.name DESC " if limit is not None: sql += "limit %s" % limit sql = "SELECT User.email, User.id, User.username, User.name, User.is_anonymous, User.about" \ " from User join (%s) as t2 on User.email=t2.user " % sql if order is not None: if order == "asc": sql += "order by t2.name ASC " else: sql += "order by t2.name DESC " result = sql_select(sql) if result == (): resp = {"code": 0, "response": []} resp = json.dumps(resp) return HttpResponse(resp, content_type="application/json") users = [] for data in result: params = { 'email': data[0], 'username': data[2], 'name': data[3], 'isAnonymous': bool(data[4]), 'about': data[5], } user = User(params) user.id = data[1] sql = "SELECT follower FROM Follow where followee=" + "'" + user.email + "'" + 'and is_deleted=0' followers = sql_select(sql) followers = list(itertools.chain.from_iterable(followers)) sql = "SELECT followee FROM Follow where follower=" + "'" + user.email + "'" + 'and is_deleted=0' following = sql_select(sql) following = list(itertools.chain.from_iterable(following)) user.followers = followers user.following = following sql = "SELECT thread FROM Subscription where user='******' and is_deleted=FALSE" % user.email subscriptions = sql_select(sql) subscriptions = list(itertools.chain.from_iterable(subscriptions)) user.subscriptions = subscriptions users.append(user.serialize()) resp = {"code": 0, "response": users} resp = json.dumps(resp) return HttpResponse(resp, content_type="application/json")
def listFollowers(request): email = request.GET.get('user') since = request.GET.get('since_id') limit = request.GET.get('limit') order = request.GET.get('order') sql = "SELECT User.email, User.id, User.username, User.name, User.is_anonymous, User.about" \ " from Follow join User on Follow.follower=User.email where Follow.is_deleted != TRUE AND Follow.followee = '%s'" % email if since != None: sql += "and User.id>=%s " % since if order != None: if order == "asc": sql += "order by User.name ASC " else: sql += "order by User.name DESC " if limit != None: sql += "limit %s" % limit result = sql_select(sql) users = [] for data in result: params = { 'email': data[0], 'username': data[2], 'name': data[3], 'isAnonymous': bool(data[4]), 'about': data[5], } user = User(params) user.id = data[1] sql = "SELECT follower FROM Follow where followee=" + "'" + user.email + "'" + 'and is_deleted=0' followers = sql_select(sql) followers = list(itertools.chain.from_iterable(followers)) sql = "SELECT followee FROM Follow where follower=" + "'" + user.email + "'" + 'and is_deleted=0' following = sql_select(sql) following = list(itertools.chain.from_iterable(following)) user.followers = followers user.following = following sql = "SELECT thread FROM Subscription where user='******' AND is_deleted=FALSE " % user.email subscriptions = sql_select(sql) subscriptions = list(itertools.chain.from_iterable(subscriptions)) user.subscriptions = subscriptions users.append(user.serialize()) resp = {"code": 0, "response": users} resp = json.dumps(resp) return HttpResponse(resp, content_type="application/json")