def post(self): data = request.json logger.info(f'Register Post data {data} [{type(data)}]') if data is None: return {'status': 'fail', 'message': 'No data passed'}, 400 try: user = User.query.filter( or_(User.email == data.get('email'), User.username == data.get('username'))).first() if user: logger.info(f"Resister found pre-existing User: {user}") return { 'status': 'fail', 'message': 'Username/Email Already exist!' }, 401 user = User( email=data.get('email'), username=data.get('username'), password=data.get('password'), ) db.session.add(user) db.session.commit() auth_token = user.encode_auth_token(user.id) return { 'status': 'success', 'message': 'Successfully registered', 'auth_token': auth_token.decode() }, 201 except Exception as e: logger.error(e) return { 'status': 'fail', 'message': 'An error has occurred', }, 401
def create_user(): username=request.json['username'] email=request.json['email'] password=request.json['password'] pw_hash = generate_password_hash(password) if len(password)<6: return jsonify({'password':['Passwords should be at least 6 charatcers long']}), HTTP_400_BAD_REQUEST if len(username)<3: return jsonify({'username':['usernames should be at least 3 charatcers long']}),HTTP_400_BAD_REQUEST if not validators.email(email): return jsonify({'email':['Email is of invalid format']}),HTTP_400_BAD_REQUEST if not username.isalnum() or " " in username: return jsonify({'username':['username should only contain alphanumeric characters,no spaces']}),HTTP_400_BAD_REQUEST if User.query.filter_by(email=email).first() is not None: return jsonify({'email':['Email is taken']}),HTTP_409_CONFLICT if User.query.filter_by(username=username).first() is not None: return jsonify({'username':['username is taken']}),HTTP_409_CONFLICT user=User(username=username, email=email,password=pw_hash) db.session.add(user) db.session.commit() return jsonify({'user':{ 'username':username, 'email':email, }}),HTTP_201_CREATED
def wrapper(*args, **kwargs): tg_user = g.telegram_user tg_chat = g.telegram_chat # TODO: check if user came from different chat, # then also register that chat in db. if (UserQuery.exists(tg_user.id)): return func(*args, **kwargs) new_user = User(telegram_id=tg_user.id, is_bot=tg_user.is_bot, language=SupportedLanguage.get(tg_user.language_code)) Chat(telegram_id=tg_chat.id, type=ChatType.get(tg_chat.type), user=new_user) db.session.add(new_user) try: db.session.commit() except Exception as e: print(e) return cancel_command(tg_chat.id) return func(*args, **kwargs)
def prepare_user_message(user: User, msg_score, *, is_media=False, signed=False, tripcode=False): # prerequisites if user.isInCooldown(): return rp.Reply(rp.types.ERR_COOLDOWN, until=user.cooldownUntil) if (signed or tripcode) and not enable_signing: return rp.Reply(rp.types.ERR_COMMAND_DISABLED) if tripcode and user.tripcode is None: return rp.Reply(rp.types.ERR_NO_TRIPCODE) if is_media and user.rank < RANKS.mod and media_limit_period is not None: if (datetime.now() - user.joined) < media_limit_period: return rp.Reply(rp.types.ERR_MEDIA_LIMIT) ok = spam_scores.increaseSpamScore(user.id, msg_score) if not ok: return rp.Reply(rp.types.ERR_SPAMMY) # enforce signing cooldown if signed and sign_interval.total_seconds() > 1: last_used = sign_last_used.get(user.id, None) if last_used and (datetime.now() - last_used) < sign_interval: return rp.Reply(rp.types.ERR_SPAMMY_SIGN) sign_last_used[user.id] = datetime.now() return ch.assignMessageId(CachedMessage(user.id))
def user_auth(data): logger.warning(f'User {data["userId"]} attempting auth') decode_response = dbUser.decode_auth_token(data["authToken"]) ip = request.remote_addr join_room(ip) if data["userId"] == decode_response: logger.warning('AUTHENTICATED :D') user = dbUser.query.filter(dbUser.id == decode_response).first() if user: for chat in user.chats: join_room(chat.room_name) user.last_ip = ip db.session.add(user) db.session.commit() emit('user_connected', { 'message': 'connected', 'chats': [chat.resp_dict(exceptID=decode_response) for chat in user.chats], }, room=ip) else: emit('reject', {'message': 'Please log back in!'}, room=ip) logger.warning('NOT AUTHENTICATED >:(') return False
def add_fake_users(count: int) -> None: """ Adds fake users in DB. """ i = 0 error_count = 0 while (i != count): if (error_count >= 5): raise PossibleInfiniteLoopError( "Too many errors in a row" ) db.session.add( User.create_fake() ) try: db.session.commit() i += 1 error_count = 0 except IntegrityError: # error because of same `telegram_id` error_count += 1 click.echo(f"Done ({count})")
def register_user(login, password): if User.query.filter_by(login=login).first(): raise ValueError("This login is busy") pass_hash = hash_password(login, password) new_user = User(login=login, pass_hash=pass_hash) db.session.add(new_user) db.session.commit() return new_user
def check_auth(request): auth_header = request.headers.get('Authorization') if auth_header: auth_token = auth_header.split(" ")[1] decode_response = User.decode_auth_token(auth_token) if isinstance(decode_response, str): return False else: return decode_response else: return False
def user_join(c_user): try: user = db.getUser(id=c_user.id) except KeyError as e: user = None if user is not None: if user.isBlacklisted(): return rp.Reply(rp.types.ERR_BLACKLISTED, reason=user.blacklistReason, contact=blacklist_contact) elif user.isJoined(): return rp.Reply(rp.types.USER_IN_CHAT) # user rejoins with db.modifyUser(id=user.id) as user: user.setLeft(False) logging.info("%s rejoined chat", user) return rp.Reply(rp.types.CHAT_JOIN) # create new user user = User() user.defaults() user.id = c_user.id updateUserFromEvent(user, c_user) if not any(db.iterateUserIds()): user.rank = RANKS.admin logging.info("%s joined chat", user) db.addUser(user) ret = [rp.Reply(rp.types.CHAT_JOIN)] motd = db.getSystemConfig().motd if motd != "": ret.append(rp.Reply(rp.types.CUSTOM, text=motd)) return ret
def test_add_user(self): # set test user bdate = datetime.strptime("1990-10-10", "%Y-%m-%d") usr = User( patient_f_name='Jon', patient_l_name='Snow', patient_bday=bdate, patient_procedure='surg', ) # pass to database self.db.session.add(usr) self.db.session.commit() self.assertTrue(len(self.db.session.query(User).all()) == 1)
def choose_run_type(cmd_args): """ function to help determine which type of function to use """ if cmd_args.postgresql: # create app and db app, db = create_app(app_type="PROD") # return app and db return app, db else: # create app and db app, db = create_app(app_type="TEST", verify_ask=False) # create tables db.create_all() # load test data curr_f_name = "Jon" curr_l_name = "Snow" curr_procedure = "ileostomy" curr_bday = datetime.strptime("1990-10-10", "%Y-%m-%d") # define test objects usr = User( curr_f_name, curr_l_name, curr_bday, curr_procedure, ) # add user and commit db.session.add(usr) db.session.commit() # read in fixtures path = "resources/application_settings.yaml" with open(path, "r") as f: data = yaml.load(f) # add data to database add_and_commit_fixtures(data, db) # return app and db return app, db
def post(self): # def blacklist_token(auth_token): # blacklisted_token = BlacklistToken(token=auth_token) # try: # db.session.add(blacklisted_token) # db.session.commit() # return { # 'status': 'success', # 'message': 'Successfully logged out' # }, 200 # except Exception as e: # logger.error(e) # return { # 'status': 'fail', # 'message': e # } auth_header = request.headers.get('Authorization') if auth_header: auth_token = auth_header.split(" ")[1] resp = User.decode_auth_token(auth_token) if isinstance(resp, str): return { 'status': 'success', 'message': resp }, 201 # todo changed from 401 else: # return blacklist_token(auth_token) blacklisted_token = BlacklistToken(token=auth_token) try: db.session.add(blacklisted_token) db.session.commit() return { 'status': 'success', 'message': 'Successfully logged out' }, 200 except Exception as e: logger.error(e) return {'status': 'fail', 'message': e} else: # return blacklist_token(auth_token) return { 'status': 'success', 'message': 'Invalid auth provided' }, 201 # todo changed from 401
def create_if_not_exists(self, email, display_image_url, full_name, provider_user_id, is_buy, auth_token): with session_scope() as session: user = (session.query(User).filter_by( provider_user_id=provider_user_id).one_or_none()) if user is None: user = User( email=email, full_name=full_name, display_image_url=display_image_url, provider="linkedin", can_buy=False, can_sell=False, provider_user_id=provider_user_id, auth_token=auth_token, ) session.add(user) session.flush() if is_buy is not None: buy_req = UserRequest(user_id=str(user.id), is_buy=True) session.add(buy_req) if not is_buy: sell_req = UserRequest(user_id=str(user.id), is_buy=False) session.add(sell_req) email_template = "register_buyer" if is_buy else "register_seller" self.email_service.send_email(emails=[email], template=email_template) committee_emails = [ u.email for u in session.query(User).filter_by( is_committee=True).all() ] self.email_service.send_email(emails=committee_emails, template="new_user_review") else: user.email = email user.full_name = full_name user.display_image_url = display_image_url user.auth_token = auth_token session.commit() return user.asdict()
def authenticate(*args, **kwargs): auth_header = request.headers.get('Authorization') if auth_header: auth_token = auth_header.split(" ")[1] decode_response = User.decode_auth_token(auth_token) if isinstance(decode_response, str): return { 'status': 'fail', 'message': f" decode error: {decode_response}" }, 401 else: try: return func(*args, **kwargs) except Exception as e: logger.error(e) return { 'status': 'fail', 'message': f'An error has occurred: {e}' }, 401 else: return {'status': 'fail', 'message': 'Invalid auth provided'}, 401
def post(self): auth_header = request.headers.get('Authorization') if auth_header: auth_token = auth_header.split(" ")[1] resp = User.decode_auth_token(auth_token) if isinstance(resp, str): return {'status': 'fail', 'message': resp}, 401 else: data = request.json logger.info(f"Comment post data[{type(data)}]: {data}") if data is None: return {'status': 'fail', 'message': 'No data passed'}, 400 else: try: post_id = data['postId'] author_id = data['authorId'] comment = data['comment'] post = dbPost.query.filter( dbPost.id == post_id).first() new_comment = dbComment(post_id=post_id, author_id=author_id, body=comment) post.comments.append(new_comment) db.session.add(new_comment) db.session.add(post) db.session.commit() return { 'status': 'success', 'message': 'comment submitted', }, 200 except Exception as e: logger.error(e) return { 'status': 'fail', 'message': 'An error has occurred', }, 401 else: return {'status': 'fail', 'message': 'Invalid auth provided'}, 401
def setUp(self): # initialize app and db objects self.app, self.db = create_app(app_type="TEST", verify_ask=False) self.app = self.app.test_client() # initialize db self.db.create_all() # load test data curr_f_name = "Jon" curr_l_name = "Snow" curr_procedure = "ileostomy" curr_bday = datetime.strptime("1990-10-10", "%Y-%m-%d") # define test objects usr = User( curr_f_name, curr_l_name, curr_bday, curr_procedure, ) qst_1 = Question( q_link_id="Surg1", q_text="Test question 1?", q_type="Bool", ) qst_2 = Question( q_link_id="Surg2", q_text="Test question 2?", q_type="Bool", ) qst_3 = Question( q_link_id="Surg3", q_text="Test question 3?", q_type="Bool", ) indication_order_3 = IndicationQuestionOrder( indication=curr_procedure, next_item=None, question=qst_3, ) indication_order_2 = IndicationQuestionOrder( indication=curr_procedure, next_item=indication_order_3, question=qst_2, ) indication_order_1 = IndicationQuestionOrder( indication=curr_procedure, next_item=indication_order_2, question=qst_1, ) # add to db self.db.session.add_all(( usr, qst_1, qst_2, qst_3, indication_order_1, indication_order_2, indication_order_3, )) self.db.session.commit()
def seed_db(): with session_scope() as session: # add users user_seeds = [ { "email": "*****@*****.**", "provider": "linkedin", "full_name": "Brandon Ng", "display_image_url": None, "can_buy": True, "can_sell": True, "is_committee": True, "provider_user_id": "UiYX0uP7Cf", }, { "email": "*****@*****.**", "provider": "linkedin", "full_name": "Brandon Ng", "display_image_url": None, "can_buy": True, "can_sell": True, "is_committee": True, "provider_user_id": "8tJpx5jWUx", }, ] for user in user_seeds: if session.query(User).filter_by( email=user.get("email")).count() == 0: session.add( User( email=user.get("email"), provider=user.get("provider"), display_image_url=user.get("display_image_url"), full_name=user.get("full_name"), can_buy=user.get("can_buy"), can_sell=user.get("can_sell"), is_committee=user.get("is_committee"), provider_user_id=user.get("provider_user_id"), )) brandon_gmail_id = (session.query(User).filter_by( email="*****@*****.**").first().id) brandon_yahoo_id = (session.query(User).filter_by( email="*****@*****.**").first().id) # create chatrooms if (session.query(ChatRoom).filter_by( seller_id=str(brandon_gmail_id)).count() == 0): session.add( ChatRoom(buyer_id=str(brandon_yahoo_id), seller_id=str(brandon_gmail_id))) if (session.query(ChatRoom).filter_by( seller_id=str(brandon_yahoo_id)).count() == 0): session.add( ChatRoom(buyer_id=str(brandon_gmail_id), seller_id=str(brandon_yahoo_id))) # adds security if session.query(Security).filter_by(name="Grab").count() == 0: session.add(Security(name="Grab")) grab_security_id = session.query(Security).filter_by( name="Grab").first().id # creates round current_round_end_time = datetime.now() if session.query(Round).filter_by( end_time=current_round_end_time).count() == 0: session.add( Round(end_time=current_round_end_time, is_concluded=True)) current_round_id = session.query(Round).first().id # create buy orders if (session.query(BuyOrder).filter_by( user_id=str(brandon_gmail_id)).count() == 0): session.add( BuyOrder( user_id=str(brandon_gmail_id), security_id=str(grab_security_id), number_of_shares=100, price=10, round_id=str(current_round_id), )) if (session.query(BuyOrder).filter_by( user_id=str(brandon_yahoo_id)).count() == 0): session.add( BuyOrder( user_id=str(brandon_yahoo_id), security_id=str(grab_security_id), number_of_shares=200, price=10, round_id=str(current_round_id), )) # create sell orders if (session.query(SellOrder).filter_by( user_id=str(brandon_gmail_id)).count() == 0): session.add( SellOrder( user_id=str(brandon_gmail_id), security_id=str(grab_security_id), number_of_shares=300, price=10, round_id=str(current_round_id), )) if (session.query(SellOrder).filter_by( user_id=str(brandon_yahoo_id)).count() == 0): session.add( SellOrder( user_id=str(brandon_yahoo_id), security_id=str(grab_security_id), number_of_shares=400, price=10, round_id=str(current_round_id), ))
def seed_db(): with session_scope() as session: # add users user_seeds = [ { "email": "*****@*****.**", "provider": "linkedin", "full_name": "Brandon Ng", "display_image_url": None, "can_buy": True, "can_sell": True, "is_committee": True, "provider_user_id": "ynA5G0JDks", }, { "email": "*****@*****.**", "provider": "linkedin", "full_name": "Brandon Ng", "display_image_url": None, "can_buy": True, "can_sell": True, "is_committee": True, "provider_user_id": "8tJpx5jWUx", }, ] for user in user_seeds: if session.query(User).filter_by( email=user.get("email")).count() == 0: session.add( User( email=user.get("email"), provider=user.get("provider"), display_image_url=user.get("display_image_url"), full_name=user.get("full_name"), can_buy=user.get("can_buy"), can_sell=user.get("can_sell"), is_committee=user.get("is_committee"), provider_user_id=user.get("provider_user_id"), )) brandon_gmail_id = (session.query(User).filter_by( email="*****@*****.**").first().id) brandon_yahoo_id = (session.query(User).filter_by( email="*****@*****.**").first().id) # adds security if session.query(Security).filter_by(name="Grab").count() == 0: session.add(Security(name="Grab")) grab_security_id = session.query(Security).filter_by( name="Grab").first().id # creates round current_round_end_time = datetime.now() if session.query(Round).filter_by( end_time=current_round_end_time).count() == 0: session.add( Round(end_time=current_round_end_time, is_concluded=True)) current_round_id = session.query(Round).first().id # create buy orders if (session.query(BuyOrder).filter_by( user_id=str(brandon_gmail_id)).count() == 0): session.add( BuyOrder( user_id=str(brandon_gmail_id), security_id=str(grab_security_id), number_of_shares=100, price=10, round_id=str(current_round_id), )) if (session.query(BuyOrder).filter_by( user_id=str(brandon_yahoo_id)).count() == 0): session.add( BuyOrder( user_id=str(brandon_yahoo_id), security_id=str(grab_security_id), number_of_shares=200, price=10, round_id=str(current_round_id), )) brandon_gmail_buy_order_id = (session.query(BuyOrder).filter_by( user_id=str(brandon_gmail_id)).first().id) brandon_yahoo_buy_order_id = (session.query(BuyOrder).filter_by( user_id=str(brandon_yahoo_id)).first().id) # create sell orders if (session.query(SellOrder).filter_by( user_id=str(brandon_gmail_id)).count() == 0): session.add( SellOrder( user_id=str(brandon_gmail_id), security_id=str(grab_security_id), number_of_shares=300, price=10, round_id=str(current_round_id), )) if (session.query(SellOrder).filter_by( user_id=str(brandon_yahoo_id)).count() == 0): session.add( SellOrder( user_id=str(brandon_yahoo_id), security_id=str(grab_security_id), number_of_shares=400, price=10, round_id=str(current_round_id), )) brandon_gmail_sell_order_id = (session.query(SellOrder).filter_by( user_id=str(brandon_gmail_id)).first().id) brandon_yahoo_sell_order_id = (session.query(SellOrder).filter_by( user_id=str(brandon_yahoo_id)).first().id) if session.query(Match).count() == 0: session.add( Match( buy_order_id=str(brandon_gmail_buy_order_id), sell_order_id=str(brandon_yahoo_sell_order_id), )) session.add( Match( buy_order_id=str(brandon_yahoo_buy_order_id), sell_order_id=str(brandon_gmail_sell_order_id), )) match_A = (session.query(Match).filter_by( sell_order_id=str(brandon_gmail_sell_order_id)).first().id) match_B = (session.query(Match).filter_by( sell_order_id=str(brandon_yahoo_sell_order_id)).first().id) # create chatrooms if session.query(ChatRoom).filter_by( match_id=str(match_A)).count() == 0: chat_room = ChatRoom(match_id=str(match_A)) session.add(chat_room) session.flush() session.add_all([ UserChatRoomAssociation( chat_room_id=str(chat_room.id), user_id=str(brandon_gmail_id), role="BUYER", ), UserChatRoomAssociation( chat_room_id=str(chat_room.id), user_id=str(brandon_yahoo_id), role="SELLER", ), ]) if session.query(ChatRoom).filter_by( match_id=str(match_B)).count() == 0: chat_room = ChatRoom(match_id=str(match_B)) session.add(chat_room) session.flush() session.add_all([ UserChatRoomAssociation( chat_room_id=str(chat_room.id), user_id=str(brandon_yahoo_id), role="BUYER", ), UserChatRoomAssociation( chat_room_id=str(chat_room.id), user_id=str(brandon_gmail_id), role="SELLER", ), ])
def main(configpath, importpath): with open(configpath, "r") as f: config = yaml.load(f) logging.basicConfig(format="[%(asctime)s] %(message)s", datefmt="%Y-%m-%d %H:%M", level=logging.INFO) db = open_db(config) with open(importpath, "r") as f: data = json.load(f) had_ids = set() for j in data["users"]: u = User() u.id = j["id"] u.username = j.get("username", None) u.realname = j.get("realname", "") u.rank = j["rank"] u.joined = safe_time(0) if j.get("left", False) != False: u.left = safe_time(j["left"] // 1000) u.lastActive = u.joined if "banned" in j.keys(): u.cooldownUntil = safe_time(j["banned"] // 1000) if "reason" in j.keys(): u.blacklistReason = j["reason"] u.warnings = j.get("warnings", 0) if u.warnings > 0: u.warnExpiry = safe_time(j["warnUpdated"] // 1000) + timedelta(hours=WARN_EXPIRE_HOURS) u.karma = j.get("karma", 0) u.hideKarma = j.get("hideKarma", False) u.debugEnabled = j.get("debug", False) if u.id in had_ids: logging.warning("%s is duplicate, dropping the second one", u) else: db.addUser(u) had_ids.add(u.id) c = SystemConfig() c.motd = data["system"]["motd"] db.setSystemConfig(c) logging.info("Success.") db.close()
def create_user(id="", **kwargs): with session_scope() as session: user = User(**attributes_for_user(id, **kwargs)) session.add(user) session.commit() return user.asdict()