def get(user_id): user = User.objects.get_or_raise(id=user_id) schema = UserSchema() result = schema.dump(user) return jsonify(result.data), 200
def create(): many = False if isinstance(request.json["data"], type([])): many = True schema = UserSchema(many=many) result = schema.load(request.json["data"]) if not result.errors: if many: for user in result.data: user.save() else: result.data.save() return jsonify(schema.dump(result.data).data), 201 else: current_app.logger.error("Error creating new User", extra={"errors": result.errors}) raise APIException("Error processing your request", status_code=400, payload=result.errors)
def test_create_user_bulk(client): user1 = StubFactory.create_user({"cpf": "71188941097"}, save_db=False) user2 = StubFactory.create_user( { "first_name": "Jane", "last_name": "Dunninghan", "cpf": "37600750880" }, save_db=False, ) schema = UserSchema(many=True) payload = {"data": schema.dump([user1, user2]).data} resp = client.post( url_for("user.create"), data=json.dumps(payload), content_type="application/json", ) user1 = resp.json[0] user2 = resp.json[1] User.objects.get(**user1) User.objects.get(**user2) assert resp.status_code == 201
def test_can_serialize_user(app): user = StubFactory.create_user(save_db=True) schema = UserSchema() result = schema.dump(user) assert result.errors == {} assert json.dumps(result.data)
def post(self): user = UserSchema().load(request.get_json(), session=db.session).data user_exists = db.session.query(db.exists().where(User.email == user.email)).scalar() if user_exists: return jsonify({"error": "User already exists"}), 409 user.password = bcrypt.generate_password_hash(user.password) db.session.add(user) db.session.commit() return UserSchema().jsonify(user), 201
def put(self, pk): user = User.query.get_or_404(pk) # Check if updated email already exists check_user = User.query.filter(User.email == request.get_json().get('email')).first() if check_user and check_user.id != user.id: return jsonify({'error': 'User email already exists'}), 409 user = UserSchema(only=('email', 'first_name', 'last_name', 'password')).load(request.get_json(), instance=user,partial=('email', 'first_name', 'last_name', 'password'), session=db.session).data if(user.password): user.password = bcrypt.generate_password_hash(user.password) db.session.commit() return UserSchema().jsonify(user), 200
def test_create_user(client): user = StubFactory.create_user({"cpf": "37600750880"}, save_db=False) schema = UserSchema() payload = {"data": schema.dump(user).data} resp = client.post( url_for("user.create"), data=json.dumps(payload), content_type="application/json", ) User.objects.get(**resp.json) assert resp.status_code == 201
def update(user_id): user = User.objects.get_or_raise(id=user_id) schema = UserSchema() errors = schema.validate(request.json["data"], partial=request.method == "PATCH") if errors: raise APIException("Error processing your request", status_code=400, payload=errors) user.update(**request.json["data"]) user.save() return jsonify({}), 204
class MeView(FlaskView): users_schema = UserSchema() @jwt_required def index(self): user_id = get_jwt_identity() user = User.query.get_or_404(user_id) return self.users_schema.jsonify(user), 200 @jwt_required def put(self): user_id = get_jwt_identity() user = User.query.get_or_404(user_id) # Check if updated email already exists check_user = User.query.filter(User.email == request.get_json().get('email')).first() if check_user and check_user.id != user.id: return jsonify({'error': 'User email already exists'}), 409 user = UserSchema(only=('email', 'first_name', 'last_name', 'password')).load(request.get_json(), instance=user,partial=('email', 'first_name', 'last_name', 'password'), session=db.session).data password = request.get_json().get('password') if(password): user.password = bcrypt.generate_password_hash(password) db.session.commit() return UserSchema().jsonify(user), 200
def wrapper(*args, **kwargs): json_data = request.get_json() if not json_data: return error(status=400, detail='Bad request') user, errors = UserSchema().load(json_data) if errors: return error(status=400, detail=_errors_to_string(errors)) kwargs['user'] = user return func(*args, **kwargs)
def get_users(): """-""" logging.info('[ROUTER]: Getting users') # Getting users = UserService.get_users() # Serialize users = UserSchema(many=True).dump(users).data response = UserResponder(users).serialize return jsonify(data=response), 200
def login_user(): j = request.get_json() u = User.query.filter(User.username == j['username'])\ .filter(User.password_hash == hashlib.sha256(j['password'].encode()).hexdigest()).first() if not u: raise Unauthorized('Not allowed to access this site.') session['user_id'] = u.id return jsonify(UserSchema().dump(u).data)
def list(args): page, per_page = args.pop("page"), args.pop("per_page") paginator = User.objects.filter(**args, active=True).paginate(page=page, per_page=per_page) schema = UserSchema(many=True) result = schema.dump(paginator.items) if not result.errors: payload = {"result": result.data} args = clean_keys(args, remove_text="__iexact") return paginated_response(paginator, "user.list", payload, args) else: current_app.logger.error("Error while serializing User Model", extra={"errors": result.errors}) raise APIException( "Internal server error while processing your requests", status_code=500)
def test_cannot_deserialize_user_required_fields(app): user_data = {"address": {}} schema = UserSchema() result = schema.load(user_data) assert result.errors == { "address": { "city": ["Missing data for required field."], "country": ["Missing data for required field."], "number": ["Missing data for required field."], "public_area_desc": ["Missing data for required field."], "state_province": ["Missing data for required field."], }, "birthdate": ["Missing data for required field."], "cpf": ["Missing data for required field."], "first_name": ["Missing data for required field."], "last_name": ["Missing data for required field."], "telephones": ["Missing data for required field."], }
def test_cannot_deserialize_user_invalid_birthdate(app): user_data = { "first_name": "John", "last_name": "Doe", "cpf": "03709557062", "birthdate": "28/21245", "telephones": ["551622338877", "551633448977"], "address": { "city": "São Carlos", "state_province": "SP", "country": "Brazil", "zip_code": "14801180", "public_area_desc": "Av Lapena", "number": "877", }, } schema = UserSchema() result = schema.load(user_data) assert result.errors == {"birthdate": ["Not a valid date."]}
def test_cannot_deserialize_user_invalid_telephone(app): user_data = { "first_name": "John", "last_name": "Doe", "cpf": "03709557062", "birthdate": "10/10/2010", "telephones": ["^5516223~X~"], "address": { "city": "São Carlos", "state_province": "SP", "country": "Brazil", "zip_code": "14801180", "public_area_desc": "Av Lapena", "number": "877", }, } schema = UserSchema() result = schema.load(user_data) assert result.errors == { "telephones": ["this list field accepts numbers only"] }
class UsersView(FlaskView): users_schema = UserSchema() users_page = UserPageSchema() page_args = PageArgsSchema() @jwt_required def index(self): args = parser.parse(self.page_args, request) users = User.query.paginate(args['page'], args['per_page'], error_out=False) return jsonify(self.users_page.dump(users).data), 200 @jwt_required def get(self, pk): user = User.query.get_or_404(pk) return self.users_schema.jsonify(user), 200 @jwt_required def post(self): user = UserSchema().load(request.get_json(), session=db.session).data user_exists = db.session.query(db.exists().where(User.email == user.email)).scalar() if user_exists: return jsonify({"error": "User already exists"}), 409 user.password = bcrypt.generate_password_hash(user.password) db.session.add(user) db.session.commit() return UserSchema().jsonify(user), 201 @jwt_required def put(self, pk): user = User.query.get_or_404(pk) # Check if updated email already exists check_user = User.query.filter(User.email == request.get_json().get('email')).first() if check_user and check_user.id != user.id: return jsonify({'error': 'User email already exists'}), 409 user = UserSchema(only=('email', 'first_name', 'last_name', 'password')).load(request.get_json(), instance=user,partial=('email', 'first_name', 'last_name', 'password'), session=db.session).data if(user.password): user.password = bcrypt.generate_password_hash(user.password) db.session.commit() return UserSchema().jsonify(user), 200 @jwt_required def delete(self, pk): user = User.query.get_or_404(pk) db.session.delete(user) db.session.commit() return '', 204
def get_me(auth_user): """-""" logging.info('[ROUTER]: Getting me') try: # Getting user = UserService.get_user_by_email(auth_user.get('email')) except UserNotFound as e: logging.error('[ROUTER]: Creating for the first time') user, errors = UserSchema().load({ 'first_name': auth_user.get('name').split(' ')[0], 'last_name': auth_user.get('name').split(' ')[1], 'email': auth_user.get('email') }) user = UserService.create_user(user) except Exception as e: logging.error('[ROUTER]: ' + str(e)) return error(status=500, detail='Generic Error') # Serialize user = UserSchema().dump(user).data response = UserResponder(user).serialize return jsonify(data=response), 200
def create_user(): j = request.get_json() u = User(first_name=j['first_name'], last_name=j['last_name'], username=j['username'], role=j['role']) # Hash password # This is not a secure way at all to do this... u.password_hash = hashlib.sha256(j['password'].encode()).hexdigest() db_session.add(u) db_session.commit() return jsonify(UserSchema().dump(u).data)
def update_user(user_id, new_user): """-""" logging.info('[ROUTER]: Updating user') try: # Update user = UserService.update_user(user_id, new_user) except UserNotFound as e: logging.error('[ROUTER]: ' + e.message) return error(status=404, detail=e.message) except Exception as e: logging.error('[ROUTER]: ' + str(e)) return error(status=500, detail='Generic Error') # Serialize user = UserSchema().dump(user).data response = UserResponder(user).serialize return jsonify(data=response), 200
def create_user(user): """-""" logging.info('[ROUTER]: Creating user') try: # Creating user = UserService.create_user(user) except UserDuplicated as e: logging.error('[ROUTER]: ' + e.message) return error(status=400, detail=e.message) except Exception as e: logging.error('[ROUTER]: ' + str(e)) return error(status=500, detail='Generic Error') # Serialize user = UserSchema().dump(user).data response = UserResponder(user).serialize return jsonify(data=response), 200
def add_stocks_to_user(user_id, n_stocks): """-""" logging.info('[ROUTER]: Adding stocks to user') try: # Adding stocks user = UserService.add_stocks_to_user(user_id, n_stocks) except GenericStockError as e: logging.error('[ROUTER]: ' + e.message) return error(status=400, detail=e.message) except UserNotFound as e: logging.error('[ROUTER]: ' + e.message) return error(status=404, detail=e.message) except Exception as e: logging.error('[ROUTER]: ' + str(e)) return error(status=500, detail='Generic Error') # Serialize user = UserSchema().dump(user).data response = UserResponder(user).serialize return jsonify(data=response), 200
def test_cannot_deserialize_user_invalid_cpf(app): user_data = { "first_name": "John", "last_name": "Doe", "cpf": "10101010101", "birthdate": "28/10/2010", "telephones": ["551622338877", "551633448977"], "address": { "city": "São Carlos", "state_province": "SP", "country": "Brazil", "zip_code": "14801180", "public_area_desc": "Av Lapena", "number": "877", }, } schema = UserSchema() result = schema.load(user_data) assert result.errors == {"cpf": ["invalid value"]} user_data.update({"cpf": "109875"}) result = schema.load(user_data) assert result.errors == {"cpf": ["invalid value"]} user_data.update({"cpf": "99999999999"}) result = schema.load(user_data) assert result.errors == {"cpf": ["invalid value"]} user_data.update({"cpf": "Xx99999999~"}) result = schema.load(user_data) assert result.errors == {"cpf": ["this field accepts numbers only"]}
def get_user(user_id): u = User.query.get(user_id) return jsonify(UserSchema().dump(u).data)
def get_current_user(): u = User.query.get(session['user_id']) if not u: raise Unauthorized('Not logged in.') return jsonify(UserSchema().dump(u).data)