def populate_admin_table(): for row in admin_codes: new_admin_model = AdminModel(*row) if AdminModel.find_by_code_and_country(new_admin_model.admin_code, new_admin_model.country_code): continue new_admin_model.save_to_db()
def post(cls): # if get_jwt_claims()["type"] != "admin": # return {"message": "Admin authorization required."}, 401 _admin_parser_ = reqparse.RequestParser() _admin_parser_.add_argument("username", type=str, required=True, help=BLANK) _admin_parser_.add_argument("password", type=str, required=True, help=BLANK) _admin_parser_.add_argument("first_name", type=str, required=True, help=BLANK) _admin_parser_.add_argument("last_name", type=str, required=True, help=BLANK) data = _admin_parser_.parse_args() if (data["username"].isspace() or data["password"].isspace() or data["first_name"].isspace() or data["last_name"].isspace()): return {"message": "One of the inputs is empty"}, 400 if len(data["username"]) < 5: return {"message": "Username is too short"}, 400 if AdminModel.find_by_username(data["username"]): return {"message": "This admin already exists"} admin = AdminModel(**data) admin.save_to_db() return {"message": "Admin created successfully."}
def post(self): data = AdminRegister.parser.parse_args() if AdminModel.find_by_adminname(data['adminname']): return {"message": "An admin with that adminname already exists"}, 400 admin = AdminModel(**data) admin.save_to_db() return {"message": "Admin created successfully."}, 201
def post(self): data = AdminRegister.parser.parse_args() if AdminModel.find_by_email(data['email']): return {"message": "User already registered"}, 400 admin = AdminModel(**data) admin.save_to_db() return {"message": "User created successfully"}, 201
def post(self): data = AdminRegister.registerparser.parse_args() if AdminModel.find_by_username(data['username']): return { "message": "An admin with that username already exists" }, 409 admin = AdminModel(**data) try: admin.save_to_db() except: return {"message": "An error occured registering admin"}, 500 return {"message": "Admin created successfully"}, 201
def check_admin_code(cls, admincodein): o_hash = hashlib.new('ripemd160') o_hash.update(admincodein.encode("utf-8")) if safe_str_cmp(AdminModel.get_id(), o_hash.hexdigest()) == True: return True else: return False
def post(cls): _admin_parser = reqparse.RequestParser() _admin_parser.add_argument("username", type=str, required=True, help=BLANK) _admin_parser.add_argument("password", type=str, required=True, help=BLANK) data = _admin_parser.parse_args() admin = AdminModel.find_by_username(data["username"]) if admin and check_password_hash(admin.password, data["password"]): access_token = create_access_token( identity=admin.id, fresh=True, user_claims={"type": "admin"}, expires_delta=timedelta(1), ) refresh_token = create_refresh_token(identity=admin.id, user_claims={"type": "admin"}) return { "access_token": access_token, "refresh_token": refresh_token }, 200 return {"message": INVALID_CREDENTIALS}, 401
def post(self): data = AdminLogin.loginparser.parse_args() admin = AdminModel.find_by_username(data['username'], data['password']) if admin: return {"message": "Login Success", "admin": admin.json()}, 200 return {"message": "Invalid username or password !"}, 401
def get(self, username, password, fcmtoken): admin = AdminModel.find_by_username(username) if admin: if admin.password == password: # return user_email.json() admin.fcmtoken = fcmtoken try: admin.save_to_db() except: return {'data': {"status": False}} ret = { 'data': { 'status': True, 'admin': { 'access_token': create_access_token(identity=admin.id), 'fcmtoken': admin.fcmtoken, 'priviledges': admin.priviledges } } } return make_response(jsonify(ret), 200) return {'status': False}, 200
def get(self, search_term): admins = [ admin.json() for admin in AdminModel.search_by_desc(search_term) ] if admins: return {'admins': admins}, 200 return {'message': "No admins match that search term"}, 404
def get(self, admin_code): admins = [ admin.json() for admin in AdminModel.find_by_code(admin_code) ] if admins: return {'admins': admins}, 200 return {'message': "No admins match that code"}, 404
async def admin_signup(admin: AdminModel = Body(...)): admin_exists = await admin_collection.find_one({"email": admin.email}, {"_id": 0}) if (admin_exists): return "Email already exists" admin.password = hash_helper.encrypt(admin.password) new_admin = await add_admin(jsonable_encoder(admin)) return new_admin
def get(self, admin_code, country_code): admin = AdminModel.find_by_code_and_country(admin_code, country_code) if admin: return admin.json() return { 'message': "No admin entry found for code {} and country {}.".format( admin_code, country_code) }, 404
def post(self): data = request.form admin = AdminModel.find_by_name(data['admin_name']) print(data) if admin and safe_str_cmp(admin.password, quote(data['password'])): return redirect("/admin_page") return {"message": "Invalid Admin!"}, 401
def post(self, name): if AdminModel.find_by_name(name): return {'message': f'User with name <{name}> already exists'} parser = reqparse.RequestParser() parser.add_argument('password', type=str, required=True, help='Password is required') data = parser.parse_args() new_admin = AdminModel(name, data['password']) new_admin.create() return new_admin.json()
def delete(self, admin_code, country_code): entry = AdminModel.find_by_code_and_country(admin_code, country_code) if entry: entry.delete_from_db() return { 'message': "Admin code '{}' for country code '{}' deleted.".format( admin_code, country_code) }, 200 return { 'message': "Admin code '{}' not found for country with code '{}'.".format( admin_code, country_code) }, 404
def put(self, admin_code, country_code): data = Admin.parser.parse_args() entry = AdminModel.find_by_code_and_country(admin_code, country_code) if entry: entry.description = data['description'] else: entry = AdminModel(admin_code, country_code, data['description']) try: entry.save_to_db() except: {'message': 'Something went wrong inserting the admin.'}, 500 return entry.json(), 201
def put(self): data = AdminUpdate.updateparser.parse_args() admin = AdminModel.find_by_username(data['username']) admin.password = data['password'] admin.fname = data['fname'] admin.mname = data['mname'] admin.lname = data['lname'] admin.phone_number = data['phone_number'] admin.date_of_birth = data['date_of_birth'] admin.email = data['email'] try: admin.save_to_db() except: return { "message": "An error occured updating information of admin" }, 500 return {"message": "Admin information updated successfully"}, 201
def post(self, admin_code, country_code): data = Admin.parser.parse_args() if AdminModel.find_by_code_and_country(admin_code, country_code): return { 'message': "A '{}' admin code already exists for country with code '{}'.". format(admin_code, country_code) }, 400 entry = AdminModel(admin_code, country_code, data['description']) try: entry.save_to_db() except: {'message': 'Something went wrong inserting the admin.'}, 500 return entry.json(), 201
def valid_admin(admin): if AdminModel.find_by_code(admin) or admin == "": return True return False
def delete(self): data = AdminDelete.deleteparser.parse_args() admin = AdminModel.find_by_username(data['username']) if admin: admin.delete_from_db() return {'message': 'Admin deleted'}
def identity(payload): user_id = payload['identity'] return AdminModel.find_by_id(user_id)
def get(self, name): admin = AdminModel.find_by_name(name) if admin: return admin.json()
def json(self): admin = AdminModel.find_by_code_and_country(self.admin, self.country_code) if admin: admin = { 'code': admin.admin_code, 'description': admin.description } else: admin = 'None' subdiv = SubdivModel.find_by_code(self.subdiv) if subdiv: subdiv = { 'code': subdiv.subdiv_code, 'description': subdiv.description } else: subdiv = 'None' sex = SexModel.find_by_code(self.sex) if sex: sex = sex.json() else: sex = "Sex code '{}' not found.".format(self.sex) country = CountryModel.find_by_code(self.country_code) if country: country = country.json() else: country = "Country with code '{}' not found.".format( self.country_code) # sort the age data according to the given age format for the population entry age_breakdown_format = AgeFormatModel.find_by_code( self.age_format).json() pops = [ self.pop2, self.pop3, self.pop4, self.pop5, self.pop6, self.pop7, self.pop8, self.pop9, self.pop10, self.pop11, self.pop12, self.pop13, self.pop14, self.pop15, self.pop16, self.pop17, self.pop18, self.pop19, self.pop20, self.pop21, self.pop22, self.pop23, self.pop24, self.pop25, self.pop26 ] age_breakdown = {} count = 0 for pop, age_range in age_breakdown_format.items(): if pop == "age_format_code": continue age_breakdown[age_range] = pops[count] count += 1 empties = [] for age_range, value in age_breakdown.items(): if value == "": empties.append(age_range) for index in empties: del age_breakdown[index] return { 'id': self.id, 'country': country, 'admin': admin, 'subdiv': subdiv, 'year': self.year, 'sex': sex, 'age_format': self.age_format, 'all_ages': self.pop1, 'age_breakdown': age_breakdown, 'live_births': self.live_births }
def post(self): # db.session.begin(subtransactions=True) try: data = MenuOrderResource.parser.parse_args() if data['payment_type'] == "CD": payment = PaymentModel(data['payment_type'], "COD", data['amount'], data['amount_payable'], data['amount_tax'], data['amount_menu'], data['amount_discount'], data['amount_wallet']) try: # payment.save_to_db() db.session.add(payment) db.session.flush() # db.session.commit() except: return { 'data': { "status": False, "message": "Paymnet False" } }, 500 # payment_id = payment.id order_id = MenuOrderModel.getOrderNumber() order = MenuOrderModel(order_id, data['user_id'], payment.id, data['address_id'], data['promo_code'], data['special_note_required'], data['ratings'], 0) try: # order.save_to_db() db.session.add(order) db.session.flush() # db.session.commit() except: return { 'data': { "status": False, "message": "Order Failed" } }, 500 o_id = order.id menu = json.loads(data['menu']) for m in menu: print str(m) # m = json.loads(me) mmodel = MenuOrderItemModel(o_id, m['menu_id'], m['menu_qty'], m['menu_amount'], m['menu_choice']) try: # mmodel.save_to_db() db.session.add(mmodel) db.session.flush() # db.session.commit() except: return { 'data': { "status": False, "message": "Menu Item Save Failed" } }, 500 db.session.commit() push_service = FCMNotification( api_key= "AAAABnCMzP4:APA91bHf4jst14Er5BrZMC9fOVVRGtMUVkPF7VYUI8t3BWbReJJbH_KYui8TIjITnTGZTq8HoKRPztnBsSXAD07m-JA1Tv1Wf6-I4P8gy3coaeMzJpG2K2alBF9iOHJQjbtQhjXuxzFo" ) # Your api-key can be gotten from: https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging firebase = pyrebase.initialize_app(config) dbfirebase = firebase.database() user = UsersModel.find_by_id(int(data['user_id'])) address = UsersAddressModel.find_by_id(int(data['address_id'])) data = { "user_id": data['user_id'], "status": "0", "order": order.json(), "payment": payment.json(), "menu": menu, "user": user.json(), "address": address.json(), "datetime": str(datetime.datetime.now(pytz.timezone('Asia/Calcutta'))) } dbfirebase.child("orders").child(str(order_id)).set(data) admin = AdminModel.find_by_username("admin") print admin.fcmtoken registration_id = admin.fcmtoken message_title = "New Order" message_body = "A new Food order has arrived..!! Confirm the order " push_service.notify_single_device( registration_id=registration_id, message_title=message_title, message_body=message_body) return { 'data': { "status": True, "payment": payment.json(), "order": order.json(), "menu": menu } } # except: # db.session.rollback() finally: db.session.close()
def create_tables(): from models.admin import AdminModel db.create_all() AdminModel().save_to_db()
def get(self): admins = AdminModel.find_all() return [entry.json() for entry in admins], 200
def authenticate(phone_no, password): admin = AdminModel.find_by_phone_no(phone_no) if admin and safe_str_cmp(admin.password, password): return admin
def post(self): # db.session.begin(subtransactions=True) try: data = CafeMenuResorce.parser.parse_args() order_id = CafeMenuOrder.getOrderNumber() print data['menu'] order = CafeMenuOrder(order_id, data['payment'], data['subtotal'], data['tax'], data['total']) try: # order.save_to_db() # print "Try Block" db.session.add(order) db.session.flush() # order.save_to_db() # db.session.commit() except: return { 'data': { "status": False, "message": "Order Failed" } }, 500 o_id = order.id print o_id menu = json.loads(data['menu']) print menu print len(menu) for m in menu: print m print "Order Id" + str(o_id) print "Menu Id" + str(m["menu_id"]) print "Menu Qty" + str(m["menu_qty"]) print "Menu Amount" + str(m["menu_amount"]) print "Choice" + str(m["menu_choice"]) # m = json.loads(me) mmodel = CafeMenuItemsModel(o_id, m['menu_id'], m['menu_qty'], m['menu_amount'], m['menu_choice']) try: # mmodel.save_to_db() #print "Menu Try Block" # mmodel.save_to_db() db.session.add(mmodel) # print "Added" db.session.flush() # print "Flush" # db.session.commit() except: return { 'data': { "status": False, "message": "Menu Item Save Failed" } }, 500 print "Menu Second" db.session.commit() push_service = FCMNotification( api_key= "AAAABnCMzP4:APA91bHf4jst14Er5BrZMC9fOVVRGtMUVkPF7VYUI8t3BWbReJJbH_KYui8TIjITnTGZTq8HoKRPztnBsSXAD07m-JA1Tv1Wf6-I4P8gy3coaeMzJpG2K2alBF9iOHJQjbtQhjXuxzFo" ) # Your api-key can be gotten from: https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging firebase = pyrebase.initialize_app(config) dbfirebase = firebase.database() data = { "order": order.json(), "menu": menu, "datetime": str(datetime.datetime.now(pytz.timezone('Asia/Calcutta'))) } dbfirebase.child("cafeorders").child(str(order_id)).set(data) admin = AdminModel.find_by_username("admin") print admin.fcmtoken registration_id = admin.fcmtoken message_title = "New Order" message_body = "A new Cafe Food order has arrived..!! Confirm the order " push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) return { 'data': { "status": True, "order": order.json(), "menu": menu } } # except: # db.session.rollback() finally: db.session.close()