def setup_verified_test(session): # Setup blocks = [ Block(blockhash="0x1", number=1, parenthash="", is_current=False), Block(blockhash="0x2", number=2, parenthash="", is_current=True), ] users = [ User( blockhash="0x1", blocknumber=1, user_id=1, is_current=True, wallet="0xFakeWallet1", created_at=datetime.now(), updated_at=datetime.now(), is_verified=False, ), User( blockhash="0x2", blocknumber=2, user_id=2, is_current=True, wallet="0xFakeWallet2", created_at=datetime.now(), updated_at=datetime.now(), is_verified=True, ), ] challenges = [ Challenge( id="referrals", type=ChallengeType.aggregate, active=True, amount="1", step_count=5, ), Challenge( id="ref-v", type=ChallengeType.aggregate, active=True, amount="1", step_count=500, ), ] # Wipe any existing challenges in the DB from running migrations, etc session.query(Challenge).delete() session.commit() session.add_all(blocks) session.commit() session.add_all(users) session.add_all(challenges) session.commit() redis_conn = redis.Redis.from_url(url=REDIS_URL) bus = ChallengeEventBus(redis_conn) bus.register_listener(DEFAULT_EVENT, referral_challenge_manager) bus.register_listener(DEFAULT_EVENT, verified_referral_challenge_manager) return bus
def update_user(current_user, email): if not current_user.admin: return ResponseGenerator.not_authorized() user = User.query.filter_by(email=email).first() data = request.get_json() if not user: return ResponseGenerator.not_found() if data['admin'] == "True": admin = True else: admin = False user.name = data['name'] user.password = data['password'] user.email = data['email'] user.admin = admin update_user = User(name=user.name, email=user.email, password=user.password, admin=user.admin) User.update(update_user) return ResponseGenerator.generate_response( f"{update_user.name} has been successfully updated", 200)
def delete_user(current_user, email): if not current_user.admin: return ResponseGenerator.not_authorized() user = User.query.filter_by(email=email).first() if not user: return ResponseGenerator.not_found() User.delete(user) return ResponseGenerator.generate_response( f"{user.name} deleted successfully from DB.", 200)
def addSampleUser(self): user1 = User( name="テストユーザー1", encrypted_password=bcrypt.generate_password_hash( "password").decode('utf-8'), ) user2 = User( name="テストユーザー2", encrypted_password=bcrypt.generate_password_hash( "password2").decode('utf-8'), ) db.session.add(user1) db.session.add(user2) db.session.commit() return user1, user2
def login(): auth = request.authorization if not auth or not auth.username or not auth.password: # return make_response('Could not verify', 401, {'WWW-Authenticate' : 'Basic realm="Login required"'}) return ResponseGenerator.mandatory_field(["email", "password"], 401) user = User.query.filter_by(email=auth.username).first() if not user: return make_response( 'Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required"'}) if User.check_password(user, auth.password): token = jwt.encode( { 'email': user.email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30) }, Configuration.SECRET_KEY) return jsonify({'token': token.decode('UTF-8')}) return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required"'})
async def authenticate(email: str, password: str): user = await User.find_by_email(email) if user and User.verify_hash(password, user.password): return user raise UnauthorisedException("Username and/or password is incorrect")
def create_user(): form_data = flask.request.json username: str = form_data.get('username') password: str = form_data.get('password') profile: str = form_data.get('profile') watchword: str = form_data.get('watchword') if watchword != WATCH_WORD: return flask.jsonify({"result": False, "message": "合言葉が違います"}), 401 # TODO:有効な文字列か確認。 if not username: return flask.jsonify({"result": False, "message": "ユーザー名は必須です"}), 400 if len(username) > 30: return flask.jsonify({"result": False, "message": "ユーザー名が長すぎます"}), 400 if not password: return flask.jsonify({"result": False, "message": "パスワードは必須です"}), 400 if len(password.encode('utf-8')) > 50: return flask.jsonify({"result": False, "message": "パスワードが長すぎます"}), 400 if User.query.filter_by(name=username).one_or_none(): return flask.jsonify({ "result": False, "message": "ユーザー名が利用されています" }), 409 hashed_password = bcrypt.generate_password_hash(password).decode('utf-8') user: User = User(name=username, encrypted_password=hashed_password, profile=profile) db.session.add(user) db.session.commit() access_token: str = create_access_token(identity=user) return flask.jsonify({ "result": True, "message": "ユーザー(" + username + ")を作成しました。", "data": user.to_json(), 'token': access_token }), 201
class TestUserLogin(unittest.TestCase): def setUp(self): self.__user = User('user_id', 'user_name') def test_should_set_correct_user_login(self): self.assertEqual(self.__user.user_id, "user_id", "Wrong User Id") self.assertEqual(self.__user.name, "user_name", "Wrong User Id") def test_should_return_dict(self): data = self.__user.to_dict() self.assertEqual("user_id", data["id"], "Wrong User Login Dict Return") self.assertEqual("user_name", data["name"], "Wrong User Login Dict Return")
def create_user(): data = request.get_json() email = data['email'] user = User.query.filter_by(email=email).first() if user: return ResponseGenerator.error_response( f"Already {email} exist in DB. Try using other email address", 409) if data['admin'] == "True": admin = True else: admin = False new_user = User(name=data['name'], email=data['email'], password=data['password'], admin=admin) User.save(new_user) return ResponseGenerator.generate_response(data, 200)
def get_users(self) -> list: self.__logger.info("Getting users from configuration") users = list() for document in self.__user_collection.find(): user_id = str(document['_id']) name = str(document['name']) user = User(user_id, name) users.append(user) return users
def create_user(offset: int) -> User: return User( blockhash="0x1", blocknumber=BLOCK_NUMBER, txhash="xyz", user_id=offset, is_current=True, handle=f"TestHandle-{offset}", handle_lc=f"testhandle-{offset}", wallet="0x1", is_creator=False, is_verified=False, name=f"test_name_{offset}", created_at=datetime.now(), updated_at=datetime.now(), )
def add_new_user(self): """ Method to add new user record into the database """ new_record = User(full_name=self.full_name, job_title=self.job_title, image_string=self.image_string, department=self.department, branch_code=self.branch_code, access_level=self.access_level, till_o_balance=self.till_o_balance, till_c_balance=self.till_c_balance, email=self.email, password=self.encrypted_password, lock=self.lock) session.add(new_record) session.commit()
def post(): try: username, password, email = ( request.json.get("username").strip(), request.json.get("password").strip(), request.json.get("email").strip(), ) except Exception as e: logger.info(f"Credentials or email is wrong. {str(e)}") return error.INVALID_INPUT if username is None or password is None or email is None: return error.INVALID_INPUT user = User.query.filter_by(email=email).first() if user is not None: return error.ALREADY_EXIST user = User(username=username, password=password, email=email) db.session.add(user) db.session.commit() return {"status": "registration completed."}
def handle_create_user( session: Session, transaction: ParsedTx, instruction: ParsedTxInstr, db_models: Dict, metadata_dictionary: Dict, records: List[Any], ): instruction_data: CreateUserData = instruction["data"] # Validate that the user row doesn't already exist - error if it does user_id = instruction_data["user_id"] # TODO: validate uniqueness on handle replica_set = list(instruction_data["replica_set"]) eth_address = Web3.toChecksumAddress( f"0x{bytes(list(instruction_data['eth_address'])).hex()}") metadata_multihash = instruction_data.get("metadata") user = User( blockhash=None, blocknumber=None, slot=transaction["result"]["slot"], user_storage_account=str( instruction.get("account_names_map").get("user")), user_authority_account=str(instruction_data.get("user_authority")), txhash=transaction["tx_sig"], user_id=user_id, is_current=True, wallet=eth_address, metadata_multihash=metadata_multihash, primary_id=replica_set[0], secondary_ids=[replica_set[1], replica_set[2]], created_at=datetime.utcfromtimestamp( transaction["result"]["blockTime"]), updated_at=datetime.utcfromtimestamp( transaction["result"]["blockTime"]), ) user_metadata = metadata_dictionary.get(instruction_data["metadata"], {}) update_user_model_metadata(session, user, user_metadata) records.append(user) db_models["users"][user_id].append(user)
def newUser(self, role): """ Function to register a new user. """ try: uname = input(Input.username.value) passwrd = input(Input.password.value) empId = str(uuid.uuid4()) newuser = User(username=uname, password=encrypt_message(passwrd), emp_id=empId, type=role, updated_at=datetime.now(), is_deleted="false") session.add(newuser) session.commit() print(Input.new_user_created.value) return True except exc.SQLAlchemyError as e: print("Error creating new employee : {}".format(e)) return False
def setUp(self): self.emp_id = '123' self.booking_dummy_data = [ booking(booking_id='test', emp_id='test', cab_number='test', source='test', destination='test', arrival_time='test', departure_time='test', created_at=datetime.now() - timedelta(days=1), updated_at=datetime.now(), canceled='0') ] self.user_dummy_data = [ User(username='******', emp_id='emp', password='******', type='type', updated_at=datetime.now(), deleted_at="", is_deleted='false') ] self.routes_dummy_data = [ routes(cab_number='123', route_id='1', stop_name='abcd', stage=4, time='2020-06-08 15:36:50', available_seats=2, updated_at='2020-06-08 15:36:50', is_deleted='False') ] self.cab_dummy_data = [ cab(cab_number='123', capacity='4', is_deleted='False', updated_at='2020-06-08 15:36:50', deleted_at="") ]
def test_referral_challenge(app): redis_conn = redis.Redis.from_url(url=REDIS_URL) with app.app_context(): db = get_db() block = Block(blockhash="0x1", number=BLOCK_NUMBER) referrer = User( blockhash="0x1", blocknumber=BLOCK_NUMBER, txhash="xyz", user_id=1, is_current=True, handle="Referrer", handle_lc="referrer", wallet="0x1", is_creator=False, is_verified=False, name="referrer_name", created_at=datetime.now(), updated_at=datetime.now(), ) with db.scoped_session() as session: # Setup bus = ChallengeEventBus(redis_conn) bus.register_listener(ChallengeEvent.referred_signup, referred_challenge_manager) bus.register_listener(ChallengeEvent.referral_signup, referral_challenge_manager) bus.register_listener(ChallengeEvent.referral_signup, verified_referral_challenge_manager) session.add(block) session.flush() session.add(referrer) session.flush() # set challenge as active for purposes of test session.query(Challenge).filter( or_( Challenge.id == "referred", Challenge.id == "referrals", Challenge.id == "ref-v", )).update({ "active": True, "starting_block": BLOCK_NUMBER }) # Test: # Ensure a single referral from single signup # despite many challenge events dispatch_new_user_signup(referrer.user_id, 2, session, bus) for _ in range(0, 4): bus.dispatch( ChallengeEvent.referral_signup, BLOCK_NUMBER, referrer.user_id, {"referred_user_id": 2}, ) bus.dispatch(ChallengeEvent.referred_signup, BLOCK_NUMBER, 2) bus.flush() bus.process_events(session) challenges = (session.query(UserChallenge).filter( UserChallenge.user_id == referrer.user_id).all()) assert len(challenges) == 1 # Test: # Multiple signups # - Referrer is capped at 5 # - Referred can keep going dispatch_new_user_signup(referrer.user_id, 3, session, bus) dispatch_new_user_signup(referrer.user_id, 4, session, bus) dispatch_new_user_signup(referrer.user_id, 5, session, bus) dispatch_new_user_signup(referrer.user_id, 6, session, bus) dispatch_new_user_signup(referrer.user_id, 7, session, bus) dispatch_new_user_signup(referrer.user_id, 8, session, bus) dispatch_new_user_signup(referrer.user_id, 9, session, bus) dispatch_new_user_signup(referrer.user_id, 10, session, bus) dispatch_new_user_signup(referrer.user_id, 11, session, bus) bus.flush() bus.process_events(session) challenges = (session.query(UserChallenge).filter( UserChallenge.user_id == referrer.user_id, UserChallenge.challenge_id == "referrals", UserChallenge.is_complete == True, ).all()) assert len(challenges) == 5 challenges = (session.query(UserChallenge).filter( UserChallenge.challenge_id == "referred", UserChallenge.is_complete == True, ).all()) assert len(challenges) == 10 # Test: # Ensure there are no verified user referrals created yet challenges = (session.query(UserChallenge).filter( UserChallenge.user_id == referrer.user_id, UserChallenge.challenge_id == "ref-v", UserChallenge.is_complete == True, ).all()) assert len(challenges) == 0 # Test: verified users # - Ensure that verified user referrals aren't counted # for referrer credit # - Ensure that a verified user challenge exists verified_user = User( blockhash="0x1", blocknumber=BLOCK_NUMBER, txhash="xyz", user_id=12, is_current=True, handle="VerifiedReferrer", handle_lc="verifiedreferrer", wallet="0x1", is_creator=False, is_verified=True, name="referrer_name", created_at=datetime.now(), updated_at=datetime.now(), ) session.add(verified_user) session.flush() dispatch_new_user_signup(verified_user.user_id, 13, session, bus) bus.flush() bus.process_events(session) # Ensure no regular referral created challenges = (session.query(UserChallenge).filter( UserChallenge.user_id == verified_user.user_id, UserChallenge.challenge_id == "referrals", UserChallenge.is_complete == True, ).all()) assert len(challenges) == 0 # Ensure one verified referral created challenges = (session.query(UserChallenge).filter( UserChallenge.user_id == verified_user.user_id, UserChallenge.challenge_id == "ref-v", UserChallenge.is_complete == True, ).all()) assert len(challenges) == 1 # Test: verified max count # - Ensure with > 5000 verified referrals, we cap at 5000 # - No regular referrals are made for i in range(5010): dispatch_new_user_signup(verified_user.user_id, 14 + i, session, bus) if i % 500 == 0: bus.flush() bus.process_events(session) bus.flush() bus.process_events(session) # Ensure 5000 verified referral created challenges = (session.query(UserChallenge).filter( UserChallenge.user_id == verified_user.user_id, UserChallenge.challenge_id == "ref-v", UserChallenge.is_complete == True, ).all()) assert len(challenges) == 5000 # Ensure no regular referral created challenges = (session.query(UserChallenge).filter( UserChallenge.user_id == verified_user.user_id, UserChallenge.challenge_id == "referrals", UserChallenge.is_complete == True, ).all()) assert len(challenges) == 0
def setUp(self): self.__user = User("user_id", "user_password") self.__json_object_encoder = JsonObjectEncoder()
def setup_extra_metadata_test(session): blocks = [Block(blockhash="0x1", number=1, parenthash="", is_current=True)] users = [ User( blockhash="0x1", blocknumber=1, user_id=1, is_current=True, wallet="0x38C68fF3926bf4E68289672F75ee1543117dD9B3", created_at=datetime.now(), updated_at=datetime.now(), ) ] challenges = [ # Test numeric challenges # Numeric 1 with default extra data, no completion Challenge( id="numeric_1", type=ChallengeType.numeric, active=True, amount="5", step_count=5, ), # Numeric 2 with some extra data Challenge( id="numeric_2", type=ChallengeType.numeric, active=True, amount="5", step_count=5, ), ] user_challenges = [ UserChallenge( challenge_id="numeric_2", user_id=1, specifier="1", is_complete=False, current_step_count=5, ), ] session.query(Challenge).delete() session.commit() session.add_all(blocks) session.commit() session.add_all(users) session.commit() session.add_all(challenges) session.commit() session.add_all(user_challenges) session.commit() redis_conn = redis.Redis.from_url(url=REDIS_URL) bus = ChallengeEventBus(redis_conn) bus.register_listener( DEFAULT_EVENT, ChallengeManager("numeric_1", NumericCustomUpdater())) bus.register_listener( DEFAULT_EVENT, ChallengeManager("numeric_2", NumericCustomUpdater())) return bus
def setup_listen_streak_challenge(session): # Setup blocks = [ Block(blockhash="0x1", number=1, parenthash="", is_current=False), Block(blockhash="0x2", number=2, parenthash="", is_current=True), ] users = [ User( blockhash="0x1", blocknumber=1, user_id=1, is_current=True, wallet="0xFakeWallet1", created_at=datetime.now(), updated_at=datetime.now(), is_verified=False, ), User( blockhash="0x2", blocknumber=2, user_id=2, is_current=True, wallet="0xFakeWallet2", created_at=datetime.now(), updated_at=datetime.now(), is_verified=True, ), ] challenges = [ Challenge( id="listen-streak", type=ChallengeType.numeric, active=True, amount="1", step_count=7, ) ] user_challenges = [ UserChallenge( challenge_id="listen-streak", user_id=1, specifier="1", is_complete=False, current_step_count=5, ), UserChallenge( challenge_id="listen-streak", user_id=2, specifier="2", is_complete=False, current_step_count=5, ), ] listen_streak_challenges = [ ListenStreakChallenge( user_id=1, last_listen_date=datetime.now() - timedelta(hours=12), listen_streak=5, ), ListenStreakChallenge( user_id=2, last_listen_date=datetime.now() - timedelta(hours=50), listen_streak=5, ), ] # Wipe any existing challenges in the DB from running migrations, etc session.query(Challenge).delete() session.commit() session.add_all(blocks) session.commit() session.add_all(users) session.add_all(challenges) session.commit() session.add_all(user_challenges) session.commit() session.add_all(listen_streak_challenges) session.commit() redis_conn = redis.Redis.from_url(url=REDIS_URL) bus = ChallengeEventBus(redis_conn) bus.register_listener(DEFAULT_EVENT, listen_streak_challenge_manager) return bus
def update_user_model_metadata(session: Session, user_record: User, metadata_dict: Dict): if "profile_picture" in metadata_dict and metadata_dict["profile_picture"]: user_record.profile_picture = metadata_dict["profile_picture"] if ("profile_picture_sizes" in metadata_dict and metadata_dict["profile_picture_sizes"]): user_record.profile_picture = metadata_dict["profile_picture_sizes"] if "cover_photo" in metadata_dict and metadata_dict["cover_photo"]: user_record.cover_photo = metadata_dict["cover_photo"] if "cover_photo_sizes" in metadata_dict: user_record.cover_photo = metadata_dict["cover_photo_sizes"] if "bio" in metadata_dict and metadata_dict["bio"]: user_record.bio = metadata_dict["bio"] if "name" in metadata_dict and metadata_dict["name"]: user_record.name = metadata_dict["name"] if "location" in metadata_dict and metadata_dict["location"]: user_record.location = metadata_dict["location"] # Fields with no on-chain counterpart if ("profile_picture_sizes" in metadata_dict and metadata_dict["profile_picture_sizes"]): user_record.profile_picture = metadata_dict["profile_picture_sizes"] if ("collectibles" in metadata_dict and metadata_dict["collectibles"] and isinstance(metadata_dict["collectibles"], dict) and metadata_dict["collectibles"].items()): user_record.has_collectibles = True else: user_record.has_collectibles = False # TODO: implement # if "associated_wallets" in metadata_dict: # update_user_associated_wallets( # session: Session, # update_task, # user_record, # metadata_dict["associated_wallets"], # "eth", # ) # TODO: implement # if "associated_sol_wallets" in metadata_dict: # update_user_associated_wallets( # session: Session, # update_task, # user_record, # metadata_dict["associated_sol_wallets"], # "sol", # ) if "playlist_library" in metadata_dict and metadata_dict[ "playlist_library"]: user_record.playlist_library = metadata_dict["playlist_library"] if "is_deactivated" in metadata_dict: user_record.is_deactivated = metadata_dict["is_deactivated"] # TODO: implement # if "events" in metadata_dict and metadata_dict["events"]: # update_user_events( # session: Session, # user_record, # metadata_dict["events"], # update_task.challenge_event_bus, # ) # reconstructed endpoints from sp IDs in tx not /ipfs response if "creator_node_endpoint" in metadata_dict: user_record.creator_node_endpoint = metadata_dict[ "creator_node_endpoint"]
def setUp(self): self.__user = User('user_id', 'user_name')
def test_should_get_user_by_id(self): user = User("user_id", "name") self.__user_business_instance.get_user_by_id.return_value = user self.__user_controller.get_user_by_id("user_id") self.assertTrue(self.__user_business_instance.get_user_by_id.called)
def setup_db(session): blocks = [Block(blockhash="0x1", number=1, parenthash="", is_current=True)] users = [ User( blockhash="0x1", blocknumber=1, user_id=1, is_current=True, wallet="0x38C68fF3926bf4E68289672F75ee1543117dD9B3", created_at=datetime.now(), updated_at=datetime.now(), ) ] challenges = [ Challenge( id="boolean_challenge_1", type=ChallengeType.boolean, active=True, amount="5", ), Challenge( id="boolean_challenge_2", type=ChallengeType.boolean, active=True, amount="5", ), Challenge( id="boolean_challenge_3", type=ChallengeType.boolean, active=True, amount="5", ), # No progress on this, but active # should be returned Challenge( id="boolean_challenge_4", type=ChallengeType.boolean, active=True, amount="5", ), # Inactive, with no progress Challenge( id="boolean_challenge_5", type=ChallengeType.boolean, active=False, amount="5", ), # Inactive, WITH progress Challenge( id="boolean_challenge_6", type=ChallengeType.boolean, active=False, amount="5", ), Challenge( id="trending_challenge_1", type=ChallengeType.trending, active=True, amount="5", ), Challenge( id="aggregate_challenge_1", type=ChallengeType.aggregate, active=True, amount="5", step_count=3, ), Challenge( id="aggregate_challenge_2", type=ChallengeType.aggregate, active=True, amount="5", step_count=2, ), Challenge( id="aggregate_challenge_3", type=ChallengeType.aggregate, active=True, amount="5", step_count=2, ), Challenge(id="trending_1", type=ChallengeType.trending, active=True, amount="5"), Challenge(id="trending_2", type=ChallengeType.trending, active=True, amount="5"), Challenge(id="trending_3", type=ChallengeType.trending, active=True, amount="5"), ] user_challenges = [ # Finished the first challenge, disbursed UserChallenge( challenge_id="boolean_challenge_1", user_id=1, specifier="1", is_complete=True, ), # Did finish the second challenge, did not disburse UserChallenge( challenge_id="boolean_challenge_2", user_id=1, specifier="1", is_complete=True, ), # Did not finish challenge 3 UserChallenge( challenge_id="boolean_challenge_3", user_id=1, specifier="1", is_complete=False, ), # Inactive challenge UserChallenge( challenge_id="boolean_challenge_6", user_id=1, specifier="1", is_complete=True, ), UserChallenge( challenge_id="aggregate_challenge_1", user_id=1, specifier="1-2", # compound specifiers, like if user1 invites user2 is_complete=True, ), # Ensure that a non-complete user-challenge isn't counted towards # aggregate challenge score UserChallenge( challenge_id="aggregate_challenge_1", user_id=1, specifier="1-3", is_complete=False, ), UserChallenge( challenge_id="aggregate_challenge_2", user_id=1, specifier="1-2", is_complete=True, ), UserChallenge( challenge_id="aggregate_challenge_2", user_id=1, specifier="1-3", is_complete=True, ), # Trending 1 should be finished and included UserChallenge( challenge_id="trending_1", user_id=1, specifier="06-01-2020", is_complete=True, ), # Trending 2 should not be included UserChallenge( challenge_id="trending_2", user_id=1, specifier="06-01-2020", is_complete=False, ), ] disbursements = [ ChallengeDisbursement( challenge_id="boolean_challenge_1", user_id=1, amount="5", signature="1", slot=1, specifier="1", ) ] # Wipe any existing challenges in the DB from running migrations, etc session.query(Challenge).delete() session.commit() session.add_all(blocks) session.commit() session.add_all(users) session.commit() session.add_all(challenges) session.commit() session.add_all(user_challenges) session.commit() session.add_all(disbursements) redis_conn = redis.Redis.from_url(url=REDIS_URL) bus = ChallengeEventBus(redis_conn) challenge_types = [ "boolean_challenge_1", "boolean_challenge_2", "boolean_challenge_3", "boolean_challenge_4", "boolean_challenge_5", "boolean_challenge_6", "trending_challenge_1", "aggregate_challenge_1", "aggregate_challenge_2", "aggregate_challenge_3", "trending_1", "trending_2", "trending_3", ] for ct in challenge_types: bus.register_listener( DEFAULT_EVENT, ChallengeManager(ct, DefaultUpdater()), ) return bus