def find_user(self, dbo): """test find user, CRUD method :param dbObject dbo: dbo """ self.reset(dbo) # 1. find user from db with orm.db_session: temp_user, _ = User.find_user_by_id(self.user.id) # 2. test value self.assert_value(temp_user) temp_user, err = User.find_user_by_id(-1) # 3. assert on error self.assertEqual(err, "User Not Found !") self.assertEqual(temp_user, None) # 4. find_all user from db temp_users = User.find_all_users() # 5. test value self.assertEqual(len(temp_users), 1) self.assert_value(temp_users[0])
def register(session, username, password, fullname, role): try: dbuser = DBUser(username, password, fullname) session.add(dbuser) dbuser.role = session.query(Role).filter(Role.name == role).one() session.commit() response = UserOk.register() except IntegrityError: session.rollback() response = UserError.register_username_taken() except: session.rollback() response = UserError.register_failed() return response
def __run_seeders(self): settings = [ Settings('bot', True), Settings('user_stats', True), Settings('make_joke', True), Settings('essay', True), Settings('random_post', True), Settings('call_admin', True), Settings('donate', True), ] for setting in settings: if not any( self.session.query(Settings).filter( Settings.name == setting.name)): self.add(setting) with open(os.path.join(location, 'posts.txt'), 'r', encoding='utf-8') as f: lines = [int(line.strip()) for line in f] posts = self.session.query(Posts).first() if not posts: self.add(Posts(len(lines), lines)) elif posts.count != len(lines): posts.count = len(lines) posts.items = lines for admin_id in Config.admin_ids: if not self.session.query(User).filter( User.user_id == admin_id).first(): self.add(User(admin_id)) self.session.commit()
def save(self, user_obj: User) -> User: hashed_password = bcrypt.hashpw(user_obj.password.encode('utf-8'), bcrypt.gensalt()) user_obj.password = hashed_password self.db.add(user_obj) self.db.commit() self.db.refresh(user_obj) return user_obj
def process_new_message(self, event): try: user = self.db.session.query(User).filter( User.user_id == event.user_id).first() if not user: user = self.db.add(User(event.user_id)) else: self.db.update(user, {User.last_interaction_date: datetime.today()}) if event.user_id in Config.admin_ids or \ Settings.bot and not user.banned: handlers = self.handlers if user.path == Buttons.get_key(Buttons.call_admin): handlers = self.special_handlers coincidence = next( (rule for rule in handlers if rule['condition'](self.vk, event, user) and ( 'main' in rule or 'admin' in rule and event.user_id in Config.admin_ids))) if coincidence: if 'admin' in coincidence and event.user_id in Config.admin_ids: coincidence['admin'](self.vk, event, user) elif 'main' in coincidence: coincidence['main'](self.vk, event, user) except StopIteration: return None except Exception as e: self.write_error_message(event.user_id) self.write_log(self.vk, event.message_id, e) self.db.session.rollback()
async def get_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> "User": credentials_exception = HTTPException( status_code=401, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) if not token: raise credentials_exception try: payload = jwt.decode(token, config["API_SECRET_KEY"], algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) except JWTError: raise credentials_exception user = User.get(db=db, value=token_data.username, key="email") if user is None: raise credentials_exception return user
async def register(user: User = me): """ User register endpoint Params: User data-> * username : str * email : EmailStr * password : str """ if not check_username(user) and not check_email(user): with db_session: db.DB_User( username=user.username, email=user.email, hashed_password=get_password_hash(user.password), email_confirmed=False, icon=user.icon, creation_date=datetime.today().strftime("%Y-%m-%d"), ) commit() if user in test_users: with db_session: user = db.DB_User.get(email=user.email) user.set(email_confirmed=True) commit() return {"Listo mostroo"} else: v = Validation() v.send_mail(user.email) # background_t.add_task(validator.send_mail, user.email) return { "message": user.username + ", a verification email has" + " been sent to " + user.email } else: msg = "" if check_username(user): msg += "Username already registered " raise HTTPException(status_code=409, detail="Username already registered ") elif check_email(user): msg += "Email already registered" raise HTTPException(status_code=409, detail="Email already registered") return {msg}
def seed_project(): _project = Project.create_project("sample_project", "SP", 2020, 2021) # get user and link it to project _user = User.find_all_users()[0] _project.users += _user return _project
def blueprint_logged_in(blueprint, token) -> bool: # TODO: make this method reusable for every SSO if not token: return False user_info: UserRecord = get_user_info(blueprint) user_email: str = user_info["primary_email"] # Find this OAuth token in the database, or create it query = OAuth.query.filter_by( provider=blueprint.name, provider_user_email=user_email, ) try: oauth = query.one() except NoResultFound: oauth = OAuth( provider=blueprint.name, provider_user_email=user_email, token=token, ) if oauth.user: # If this OAuth token already has an associated local account, # log in that local user account. login_user(oauth.user) else: # This OAuth token doesn't have an associated local account, # If there is an existing user with the same email we can join # their accounts. Otherwise, we need to create a new account. We # can log in that account as well, while we're at it. user_query = User.query.filter_by(primary_email=user_email) try: user = user_query.one() except NoResultFound: user = User( primary_email=user_info["primary_email"], name=user_info["name"], ) db.session.add(user) db.session.commit() for question_type in QUESTION_TYPES: stat_table = StatsTable(player_id=user.id, question_type=question_type) db.session.add(stat_table) oauth.user = user db.session.add(oauth) db.session.commit() # Log in the new local user account login_user(user) return False
def get(cls, message_id: int): c = conn.cursor() c.execute('SELECT * from Messages WHERE id = ?', (message_id, )) existing_message = c.fetchone() c.close() if existing_message: _, user_id, content, date_time = existing_message user = User.get(user_id) return cls(message_id, user, content, date_time) return None
def remove_user(self, dbo): """Test remove_user, CRUD method :param dbObject dbo: dbo """ self.reset(dbo) with orm.db_session: # 1. find user from db temp_user, _ = User.find_user_by_id(self.user.id) # 2. remove User.remove_user_by_id(temp_user.id) # 3. re-get temp_user, err = User.find_user_by_id(self.user.id) # 4. assert self.assertEqual(temp_user, None) self.assertEqual("User Not Found !", err)
def start(message): user_id = message.from_user.id print(user_id) response = queries.check_user_in_db(db, user_id) if response is None: db.add_model(User(tg_id=user_id)) db.commit_session() bot.send_message(message.from_user.id, 'Добро пожаловать, вы успешно зарегестрировались', reply_markup=main_menu())
def registration(): try: req = request.get_json() user: User = User(req["email"], req["password"]) db_session.add(user) db_session.commit() return make_response(jsonify({"message": "ok"}), 201) except sqlalchemy.exc.SQLAlchemyError as e: return make_response(jsonify({"errors": e.args}), 422) except Exception as e: return make_response(jsonify({"errors": e}), 500)
def register(bot, update: Update): user = update.effective_user message = update.effective_message try: auth.get_access_token(message.text) # Replace XXXXXXX with verification code from URL except tweepy.TweepError: print('Verification Error') access_token = auth.access_token access_token_secret = auth.access_token_secret auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) try: twitter_user = api.me() except tweepy.TweepError: return REGISTER new_user = User(user.id, user.username, twitter_user.id, twitter_user.screen_name, access_token, access_token_secret) User.add_new_user(new_user) update.message.reply_text(ReadyText.success_insert_user, reply_markup=ReplyKeyboardMarkup(keyboard=main_keyboard)) return ACTION
def update_user(self, dbo): """Test update_user, CRUD method :param dbObject dbo: dbo """ self.reset(dbo) with orm.db_session: # 1. find update_user from db temp_user, _ = User.find_user_by_id(self.user.id) temp_user.name = "updated_name" temp_user.email = "*****@*****.**" temp_user.year_start = 2021 temp_user.year_end = 2022 temp_user, _ = User.update_user_by_id(temp_user.id, temp_user) # 2. assert self.assertEqual("updated_name", temp_user.name) self.assertEqual("*****@*****.**", temp_user.email) self.assertEqual(2021, temp_user.year_start) self.assertEqual(2022, temp_user.year_end)
async def on_connect(self, client, path): greetings_msg = json.dumps({ 'type': 'connection_open', }) await client.send(greetings_msg) user_name, user_color = await get_info(client) user = User.get_by_name(user_name) if not user: user = User.create(user_name, user_color) if user.color != user_color: user.update(color=user_color) information_msg = json.dumps({ 'type': 'user_information', 'info': user.serialize() }) await client.send(information_msg) client_object = (client, user) await self.register_client(client_object) try: async for message in client: message_json = load_json_safe(message) message_type = message_json.get('type', '') if message_type == 'send_message': text_message = message_json.get('message', '<mensagem vazia>') await self.message_handler(text_message, user) elif message_type == 'change_color': color_code = message_json.get('user_color', '#FFF') user.update(color=color_code) elif message_type == 'change_name': new_name = message_json.get('user_name', user.name) user.update(name=new_name) elif message_type == 'close_connection': break finally: await self.unregister_client(client_object)
def start(bot, update: Update, user_data): logger.info("start") bale_id = str(update.effective_user.id) user = User.get_user_by_user_id(bale_id) if user: reply_keyboard = [[ButtonText.send_tweet, ButtonText.get_home_time_line, ButtonText.search]] update.message.reply_text(ReadyText.start_conversation.format(user.screen_name), reply_markup=ReplyKeyboardMarkup(keyboard=reply_keyboard)) user_data['user'] = user return ACTION else: reply_keyboard = [[ButtonText.register]] update.message.reply_text(ReadyText.need_registration, reply_markup=ReplyKeyboardMarkup(keyboard=reply_keyboard)) logger.info("need_registration") return REGISTER
def post(self): parser = reqparse.RequestParser() parser.add_argument('name', type=str, help='asdasd', required=True) parser.add_argument('age', type=int, help='asdasd', required=True) args = parser.parse_args() name = args.get('name') age = args.get('age') # u1 = User.create(name=name, age=age) # u2 = User.create(name=name, age=age) u1 = User.find("73eede85-79a4-45a2-908d-40449b893ba5") print("USER", u1) return {"status": [u1.id, u1.name]}
def SignUp(self, request, context): user_obj = User( email=request.email, username=request.username, name=request.name, password=request.password ) resp = user_service.signup(user_obj=user_obj) response = user_pb2.LoginResponse( token="dummy_token", user=user_pb2.User( id=resp["user"].id, name=resp["user"].name, email=resp["user"].email, username=resp["user"].username ) ) return response
def registerUser(): data = request.get_json() if request.method == 'POST': if len(data) is 0: return 'Request was empty!' username = data.get('username') if not isProperUsername(username): return 'Invalid username!' password = data.get('password') if not isProperPassword(password): return 'Invalid password!' password = generate_password_hash(password) email = data.get('email') if not isProperEmail(email): return 'Invalid email!' createdDate = datetime.now() lastUpdated = datetime.now() if User.query.filter_by(username=username).first() is not None: return 'A user already exists with the username!' elif User.query.filter_by(email=email).first() is not None: return 'A user already exists with the email!' else: user = User(username=username, password=password, email=email, createdDate=createdDate, lastUpdated=lastUpdated) db.session.add(user) db.session.commit() userid = User.query.filter_by(username=username).first().userid profile = Profile(createdDate=createdDate, lastUpdated=lastUpdated, userid=userid) db.session.add(profile) db.session.commit() return 'Registration success!' return 'Registration failed!' else: return 'Unsupported HTTP method!'
def fill_datas(self): """Fill tables with test data""" self.user = User.create_user("test", "*****@*****.**", 2020, 2021)
#!/usr/bin/env python # --*--coding:utf-8 --*-- from db.models.user import User from db.models.base import session user = User(username="******", password='******') session.add(user) session.commit() session.close()
async def karma_info(message: types.Message, _): result = "Топ по карме:\n" users = User.find().sort("karma", -1) async for user in users: result += f"{user.nickname} - {user.karma}\n" await message.answer(result)
import uuid config_path = "/home/diksha/Interview/Work/MyCart-App/config/configuration.json" if __name__ == "__main__": config = get_config(config_path) db_conn = connect_to_db(config["db"], config["host"], config["user"], config["password"]) # User Operations # CREATE user = User(db_conn, first_name="Saavi", last_name='Sirsat', email='saavisirsatgmail.com', contact_number=1234567890, address='Pune', postal_code='411031', password='******', user_type=1) user.create_user() user = User(db_conn, first_name="Priya", last_name='Sirsat', email='saavisirsatgmail.com', contact_number=1234567890, address='Pune', postal_code='411031', password='******', user_type=1)
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from db.db_worker import DBSession from db.models.base import BaseModel from db.models.category import Category from db.models.item import Item from db.models.user import User engine = create_engine('sqlite:///test.db', echo=True) BaseModel.create_base(engine) db = DBSession(sessionmaker(bind=engine)()) user1 = User(tg_id=1) db.add_model(user1) category1 = Category(category_name='Hoodie') db.add_model(category1) item1 = Item(name='item1', clothe_size='XS', description='Крутой товар', category=category1, picture=None) item2 = Item(name='item2', clothe_size='S', description='Крутой товар но размером больше', category=category1, picture=None) db.add_model(item1) db.add_model(item2) user1.items.append(item1)
def seed_user(): return User.create_user("test", "*****@*****.**", 2020, 2021)
from db.utils.check import check_email2, check_username, check_email, check_validation_code from db.utils.dumps import get_users from fastapi import APIRouter, HTTPException, status, Depends from db.models.user import User, Token, check_email_status from pony.orm import db_session from api.utils.auth import ACCESS_TOKEN_EXPIRE_MINUTES, get_password_hash, valid_credentials, get_logged_users from datetime import datetime from api.utils.auth import create_access_token from datetime import timedelta from db.utils.check import IncorrectPassword, UsernameNotFound from fastapi.security import OAuth2PasswordRequestForm router = APIRouter() #!Debug me = User(username='******', password='******', email='*****@*****.**') player0 = User(username='******', password='******', email='*****@*****.**') player1 = User(username='******', password='******', email='*****@*****.**') player2 = User(username='******', password='******', email='*****@*****.**') player3 = User(username='******', password='******', email='*****@*****.**') player4 = User(username='******', password='******', email='*****@*****.**')