def put(self, creditorId, debtorId): creditor = UserModel.findById(creditorId) debtor = UserModel.findById(debtorId) if not creditor or not debtor: UserException.responseError(404, 'User not found') result = UserModel.transfer(creditor, debtor) if not result: UserException.responseError(409, 'Creditor do not have enough balance') return result
def post(self): file = request.files['file'] if not file: UserException.responseError(400, 'Bad Request - File was not informed') imageEncoding = FaceRecognition.imageEncoding(file) embeddings = UserModel.findAllEmbedding() id = FaceRecognition.compareImages(imageEncoding, embeddings) if id: user = UserModel.findById(id) return user.json() UserException.responseError(404, 'User not found')
def editPassword(): if 'username' in session and session['userrole'] == "Manager": if request.method == 'POST': edit_password = request.form["password"] password = hashlib.sha256( edit_password.encode('utf-8')).hexdigest() user_id = request.form["id"] object_one = UserModel() object_one.edit_password(password, user_id) return jsonify("password changed") return jsonify("something went wrong") else: return redirect(url_for('login'))
def post(self): data = UserRegister.parser.parse_args() email = data['email'] password = data['password'] user_object = UserModel(email, password) # check if user already exixsts new_user = user_object.check_if_user_exists_by_email(email) if new_user == 0: new_user = user_object.add_user(email, password) return send_success('user created', new_user, status.HTTP_201_CREATED) else: return send_error('user already exists', status.HTTP_409_CONFLICT)
def register_user(self): username = request.get_json()['username'] find_user = UserModel.get_user(self, username) if find_user: return (jsonify('That username already exists!Try again'), 401) user_name = request.get_json()['username'] first_name = request.get_json()['firstname'] last_name = request.get_json()['lastname'] hashpass = bcrypt.hashpw( request.get_json()['password'].encode('utf-8'), bcrypt.gensalt()) user_id = UserModel.register_user(self, first_name, last_name, username, hashpass) if user_id: return (jsonify('User created'), 200) return (jsonify('Try'), 401)
def get(self): result = UserModel.findAll() users = [] for user in result: obj = user.json() users.append(obj) return {'users': users}
def get(self): """Use this endpoint to get all the tasks""" # tasks=TaskModel.fetch_all() user_id = get_jwt_identity() user = UserModel.get_userby_id(user_id) user_tasks = user.tasks return tasks_schema.dump(user_tasks), 200
def delete(self, id): """Delete user by id""" user = UserModel.fetch_all(id) if user: user.delete_from_db() return {"Message": 'User Deleted Successfully'} else: return {"Message": 'The User does not exist'}
def post(self): data = UserResetUsername.parser.parse_args() user = UserModel.find_by_username(data['username']) if user: user.username = data['newusername'] user.save_to_db() return {'message': 'Username reset successful'}, 201 return {'message': "Username reset unsuccessful"}, 401
def post(self): data = UserResetPassword.parser.parse_args() user = UserModel.find_by_username(data['username']) if user: user.password, user.salt = create_password_hash( data['newpassword']) user.save_to_db() return {'message': 'User password reset successful'}, 201 return {'message': "User password reset unsuccessful"}, 401
def post(self): data = user_parser.parse_args() data['password'] = bcrypt.generate_password_hash(data['password'], 10) user = UserModel(**data) db.session.add(user) db.session.commit() return {'message': f'User created succesfuly'}, 201
def post(self, id): user = UserModel.findById(id) if not user: UserException.responseError(404, 'User not found') file = request.files['file'] if not file: UserException.responseError(400, 'Bad Request - File was not informed') user.embedding = FaceRecognition.imageEncoding(file) embeddings = UserModel.findAllEmbedding() userId = FaceRecognition.compareImages(user.embedding, embeddings) if userId: UserException.responseError(409, 'User found - id: ' + str(userId)) try: user.update(id) except: UserException.responseError( 500, 'An error occurred during data update') return user.json(), 201
def decorated_function(*args, **kwargs): identity = get_raw_jwt()['identity'] user_type = UserModel.get_user_type(identity) if user_type in roles: print("ALLOWED!") else: print("OOPS! UNAUTHORIZED ACCESS!") return send_error('Unauthorized', status.HTTP_401_UNAUTHORIZED) return f(*args, **kwargs)
def login(self): username = request.get_json()['username'] find_user = UserModel.get_user(self, username) hashpass = find_user['password'] if find_user: if bcrypt.hashpw(bytes(request.get_json()['password'], 'utf-8'), hashpass) == hashpass: session['username'] = request.get_json()['username'] session['firstname'] = find_user['firstname'] session['lastname'] = find_user['lastname'] return (jsonify('Suscs username/password combination'), 200) return (jsonify('Invalid username/password combination'), 401)
def get_user(cls, current_user): user = users.get_current_user() url = '' url_string = '' if user: url = users.create_logout_url(current_user.request.uri) url_string = 'Logout' myuser_key = ndb.Key('UserModel', user.email()) myuser = myuser_key.get() if myuser == None: myuser = UserModel(id=user.email(), email=user.email()) myuser.put() else: url = users.create_login_url(current_user.request.uri) url_string = 'login' data = { 'url': url, 'url_string': url_string, 'user': user, } return data
def editUser(user_id): if 'username' in session and session['userrole'] == 'Manager': if request.method == 'GET': id = user_id objectone = UserModel() form = objectone.edit_userdetails(id) return render_template("users/edit_user_edtails.html", form=form) if request.method == 'POST': firstname = escape(request.form['FirstName']) lastname = escape(request.form['LastName']) age = escape(request.form['Age']) email = escape(request.form['Email']) phonenumber = escape(request.form['PhoneNumber']) address = escape(request.form['Address']) userroles = escape(request.form['UserRoles']) sql = "UPDATE maindb.users_table SET firstname = %s,lastname = %s,age = %s, email = %s,phonenumber = %s,address = %s,userroles = %s WHERE user_id = %s" values = (firstname, lastname, age, email, phonenumber, address, userroles, user_id) newcursor.execute(sql, values) condb.commit() return redirect(url_for('users')) else: return redirect(url_for('users'))
class User(Resource): user_object = UserModel() @jwt_required @roles_accepted(['viewer', 'admin', 'contributor']) def get(self, id): # handle claims claims = get_jwt_claims() if not claims['is_admin']: return send_error('Admin privileges required', status.HTTP_401_UNAUTHORIZED) user_exists = User.user_object.check_if_user_exists_by_id(id) if not user_exists: return send_error('user does not exist', status.HTTP_404_NOT_FOUND) else: user = User.user_object.find_user_by_id(id) if user: return send_success('success', user, status.HTTP_200_OK) @jwt_required def delete(self, id): user_exists = User.user_object.check_if_user_exists_by_id(id) if not user_exists: return send_error('user does not exist', status.HTTP_400_BAD_REQUEST) is_deleted = User.user_object.delete_user(id) if is_deleted: return send_success('success', None, status.HTTP_200_OK) else: return send_error('something went wrong', status.HTTP_400_BAD_REQUEST) @jwt_required def put(self, id): # check if user already exixsts new_user = User.user_object.check_if_user_exists_by_id(id) if new_user == 0: return send_error('user does not exist', status.HTTP_409_CONFLICT) else: data = json.loads(request.data) new_user = User.user_object.update_user(data, id) return send_success('success', new_user, status.HTTP_200_OK)
def add_claims_to_jwt(identity): # get user type using identity(email) type_of_user = UserModel.get_user_type(identity) jwt_claim = { 'is_admin': False, 'is_contributor': False, 'is_viewer': False } if type_of_user == 'admin': jwt_claim['is_admin'] = True elif type_of_user == 'viewer': jwt_claim['is_viewer'] = True elif type_of_user == 'contributor': jwt_claim['is_contributor'] = True return jwt_claim
def post(self): data = UserUtil.userParser.parse_args() user = UserModel(None, data['name'], data['email'], data['company'], data['balance'], data['order'], data['embedding']) if UserModel.findByEmail(user.email): UserException.responseError(409, 'Email already exist') try: user.save() except: UserException.responseError( 500, 'An error occurred during data update') return user.json(), 201
def put(self, id): if not UserModel.findById(id): UserException.responseError(404, 'User not found') data = UserUtil.userParser.parse_args() user = UserModel(id, data['name'], data['email'], data['company'], data['balance'], data['order'], data['embedding']) result = UserModel.findByEmail(user.email) if result and result['Users_id'] != id: UserException.responseError(409, 'Email already exist') try: user.update(id) except: UserException.responseError( 500, 'An error occurred during data update') return user.json()
def post(self): data = UserLogin.parser.parse_args() user = UserModel.find_by_username(data['username']) if user and check_password(data['password'], user): expires = timedelta(days=20) access_token = create_access_token( identity=user.user_id, fresh=True, expires_delta=expires, ) refresh_token = create_refresh_token(user.user_id, expires_delta=False) return { 'access_token': access_token, 'refresh_token': refresh_token, "user_id": user.user_id }, 200 return {"message": "Invalid Credentials!"}, 401
def post(self): data = UserSignup.parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "A user with that username already exists"}, 200 if UserModel.find_by_email(data['email']): return {"message": "A user with that email already exists"}, 200 if UserModel.find_by_phonenumber(data['phonenumber']): return { "message": "A user with that phonenumber already exists" }, 200 user = UserModel(data['firstname'], data['lastname'], data['email'], data['phonenumber'], data['gender'], data['dateofbirth'][0:10], data['password'], data['username'], data['location']) user.save_to_db() return {"message": "User was created successfully."}, 201
def users(): if 'username' in session and session['userrole'] == 'Manager': if request.args.get('page') != None: current_page = int(request.args.get('page')) else: current_page = 1 # if search is none and empty this condition will execute if request.args.get( "search") == None or not request.args.get('search'): if request.args.get('page') != None: current_page = int(request.args.get('page')) else: current_page = 1 object_one = UserModel() searchnone_emptyvalues = object_one.users_with_pagination( current_page) return render_template( "users/index.html", users_list=searchnone_emptyvalues["users_list"], total_pages=searchnone_emptyvalues["total_pages"], current_page=current_page) elif request.args.get("search") != None: if request.args.get('page') != None: current_page = int(request.args.get('page')) else: current_page = 1 result_search = request.args.get('search') object_one = UserModel() search_withvalues = object_one.users_pageination_withsearh( result_search, current_page) return render_template( "users/index.html", users_list=search_withvalues["users_list"], total_pages=search_withvalues["total_pages"], current_page=current_page, result_search=result_search) else: return redirect(url_for('dashboard'))
def json(self): user = UserModel.find_by_id(self.user_id) rider = RiderModel.find_by_rider_id(self.rider_id) ridername = rider.rider_firstname + ' ' + rider.rider_lastname overitems = OrderItemModel.find_by_orderid(self.order_id) orderitems = [] for order in overitems: item = ItemModel.find_by_id(order.item_id) orderitems.append( dict({ "item_name": item.item_name, "item price": item.unit_price, "quantity": order.item_quantity })) return { "username": user.username, "Ridername": ridername, "destination": self.destination, 'pickup': self.pickup_point, 'ordertime': str(self.ordertime), 'amountpaid': self.amountpaid, "ordererditems": orderitems }
def authenticate(username, password): user = UserModel.find_by_username(username) if user and safe_str_cmp(user.password, password): return user
def identity(payload): user_id = payload['identity'] return UserModel.find_by_id(user_id)
def authenticate(username, password): user = UserModel.find_by_username(username) if user and user.password == password: return user
from models.userModel import UserModel users = [UserModel(1, "user 1", "abc123"), UserModel(2, "user 2", "abc123")] def authenticate(username, password): for user in users: if user.username == username and password == "abc123": return user def indentity(payload): user_id = payload['identity'] for user in users: if user.id == user_id: return user
def get(self): """Use this Endpoint to get all users""" users = UserModel.fetch_all() return users_schema.dump(users), 200
def get(self, id): """Get user by id""" user = UserModel.fetch_all(id) return users_schema.dump(user), 200