def delete(self): args = request.args user = None if 'id' in args: user = User.delete(args['id']) else: user = User.delete(str(current_user.id)) if not user: return {"message": "User not found id={}".format(args['id'])}, 404 return user.to_json()
def create(): req_data = request.get_json() try: data = rentableitem_schema.load(req_data) except marshmallow.exceptions.ValidationError as e: return custom_response(e.messages, 401) rentableitem = RentableItemModel(data) user_in_db = UserModel.get_user_by_name(data.get('owner_name')) if not user_in_db: message = { 'error': 'User does not exists exist, please supply another name' } return custom_response(message, 400) if rentableitem.category not in RentableItemModel.categoryTypes: message = { 'error': 'Category does not exists exist, please supply another category' } return custom_response(message, 400) rentableitem.owner_id = user_in_db.id rentableitem.owner = user_in_db rentableitem.owner_name = user_in_db.name rentableitem.rented = False rentableitem.save() ser_rentableitem = rentableitem_schema.dump(rentableitem) return custom_response(ser_rentableitem, 200)
def put(self): args = request.args.to_dict() updates = request.json print(updates) user = None if 'id' in args: user = User.update(args['id'], updates) else: user = User.update(str(current_user.id), updates) if not user: return {"message": "User not found id={}".format(args['id'])}, 404 return json.loads(user.to_json())
def post(self): data = parser.parse_args() current_user = UserModel.find_by_username(data['username']) if not current_user: return create_response({'message': 'User {} doesn\'t exist' .format(data['username'])}, 404) if UserModel.verify_hash(data['password'], current_user.password): access_token = create_access_token(identity=data['username'], expires_delta=False) return create_response({ 'message': 'Logged in as {}'.format(current_user.username), 'access_token': access_token}, 201) else: return create_response({'message': 'Wrong credentials'}, 401)
def get(self): args = request.args.to_dict() print(current_app) if 'username' in args: user = User.find_user_by_username(username=args['username']) if not user: return { "message": "User not found id={}".format(args['id']) }, 404 return json.loads(user.to_json()) else: users = User.read() return json.loads(users.to_json())
def post(self): data = user_parser.parse_args() current_user = UserModel.find_by_username(data['username']) if not current_user: return { 'message': 'User {} doesn\'t exist'.format(data['username']) } if UserModel.verify_hash(data['password'], current_user.password): access_token = create_access_token(identity=data['username']) refresh_token = create_refresh_token(identity=data['username']) return { 'message': 'Logged in as {}'.format(current_user.username), 'access_token': access_token, 'refresh_token': refresh_token } else: return {'message': 'Wrong credentials'}
def post(self): data = self.parser.parse_args() username = data['username'] password = data['password'] # Missing Parameters if username is None or password is None: return { 'message': 'No username or password passed for registration.' }, 400 # Existing User if UserModel.query.filter_by(username=username).first() is not None: return { 'message': 'UserModel has already been created, aborting.' }, 400 user = UserModel(username=username) user.hash_password(password) db.session.add(user) db.session.commit() return {'username': user.username}, 201
def post(self): payload = to_snake_case(request.get_json()) user = UserSchema().load(payload) user = UserModel(**user) try: db.session.add(user) db.session.commit() return 'User Successfully Created!', 201 except Exception as e: db.session.rollback() raise e
def post(self): username = request.form['username'] password = request.form['password'] session = get_db().session user = session.query(UserModel).filter( UserModel.username == username).first() if user is not None: abort(400, message=_('{} already exists!')) session.add(UserModel(username=username, password=password)) session.commit() return 'success', 201
def setUp(self): """ Test Setup """ self.app = create_app("testing") self.client = self.app.test_client user_schema = UserSchema() user_data = { 'last_name': 'olawale', 'first_name': 'shindeiru', 'email': '*****@*****.**', 'password': '******', 'address': 'Missing data for required field.', 'city': 'Eindhoven', 'zip_code': '3123ND', 'age': '21', 'phone_number': '0631566246', } user1 = { 'password': '******', 'email': '*****@*****.**', } data = user_schema.load(user_data) user = UserModel(data) self.daily_schedule = { 'user_id': user.user_id, 'schedule_date': '22-01-2020' } with self.app.app_context(): # create all tables db.create_all() user.save() res = self.client().post( '/api/v1/users/login', headers={'Content-Type': 'application/json'}, data=json.dumps(user1)) json_data = json.loads(res.data) self.token = json_data.get('jwt_token')
def get(self): args = request.args.to_dict() code = get_field("code", args) username = get_field("username", args) pwd = get_field("pwd", args) user = User.find_user_by_username(username) if code != None and pwd != None: code = int(code) print(user.code, code) if not code == user.code: return {'message': 'Code isn\'t correct'}, 401 user.refresh_token() user = User.update(str(user.id), {'password': pwd}) login_user(user) return {'token': user.token}, 200 elif code != None: code = int(code) if code != user.code: return {'message': 'Code isn\'t correct'}, 401 return {'message': 'Code is correct'}, 200 return {'message': 'Some server errors, cheers :)'}, 500
def get(self): args = request.args.to_dict() _id = get_field("id", args) code = int(get_field("code", args)) user = User.find_user_by_id(_id) if not user: return jsonify( {'message': 'Account already confirmed. Please login.'}) if user.confirmed: return jsonify( {'message': 'Account already confirmed. Please login.'}) updates = { 'confirmed': True, 'confirmed_on': datetime.datetime.utcnow() } if code == user.code: User.update(str(user.id), updates) return json.loads(user.to_json()) return jsonify({'message': 'Not valid code'}), 400
def create_user(): ''' Create new user in Database ''' username = request.json['username'].lower() password = request.json['password'] user = UserModel.query.filter_by(username=username).first() if user is None: hashed_password = generate_password_hash(password, method='sha256') new_user = UserModel(public_id=str(uuid.uuid4().hex), username=username, password=hashed_password, admin=False) db.session.add(new_user) db.session.commit() return user_schema.jsonify(new_user) return jsonify({'status': f'{username} is already in database'})
def post(self): args = request.args.to_dict() username = args['username'] user = User.find_user_by_username(username) if not user: return jsonify({'message': 'User not found'}), 400 code = generate_code() user.code = code user.save() html = render_template('reset.html', code=code, name=user.name) subject = "Restore password" message = Message(subject=subject, html=html, recipients=[user.username]) send_email(message) return 200
def post(self): data = request.form.to_dict() argv = request.args.to_dict() parser = reqparse.RequestParser() parser.add_argument('image', type=werkzeug.datastructures.FileStorage, location='files') args = parser.parse_args() file = args['image'] relp = "" if file: filename = werkzeug.secure_filename(file.filename) relp = filename FILES_PATH = files_storage / filename file.save(FILES_PATH.resolve()) try: user = User.create(data, image=relp) if "code" in argv: print("code", argv['code']) iv = Invitation.use_invitation_code(argv['code']) login_user(user) # token = jwt.encode({'username': user.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=2)}, current_app.config['SECRET_KEY'], algorithm="HS256") # confirm_url = Api.url_for(Api(current_app), resource=UserConfirmController, token=token, _external=True) code = user.code html = render_template('email.html', code=code) subject = "Please confirm your email" message = Message(subject=subject, html=html, recipients=[user.username]) send_email(message) user.code = None return json.loads(user.to_json()) except NotUniqueError as e: return {'message': e.args}, 400
def post(self): form = request.form.to_dict() if not 'username' or not 'password' in form: return make_response( "Could not verify", 401, {"WWW-Authenticate": 'Basic realm="Login required!"'}) user = User.find_user_by_username(form['username']) if not user: return make_response( "Could not verify", 401, {"WWW-Authenticate": 'Basic realm="Login required!"'}) # if check_password_hash(user.password, form['password']): # encoded_jwt = jwt.encode({"some": "payload"}, current_app.config['SECRET_KEY'], algorithm="HS256") # print(encoded_jwt) # token = jwt.encode({'_id': user._id}, current_app.config['SECRET_KEY'], algorithm="HS256") login_user(user) return json.loads(user.to_json())
def rent_item(rentableitem_id): req_data = request.get_json() data = rentperiod_schema.load(req_data) start_date = data.get("start_date") end_date = data.get("end_date") name = data.get("user_name") user = UserModel.get_user_by_name(name) if not user: message = { 'error': 'User does not exists exist, please supply another name' } return custom_response(message, 400) rentableitem = RentableItemModel.get_rentableitem_by_id(rentableitem_id) if not rentableitem: return custom_response({'error': 'rentable item not found'}, 404) periods_of_rental_of_current_item = RentPeriodModel.get_all_rent_periods_with_rentableitem_id( rentableitem.id) for period_of_rental in periods_of_rental_of_current_item: if start_date < period_of_rental.end_date and end_date > period_of_rental.start_date: return custom_response( {'error': 'the item is already rented in that period'}, 404) if not (start_date >= rentableitem.available_start_date and end_date <= rentableitem.available_end_date): return custom_response( {'error': 'the owner does not rent the item in that period'}, 404) rent_period = RentPeriodModel(data) rent_period.rentableitem = rentableitem rent_period.rentableitem_id = rentableitem.id rent_period.save() rentableitem.rented = True db.session.commit() return custom_response("rent succes", 200)
def create(): req_data = request.get_json() data = review_schema.load(req_data) review = ReviewItemModel(data) if not (1 <= review.rating <= 5): message = {'error': 'Rating must be between 1 and 5'} return custom_response(message, 400) user_in_db = UserModel.get_user_by_name(data.get('owner_name')) rentableitem_in_db = RentableItemModel.get_rentableitem_by_id( data.get('rentableitem_id')) if not user_in_db: message = { 'error': 'User does not exists exist, please supply another name' } return custom_response(message, 400) if not rentableitem_in_db: message = { 'error': 'Rentable item does not exists exist, please supply another id' } return custom_response(message, 401) review.owner_id = user_in_db.id review.owner = user_in_db review.owner_name = user_in_db.name review.rentableitem = rentableitem_in_db review.rentableitem_id = rentableitem_in_db.id review.save() ser_review = review_schema.dump(review) return custom_response(ser_review, 200)
def post(self): data = user_parser.parse_args() if UserModel.find_by_username(data['username']): return { 'message': 'User {} already exists'.format(data['username']) } new_user = UserModel(username=data['username'], password=UserModel.generate_hash( data['password'])) try: new_user.save_to_db() access_token = create_access_token(identity=data['username']) refresh_token = create_refresh_token(identity=data['username']) return { 'message': 'User {} was created'.format(data['username']), 'access_token': access_token, 'refresh_token': refresh_token } except: return {'message': 'Something went wrong'}, 500
def post(self): data = parser.parse_args() if UserModel.find_by_username(data['username']): return create_response({'message': 'User {} already exists' .format(data['username'])}, 409) new_user = UserModel( username=data['username'], password=UserModel.generate_hash(data['password']) ) try: new_user.save_to_db() access_token = create_access_token(identity=data['username'], expires_delta=False) return create_response({ 'message': 'User {} was created'.format(data['username']), 'access_token': access_token }, 201) except Exception: return create_response({'message': 'Something went wrong'}, 500)
def test_hash(self): password = "******" pass_hash = UserModel.generate_hash(password) self.assertTrue(UserModel.verify_hash(password, pass_hash))
def identity(payload): user_id = payload['identity'] return UserModel.find_by_id(user_id)
def delete(self): return UserModel.delete_all()
def get(self): return UserModel.return_all()
def user_load(user_id): user = UserModel.find_user_by_id(user_id) return user