def post(self): data = CustomerRegister.parser.parse_args() print('data', data['address']) if UserModel.find_by_username(data['username']): return {'message': 'username already exists'}, 400 if AgentModel.find_by_agent_id(data['agent_id']) is None: return {'message': 'Invalid agent Id'}, 400 user = UserModel(data['username'], data['password'], usertype='customer') user.save_to_db() agent = AgentModel.find_by_agent_id(data['agent_id']) d, m, y = data['dob'].split('-') converted_dob = datetime(int(y), int(m), int(d)) customer = CustomerModel(customer_id=user.id, agent=agent, name=data['name'], dob=converted_dob, email=data['email'], address=data['address'], contact_num=data['contact_num'], alternate_num=data['alternate_num']) print('got it', customer.json()) customer.save_to_db() return {'message': 'customer Registered Successfully'}, 201
def customer_reg(): if request.method == 'POST': try: name = request.form['name'] email = request.form['email'] phone = request.form['phone'] password = request.form['password'] confirmpass = request.form['confirmpass'] if password != confirmpass: flash('Passwords dont match!', 'danger') return redirect(url_for('customer_reg')) elif (CustomerModel.check_email_exist(email)): flash('Email already in use', 'danger') return redirect(url_for('customer_reg')) else: # protect the password by harshing it hashedpass = bcrypt.generate_password_hash(password, 10).decode('utf-8') # add the customer to the database customer = CustomerModel(name=name, email=email, phone_number=phone, password=hashedpass) customer.insert_record() flash( 'Your account has been successfully created.Please Login', 'success') return redirect(url_for('customer_login')) except Exception as e: print(e) return render_template('customerreg.html')
def post(self, related_user_id): data = Customer.parser.parse_args() theCustomer = CustomerModel( data['credit_limit_balance'], EducationType(data['education']), MaritalStatusType(data['marriage']), data['age'], data['repayment_status_month_1'], data['repayment_status_month_2'], data['repayment_status_month_3'], data['repayment_status_month_4'], data['repayment_status_month_5'], data['repayment_status_month_6'], data['bill_amount_month_1'], data['bill_amount_month_2'], data['bill_amount_month_3'], data['bill_amount_month_4'], data['bill_amount_month_5'], data['bill_amount_month_6'], data['payment_amount_month_1'], data['payment_amount_month_2'], data['payment_amount_month_3'], data['payment_amount_month_4'], data['payment_amount_month_5'], data['payment_amount_month_6'], related_user_id, data['customer_result_id']) # OR USE: theCustomer = CustomerModel(related_user_id, **data) # **kwargs is a dictionary (key word args) try: theCustomer.save_to_db() except: return {"message": "An error occurred inserting the item"}, 500 return theCustomer.json(), 201
def doRegister(self, request): """买家注册""" self.response_["type"] = BaseView.RESPONSE_TYPE_JSON customerKeys = ("name", "password", "mobile", "email") customer = {} for key in customerKeys: customer[key] = request.POST.get(key) # 正则验证数据 regex = Regex() if regex.validateUsername(customer["name"]) is False: self.context = { "code": 403, "msg": "用户名须为6-30位字母数字字符组成", "data": {} } elif regex.validatePassword(customer["password"]) is False: self.context = { "codd": 404, "msg": "密码须位8-30位字母数字字符组成", "data": {} } elif regex.validateMobile(customer["mobile"]) is False: self.context = {"codd": 405, "msg": "手机格式验证错误", "data": {}} elif regex.validateEmail(customer["email"]) is False: self.context = {"codd": 406, "msg": "邮箱格式验证错误", "data": {}} else: # 数据库查重 if CustomerModel.objects.filter(name=customer["name"]).exists(): self.context = {"code": 407, "msg": "用户名已存在", "data": {}} elif CustomerModel.objects.filter( mobile=customer["mobile"]).exists(): self.context = {"code": 408, "msg": "手机已存在", "data": {}} elif CustomerModel.objects.filter( email=customer["email"]).exists(): self.context = {"code": 409, "msg": "邮箱已存在", "data": {}} else: # 插入新数据 customer = CustomerModel( name=customer["name"], password=hashlib.sha512( customer["password"].encode("utf-8")).hexdigest(), mobile=customer["mobile"], email=customer["email"]) customer.save() self.context = { "code": 200, "msg": "注册成功", "data": { "id": customer.id } }
def post(cls, _id: str): if CustomerModel.find_by_id(_id): return {"message": ERROR_ID_EXISTS}, 400 data = request.get_json() if CustomerModel.find_by_email(data["email"]): return {"message": ERROR_EMAIL_EXISTS}, 400 customer = customer_schema.load(data) try: customer.save_to_db() except: return {"message": ERROR_SAVING_USER}, 500 return {"message": SUCCESS_SAVING_USER}, 200
def get_customer(id: int): customer = CustomerModel.get_by_id(id) if customer: return customer.json() return jsonify({'message': 'Customer not found'})
def delete(cls, email: str): customer = CustomerModel.find_by_email(email) if customer: customer.delete_from_db() return {"message": gettext("CUSTOMER_DELETED")} return {"message": gettext("CUSTOMER_NOT_FOUND")}, 404
async def edit_customer(response: Response, new_customer: CustomerModel, customer_id: int): app.db_connection.row_factory = aiosqlite.Row query = 'SELECT customerid FROM customers WHERE customerid = ? ;' cursor = await app.db_connection.execute(query, (customer_id, )) customer = await cursor.fetchone() if customer is None: response.status_code = status.HTTP_404_NOT_FOUND return { "detail": { "error": "Sorry, there's no customer with that ID." } } update_customer = new_customer.dict(exclude_unset=True) query = 'UPDATE customers SET ' for field in update_customer.keys(): query += f'{field} = ? ,' query = query[:-1] query += 'WHERE customerid = ? ;' values = list(update_customer.values()) values.append(customer_id) await app.db_connection.execute(query, tuple(values)) await app.db_connection.commit() cursor = await app.db_connection.execute( 'SELECT * FROM customers WHERE customerid = ? ;', (customer_id, )) customer = await cursor.fetchone() return customer
def get(cls): uid = get_jwt_identity() orders = [] if StoreModel.find_by_id(uid): for order in OrderModel.find_all(): if order.status == 'pending': items = fetching_order(order.order_items) message = order.message orders.append({ 'id': order.id, 'status': order.status, 'items': items, 'message': message }) return orders, 200 elif CustomerModel.find_by_id(uid): for order in OrderModel.find_customer_completed_orders( customer_id=uid): items = fetching_order(order.order_items) message = order.message orders.append({ 'id': order.id, 'items': items, 'message': message }) return orders, 200 return 401
def post(self): data = request.form customer = CustomerModel.find_by_id(data['customer_id']) if customer and safe_str_cmp(customer.password, md5(data['password'].encode("utf-8")).hexdigest()): return redirect("/information/" + data['customer_id']) return {"message": "Invalid Credentials!"}, 401
def delete(self): is_user = False try: if g.user: is_user = True except: pass data = CustomerDelete.parser.parse_args() error_validation = validators.delete_validator(**data) if error_validation['error validation']: return error_validation if is_user: user = g.user position = PositionModel.find_by_id(user.position_id) if position.name != 'admin' or not user.verify_password( data['password']): return { 'message': "You are not privileged to delete customer's account!" }, 400 customer = CustomerModel.find_by_username(data['username']) if customer: log = LogModel("remove customer '{}'".format(data['username']), g.user.username, auth.admin) customer.delete_from_db() log.save_to_db() return {'message': "Customer's account deleted."} return { 'message': "Customer '{}' account does not exist.".format( data['username']) } else: customer = g.customer if customer.username != data['username']: return { 'message': 'You can not delete your account because you have typed wrong username!' }, 400 if not customer.verify_password(data['password']): return { 'message': 'You can not delete your account because you have typed wrong password!' }, 400 log = LogModel("remove customer '{}'".format(data['username']), g.customer.username, auth.customer) customer.delete_from_db() log.save_to_db() return {'message': 'Your account is deleted.'}
def get(cls): uid = get_jwt_identity() if CustomerModel.find_by_id(uid): return {"type": "customer"}, 200 store = StoreModel.find_by_id(uid) if store: return {"type": "messenger"}, 200 return {"message": CUSTOMER_NOT_FOUND}, 404
def delete(self, related_user_id): theCustomer = CustomerModel.find_recent_by_related_user_id( related_user_id) if theCustomer: theCustomer.delete_from_db() return {'message': 'theCustomer deleted'}
def get(cls, confirmation_id: str): confirmation = ConfirmationModel.find_by_id(confirmation_id) user = CustomerModel.find_by_id(confirmation.customer_id) if not user: return {"message": CUSTOMER_NOT_FOUND}, 404 confirmation.confirmed = True confirmation.save_to_db() headers = {"Context-Type": "text/html"} return make_response(render_template("confirmed.html"), 200, headers)
def authenticate(username, password): user = UserModel.find_by_username(username) customer = CustomerModel.find_by_username(username) print('authXXX') if user and user.verify_password(password): print('USER-auth') return user elif customer and customer.verify_password(password): print('CUSTOMER-auth') return customer
def update_customer(id: int): request_data = request.get_json() name = request_data['name'] description = request_data['description'] if CustomerModel.get_by_name(name): return {'message': f"customer with name '{name}' already exists"}, 400 customer = CustomerModel.get_by_id(id) customer.name = name customer.description = description try: customer.save() except Exception: return {"message", "Error updating the customer"}, 500 return customer.json()
def delete_customer(id: int): customer = CustomerModel.get_by_id(id) try: customer.delete() except Exception: return {"message", "Error updating the customer"}, 500 return jsonify({'message': 'Customer deleted succesfully'})
def delete(cls, _id: str): customer = CustomerModel.find_by_id(_id) if not customer: return {"message": CUSTOMER_NOT_FOUND}, 404 try: customer.delete_from_db() except: return {"message": ERROR_DELETING_CUSTOMER}, 500 return {"message": SUCCESS_DELETING_CUSTOMER}, 200
def get(self, username): if not Item.is_user(): return {'message': 'You are not privileged to continue!'}, 400 else: guest = UserModel.find_by_username(username) or CustomerModel.find_by_username(username) if not guest: return {'message': "Guest '{}' not found.".format(username)}, 404 if Item.is_admin(): return {'items': [item.json() for item in ItemModel.query.filter_by(reserved_by=guest.username)]} return {'items': [item.short_json() for item in ItemModel.query.filter_by(reserved_by=guest.username)]}
def delete(self, _id): user = CustomerModel.find_by_id(_id) if user: try: user.delete_from_db() except: return {"message": "An error occurred while deleting this user."}, 500 return {'message': 'User deleted.'} return {'message': "The user you're trying to delete doesn't exist."}, 400
def post(self): data = CustomerRegister.parser.parse_args() error_validation = validators.customer_register_validator(**data) if error_validation['error validation']: return error_validation if CustomerModel.find_by_username( data['username']) or UserModel.find_by_username( data['username']): return { "message": "An account with that username already exists" }, 400 customer = CustomerModel( **data) # CustomerModel(data['username'], data['password'] ...) customer.save_to_db() # return {'customer': customer.fake_json()}, 201 # return {'customers': [customer.short_json() for customer in CustomerModel.query.all()]}, 201 return {"message": "Account created successfully."}, 201
def get(self, related_user_id): theCustomer = CustomerModel.find_recent_by_related_user_id( related_user_id) if theCustomer: return theCustomer.json() return { 'message': 'customer with related_user_id \'' + related_user_id + '\' not found' }, 404
def put(self, _id): data = self.parser.parse_args() user = CustomerModel.find_by_id(_id) if user: user.first_name = data["first_name"] # if data["first_name"] else user.first_name user.middle_name = data["middle_name"] user.last_name = data["last_name"] user.date_of_birth = date(*data["date_of_birth"]) user.gender = data["gender"] user.email = data["email"] user.phone_No_1 = data["phone_No_1"] user.phone_No_2 = data["phone_No_2"] user.phone_No_3 = data["phone_No_3"] user.address = data["address"] user.social_status = data["social_status"] user.national_id = data["national_id"] user.has_smartphone = data["has_smartphone"] user.has_computer = data["has_computer"] user.has_internet = data["has_internet"] else: valid_data = {key: val for key, val in data.items() if val is not None} user = CustomerModel(**valid_data) try: user.save_to_db() except: return {"message": "An error occurred while saving to the database."}, 500 return user.json()
def customer_login(): if request.method == 'POST': email = request.form['email'] password = request.form['password'] # check if an email exists if CustomerModel.check_email_exist(email=email): # validate the password if CustomerModel.validate_password(email=email, password=password): # set the customer session session['email'] = email session['uid'] = CustomerModel.get_customer_id(email) # redirect him to the homepage return redirect(url_for('home')) else: flash('Invalid login credential', 'danger') return redirect(url_for('customer_login')) else: flash('Invalid login credential', 'danger') return redirect(url_for('customer_login')) return render_template('custlogin.html')
def identity(payload): _id = payload['identity'] # print(payload) user = UserModel.find_by_id(_id) customer = CustomerModel.find_by_id(_id) if user: print("as user") g.user = user return user else: print("as customer") g.customer = customer return customer
def mutate(root, info, campaign_id, customer_data): campaign = CampaignModel.find_by_id(campaign_id) if not campaign: raise Exception("Campaign not found!") company = campaign.company.fetch() if not company: raise Exception("Company not found!") customer = CustomerModel(**customer_data, source=campaign, company=company) customer.save() return AddCustomer(customer=customer)
def post(self): try: user = g.user except: return {'message': "You are not privileged to continue!"}, 400 data = UserRegister.parser.parse_args() error_validation = validators.user_register_validator(**data) if error_validation['error validation']: return error_validation position = PositionModel.find_by_id(user.position_id) print(position) if position.name != 'admin': return { 'message': "You are not privileged to create user's account!" }, 400 if UserModel.find_by_username(data['username']): return { "message": "A user with that username already exists." }, 400 if CustomerModel.find_by_username(data['username']): return { "message": "A customer with that username already exists." }, 400 user = UserModel(**data) # user.save_to_db() log = LogModel("add user '{}'".format(data['username']), g.user.username, auth.admin) try: user.save_to_db() log.save_to_db() except: return { 'message': 'An error occurred inserting the user.' }, 500 # Internal Server Error # return {'user': user.fake_json()}, 201 # return {'users': [user.short_json() for user in UserModel.query.all()]}, 201 return {"message": "User created successfully."}, 201
def put(self): data = Customer.parser.parse_args() customer = CustomerModel.find_by_full_name(data["f_name"], data["l_name"]) if customer: customer.email = data["email"] customer.active = data["active"] customer.created_at = data["created_at"] else: customer = CustomerModel(**data) customer.save_to_db() return customer.json()
def get(self, customer_name): try: if g.customer: return {'message': 'You are not privileged to continue!'}, 400 except: pass # position = PositionModel.find_by_id(g.user.position_id) # if position.name != 'admin': # return {'message': "You are not privileged to check user details!"}, 400 customer = CustomerModel.find_by_username(customer_name) if customer: return customer.json() return { 'message': "Customer '{}' not found.".format(customer_name) }, 404
def put(self, tax_id): data = Customer.parser.parse_args() customer = CustomerModel.find_by_taxid(tax_id) if customer: customer.debtor_value = data['debtor_value'] customer.customer_defaulter = data['customer_defaulter'] else: customer = CustomerModel(tax_id, data['debtor_value']) customer.save_to_db() return customer.json()