def delete_session(form): if not assert_keys_in_form_exist(form, ['sessionID']): return msg.error_msg("Please check your request body.") sessions = SessionModel() given_session_id = form['sessionID'] session_founded = sessions.get_session(session_id=given_session_id) if session_founded is None: return msg.error_msg("Failed to find given session") if len(session_founded) == 0: return msg.error_msg("Can't found the session.") if session_founded[0]['end_time'] is not None: return msg.error_msg("This session already canceled.") end_time = datetime.utcnow() res = sessions.end_session(session_id=given_session_id, end_time=end_time) if res is None: return msg.error_msg("Failed to end this session.") return msg.success_msg({ "sessionID": given_session_id, "endTime": str(end_time) })
def add_session(form): if not assert_keys_in_form_exist(form, ['email', 'password']): return msg.error_msg("Please check the inputs.") sessions = SessionModel() users = UserModel() (email, password) = (form['email'], form['password']) users_founded = users.get_user(email=email, password=encrypt(password), enable=True) if users_founded == None: return msg.error_msg("Failed to validate user information.") if len(users_founded) == 0: return msg.error_msg("Invalid email address or password.") uid = users_founded[0]['user_id'] new_session_id = sessions.create_session_id() start_time = datetime.utcnow() res = sessions.start_session(new_session_id, uid, start_time) if res == None: return msg.error_msg("Failed to start a new session.") return msg.success_msg({ "sessionID": new_session_id, "uid": uid, "startTime": str(start_time), "userName": users_founded[0]['name'] })
def authenticate_api_key(key, secret): """Authenticate an API key""" s = Session() user = s.query(User).filter_by(api_key=key, api_secret=secret).first() s.close() return user
def get_user_info(form): users = UserModel() sessions = SessionModel() if not assert_keys_in_form_exist(form, ['sessionID']): return msg.error_msg("Invalid Session ID.") session_id = form['sessionID'] session = sessions.get_session(session_id) if len(session) == 0: return msg.error_msg("Unable to find the session.") (sessionid, uid, start_time, end_time) = session[0].values() user = users.get_user(uid=uid) if len(user) == 0: return msg.error_msg("Unable to find the user") (uid, name, email, phone, password, major, degree, enable) = user[0].values() return msg.success_msg({ "uid": uid, "name": name, "email": email, "phone": phone, "major": major, "degree": degree })
def setUp(self): from db.session import Session, DBState from db.models import User, Item, DiscuzMember, DiscuzMemberCount from db.base import Model Model.metadata.drop_all(DBState.engine) Model.metadata.create_all(DBState.engine) s = Session() [ s.add(i) for i in [ User(id=1, username='******', jiecao=100000, ppoint=1000, title='', email='*****@*****.**'), User(id=2, username='******', jiecao=100000, ppoint=1000, title='', email='*****@*****.**'), DiscuzMember(uid=1, username='******'), DiscuzMember(uid=2, username='******'), DiscuzMemberCount(uid=1, jiecao=100000), DiscuzMemberCount(uid=2, jiecao=100000), Item(id=1, owner_id=1, sku='foo', status='backpack'), Item(id=2, owner_id=2, sku='bar', status='backpack'), ] if not options.freeplay or 'DiscuzMember' not in i.__class__.__name__ ] s.commit()
def search(grocery_name): if request.method == 'GET': session = Session() result = session.query(Grocery).filter_by(name=grocery_name).first() if result is None: return ('Grocery not found.', 404) else: return result.__json__()
def connect(dsn): """ Create engine and setup session """ engine = create_engine(dsn) Session.configure(bind=engine) return engine
def grocery_list(grocery_list_id): if request.method == 'GET': session = Session() result = session.query(GroceryList).filter_by(grocery_list_id=grocery_list_id).first() if result is None: return ('Grocery list not found.', 404) else: return result.__json__()
def create(cls, username, password): session = Session() session.execute( "INSERT INTO user(username, password) VALUES ('{username}', '{password}')".format( username=username, password=password ) ) session.commit()
def user(self): """Load user on demand""" if not self.user_id: return None db = DbSession() user = db.Query(User).filter_by(self.user_id) db.close() return user
def update_user(form): users = UserModel() sessions = SessionModel() if not assert_keys_in_form_exist(form, [ 'sessionID', 'name', 'email', 'phone', 'newPassword', 'major', 'degree' ]): return msg.error_msg("Please check your requests.") name = form['name'] session_id = form['sessionID'] email = form['email'] phone = form['phone'] new_password = form['newPassword'] major = form['major'] degree = form['degree'] if new_password.strip() == "": return msg.error_msg("Password cannot be empty.") if len(name) > 255: return msg.error_msg("Username cannot exceed 255 characters.") if len(new_password) > 255: return msg.error_msg("Password cannot exceed 255 characters.") # Get User according to sessionID session = sessions.get_session(session_id) if len(session) == 0: return msg.error_msg("Unable to find the session.") (sessionid, uid, start_time, end_time) = session[0].values() if end_time is not None: return msg.error_msg("This session already canceled.") args = { "Name": name, "Email": email, "Phone": phone, "Password": encrypt(new_password), "Major": major, "Degree": degree, "UID": uid } ret = users.update_user(args) if ret is None: return msg.error_msg("Failed to update user profile.") return msg.success_msg({})
async def decrement_actor_vote(actor_id: int): try: Session.query(Actor).filter(Actor.actor_id == actor_id).update( {Actor.votes: Actor.votes - 1}) Session.commit() content = {"Success": "Actor votes decreased."} status_code = 200 except: content = {"Not Found": "Actor Not Found."} status_code = 404 return JSONResponse(status_code=status_code, content=content, headers=headers)
def authenticate_auth_token(token): """Authenticate a jwt auth token""" try: payload = jwt.decode(token, TOKEN_SECRET_KEY) except: return None user_id = payload["sub"] s = Session() user = s.query(User).filter_by(id=user_id).first() s.close() return user
def groceries(): if request.method == 'POST': #makes new grocery grocery = Grocery.from_json(request.json) session = Session() session.add(grocery) session.commit() return grocery.__json__() elif request.method == 'GET': #grabs all groceries from SQL database session = Session() result = session.query(Grocery).order_by(Grocery.grocery_id).all() return {'groceries': [grocery.__json__() for grocery in result]}
def ListCustomers(self, request, context): """ List all customers :param request: A ListCustomersRequest :param context: the grpc context """ db = Session() customers = db.query(Customer).all() return customers_pb2.ListCustomersResponse( customers=[ c.to_message(customers_pb2.Customer) for c in customers ], status=status_pb2.Status(code=200))
async def step(self, obj): try: nowms = int(time() * 1000) self.log(f'Step ms {nowms}') state = self.inner_step(obj, nowms) if state != DEVSTATE_INVALIDSTEP: if not self.session: self.session = Session(device=self.deviceid, user=self.userid, settings=self.conf, datestart=nowms) if (await self.session.to_db(self.db, True)): self.dispatch("on_session", self.session) elif self.main_session_id < 0: self.main_session_id = -self.main_session_id self.session.mainid = self.main_session_id await self.session.to_db(self.db, True) self.nUpdates = self.nUpdates + 1 try: commit = nowms - self.last_commit > 30000 obj.session = self.session.rowid await obj.to_db(self.db, commit) if commit: self.last_commit = nowms except Exception: self.error(f'Commit error: {traceback.format_exc()}') obj.s('updates', self.nUpdates) return state except Exception: self.error(f'Step error: {traceback.format_exc()}') return DEVSTATE_INVALIDSTEP
def reduce_count_of_stock_part(part_id: int, reduction: int) -> None: """Increase count of a part in stock.""" # TODO: prevent reduction below 0. session: Session = Session() part = session.query(StockPart).filter(StockPart.id_ == part_id).one() part.count -= reduction session.commit()
async def get_actors(): try: actors = [actor.to_json() for actor in Session.query(Actor).all()] content = {"actors": actors} return JSONResponse(content=content, headers=headers) except Exception as e: content = {"Server error": "something went wrong!"} return JSONResponse(status_code=500, content=content, headers=headers)
def setUp(self): from db.session import Session, DBState from db.models import User, Item, DiscuzMember, DiscuzMemberCount from db.base import Model Model.metadata.drop_all(DBState.engine) Model.metadata.create_all(DBState.engine) s = Session() [s.add(i) for i in [ User(id=1, username='******', jiecao=100000, ppoint=1000, title='', email='*****@*****.**'), User(id=2, username='******', jiecao=100000, ppoint=1000, title='', email='*****@*****.**'), DiscuzMember(uid=1, username='******'), DiscuzMember(uid=2, username='******'), DiscuzMemberCount(uid=1, jiecao=100000), DiscuzMemberCount(uid=2, jiecao=100000), Item(id=1, owner_id=1, sku='foo', status='backpack'), Item(id=2, owner_id=2, sku='bar', status='backpack'), ] if not options.freeplay or 'DiscuzMember' not in i.__class__.__name__] s.commit()
def create_new_stock_part(name: str, count: int) -> None: """Create new part in stock.""" session: Session = Session() new_part: StockPart = StockPart( part=Part(name=name), count=count, ) session.add(new_part) session.commit()
def grocery_list_item(grocery_list_item_id): if request.method == 'GET': session = Session() result = session.query(GroceryListItem).filter_by( grocery_list_item_id=grocery_list_item_id).first() if result is None: return ('Grocery list item not found.', 404) else: return result.__json__() elif request.method == 'DELETE': session = Session() grocery_list_item = session.query(GroceryListItem).filter_by( grocery_list_item_id=grocery_list_item_id).first() if grocery_list_item is None: return ('Grocery list item not found.', 404) else: session.delete(grocery_list_item) session.commit() return grocery_list_item.__json__()
def user_lists(user_id): if request.method == 'GET': #Retrieves all of a user's lists session = Session() result = session.query(GroceryList).filter_by(user_id=user_id).all() response = [] for grocery_list in result: json = grocery_list.__json__() grocery_list_items_preview = ( session.query(GroceryListItem).order_by( GroceryListItem.grocery_list_item_id)[:SAMPLE_IMAGES]) json['grocery_list_items_preview'] = grocery_list_items_preview response.append(json) return {'grocery_lists': response} elif request.method == 'POST': #Creates a new list for the user grocery_list = GroceryList(user_id=user_id, name=request.json['name']) session = Session() session.add(grocery_list) session.commit() return grocery_list.__json__()
async def get_actor_votes(actor_id: int): try: votes = Session.query( Actor.votes).filter(Actor.actor_id == actor_id).scalar() content = {"votes": votes} return JSONResponse(content=content, headers=headers) except: content = {"Not Found": "Actor Not Found."} return JSONResponse(status_code=404, content=content, headers=headers)
async def get_actor(actor_id: int): try: actor = Session.query(Actor).filter( Actor.actor_id == actor_id).scalar() content = {"actor": actor.to_json()} return JSONResponse(content=content, headers=headers) except: content = {"Not Found": "Actor Not Found."} return JSONResponse(status_code=404, content=content, headers=headers)
def delete_user(form): users = UserModel() sessions = SessionModel() if not assert_keys_in_form_exist(form, ['sessionID', 'password']): return msg.error_msg("Please check the inputs.") password = form['password'] session_id = form['sessionID'] # Get User according to sessionID session = sessions.get_session(session_id) if len(session) == 0: return msg.error_msg("Unable to find the session.") (sessionid, uid, start_time, end_time) = session[0].values() if end_time is not None: return msg.error_msg("Expired SessionID") # Verify password if password.strip() == "": return msg.error_msg("Password cannot be empty.") findUser = users.get_user(uid=uid, password=encrypt(password), enable=True) if findUser is None: return msg.error_msg("Failed to find user.") if len(findUser) == 0: return msg.error_msg("Wrong password.") # Delete User ret = users.delete_user(uid) if ret is None: return msg.error_msg("Failed to delete user.") # Revoke all sessions sessions.end_session(uid=uid) return msg.success_msg({"uid": uid, "sessionID": session_id})
def grocery_list_items(): if request.method == 'POST': grocery_list_item = GroceryListItem.from_json(request.json) session = Session() session.add(grocery_list_item) session.commit() return grocery_list_item.__json__()
def users(): if request.method == 'POST': user = User.from_json(request.json) session = Session() session.add(user) session.commit() return user.__json__()
def add_iventory(): """Add parts to DB.""" session = Session() inventory = ( StockPart( part=Part(name='Valve Body 32"'), count=100, ), StockPart( part=Part(name='Valve Body 12"'), count=50, ), StockPart( part=Part(name='Valve Slip 32"'), count=90, ), StockPart( part=Part(name='Valve Slip 12"'), count=50, ), StockPart( part=Part(name='Screw 14 x 2 1/2"'), count=1000, ), ) session.add_all(inventory) session.commit()
def add_session(form): if not assert_keys_in_form_exist(form, ['email', 'password']): return msg.error_msg("Invalid request.") (email, password) = (form['email'], form['password']) users_founded = User.get_user(email=email, password=encrypt(password), enable=True) if users_founded is None: return msg.error_msg("Failed to validate user information.") if len(users_founded) == 0: return msg.error_msg("Invalid email address or password.") uid = users_founded[0]['user_id'] new_session_id = Session.create_session_id() start_time = datetime.utcnow() res = Session.start_session(new_session_id, uid, start_time) if res is None: return msg.error_msg("Failed to start a new session.") return msg.success_msg({"sessionID": new_session_id, "uid": uid, "startTime": str(start_time)})
def create_user(params: dict): """ Create a user """ password_hash = hash_password(params.get("password")) del params["password"] params["password_hash"] = password_hash user = models.User(**params) db = Session() db.add(user) db.commit() db.close() return user
def user_list(user_id, list_id): if request.method == 'GET': #Grabs all items from a user's grocery list session = Session() result = session.query(GroceryListItem).filter_by( grocery_list_id=list_id).order_by( GroceryListItem.grocery_list_item_id).all() if result is None: return ('Grocery not found.', 404) else: return { 'grocery_items': [grocery_list_item.__json__() for grocery_list_item in result] } elif request.method == 'POST': #Adds an item to a user's grocery list grocery_list_item = GroceryListItem( grocery_list_id=list_id, grocery_id=request.json['grocery_id']) session = Session() session.add(grocery_list_item) session.commit() return grocery_list_item.__json__()
def CreateCustomer(self, request, context): """ Create a customer :param request: A CreateCustomerRequest :param context: The grpc context """ # Validate customer errors = validate_customer(request.customer) if errors: return customers_pb2.CreateCustomerResponse( status=status_pb2.Status(code=400, data_errors=errors), ) # Add customer to database db = Session() customer = Customer(request.customer) try: db.add(customer) db.commit() return customers_pb2.CreateCustomerResponse( customer=customer.to_message(customers_pb2.Customer), status=status_pb2.Status(code=200), ) except Exception as e: db.rollback() return customers_pb2.CreateCustomerResponse( status=status_pb2.Status(code=500, runtime_errors=[ exception_to_runtime_error(e) ]), ) finally: db.close()