def put(self, user_id): try: req_data = request.get_json(force=True) user_in_db = User.get_user_by_id(user_id) if not user_in_db: return bad_request('User not found!', 422) data = UserSchema().load(req_data, partial=True) db_helper.update(user_in_db, data) data = UserSchema(exclude=['password']).dump(user_in_db) return ok(data, 200) except ValidationError as e: return bad_request(e.messages, 422) except Exception as e: print(e) return bad_request('Something went wrong', 500)
def on_get(self, req, resp, user_id): query = req.context['session'].query(UserModel) query = query.filter(UserModel.id == user_id) user = query.one_or_none() if not user: raise falcon.HTTPNotFound() resp.body = json.dumps(UserSchema().dump(user).data)
def put_user(): schema = UserSchema() result = dict() if not request.is_json: result['msg'] = 'Missing JSON in request' return jsonify(result), 400 req_data = request.get_json() if 'email' in req_data.keys(): email = req_data['email'] user = User.query.get_or_404(email) if 'password' in req_data.keys(): user.password = req_data['password'] if 'name' in req_data.keys(): user.name = req_data['name'] db.session.add(user) db.session.commit() result['msg'] = 'OK' result['data'] = schema.dump(user) else: result['msg'] = 'keys error' return jsonify(result), 400 return jsonify(result), 200
def _update_user(user_id): form = UserSchema().validate_or_400(request.get_json()) user = User.get(user_id) user = user.update(form) if commit_to_db(): return success(user.json()) error(500, {"user": "******"})
def create_user(): from wsgi import bcrypt schema = UserSchema() result = dict() req_data = request.get_json() if 'email' in req_data.keys(): email = req_data['email'] user = User.query.get(email) if user is None: user = User() user.email = req_data['email'] if 'password' in req_data.keys(): password = req_data['password'] pw_hash = bcrypt.generate_password_hash(password) user.password = pw_hash if 'name' in req_data.keys(): user.name = req_data['name'] else: # TODO 존재하면 있다고 리턴 result['msg'] = 'user exists' return jsonify(result), 400 else: user = schema.load(request.json) db.session.add(user) db.session.commit() result['msg'] = "user created" # result['data'] = schema.dump(user) result['data'] = "OK" return jsonify(result)
def create_user(): username = request.json.get('username') password = request.json.get('password') if not username or not password: return jsonify({ "Error": [{ "Type": "I/O", "message_error": "password or username is not inserted" }] }), 400 if User.query.filter_by(username=username).first(): return jsonify({ "Error": [{ "Type": "business", "message_error": "this username is not exist" }] }), 400 user = User(username=username) user.hashed_password = user.hash_password(password) db.session.add(user) db.session.commit() return jsonify(UserSchema().dump(user)), 201
def post(self): try: json_data = request.get_json(force=True) if not json_data: return bad_request('No input data provided', 400) if 'email' not in request.json: return bad_request('email not provided', 422) if 'password' not in request.json: return bad_request('password not provided', 422) if json_data['email'] == '' or json_data['email'] == None: return bad_request('email can\'t be empty or null', 422) if json_data['password'] == '' or json_data['password'] == None: return bad_request('password can\'t be empty or null', 422) user_in_db = User.get_user_by_email(json_data['email']) if user_in_db: authorized = user_in_db.check_password(json_data['password']) if authorized: users = UserSchema(only=('id', 'name', 'roles')).dump(user_in_db) expires = timedelta(days=1) token = create_access_token(identity=users, expires_delta=expires) return ok( { 'id': users['id'], 'name': users['name'], 'token': token }, 200) else: return bad_request('wrong password', 422) else: return bad_request('user not found!', 404) except Exception as e: return bad_request(str(e), 500)
def patch(self, user_id): try: data_parser = parser.parse_args() users = User.get_user_by_id(user_id) if not users: return bad_request('User not found!', 422) if data_parser['file'] == "": return bad_request('File not found!', 422) photo = data_parser['file'] if photo and allowed_file(photo.filename): secure_name = secure_filename(photo.filename) secure_name = get_file_extension(secure_name) secure_name = '{}{:-%Y%m%d%H%M%S}.{}'.format( str(uuid4().hex), datetime.now(), secure_name) photo.save(os.path.join(APP_STATIC, secure_name)) if users.image: os.remove(os.path.join(APP_STATIC, users.image)) # photo_url = request.url_root + url_for( # 'static', filename="image/" + secure_name) users.image = secure_name users.updated_at = datetime.now() db_helper.only_save() users = UserSchema(exclude=['password']).dump(users) return ok(users, 200) else: return bad_request('File not allowed!', 422) except Exception as e: return bad_request('Something went wrong', 500)
def post(self): json_data = request.get_json(force=True) if not json_data: return bad_request('No input data provided', 400) try: data = UserSchema().load(json_data) user_in_db = User.get_user_by_email(data.get('email')) if user_in_db: return bad_request('User already exist, please supply another email address', 422) users = User(data) db_helper.insert(users) ser_data = UserSchema(exclude=['password']).dump(users) return ok(ser_data, 201) except ValidationError as e: return bad_request(e.messages, 422) except Exception: return bad_request('Something went wrong', 500)
def get(self): users_schema = UserSchema(many=True) try: users = User.retrieve_all() except Exception as e: return jsonify(error=str(e)) else: return users_schema.jsonify(users).json, 200
def insert_user(user_json): user = UserSchema().load(user_json) try: user.password = user_service.set_user_password(user.password) return user_service.insert_user(user) except Exception as e: print(e) return {'error': 'Falha ao inserir usuario'}, 500
def get(self, user_id): user_schema = UserSchema(exclude=['password']) users = User.query.get(user_id) if not users: return {'status': 'error', 'data': 'not found'}, 404 print(users.image) users = user_schema.dump(users) return {'status': 'ok', 'data': users}, 200
def login( email, password ): user = get_user_by_email( email ) if validate_user_password( password, user.password ): user.password = None return UserSchema().dump( user ), 200 else: raise Exception("Senha incorreta!")
def list_users(): from wsgi import app app.logger.info("users call") schema = UserSchema(many=True) all_Users = User.query result = dict() result['data'] = schema.dump(all_Users) return jsonify(result)
def get_user(current_user, public_id): if not current_user.admin: return jsonify({'message': 'Cannot perform that function!'}) user = User.query.filter_by(public_id=public_id).first() if not user: return jsonify({'message': 'No user found'}) return UserSchema().jsonify(user)
def get_user(email): schema = UserSchema() result = dict() user = User.query.get_or_404(email) result['msg'] = 'OK' result['data'] = schema.dump(user) return jsonify(result), 200
def list_users(): search = request.args.get('keyword', '') schema = UserSchema(many=True) if search: users = User.query.filter(User.username.ilike('%{}%'.format(search))) return jsonify(schema.dump(users)), 200 users = User.query.all() return jsonify(schema.dump(users)), 200
def get_by_id(user_id): try: item = UserModel.query.filter_by(id=user_id).first() if item is None: return HTTP_404_NOT_FOUND, None schema = UserSchema() result = schema.dump(item, many=False) return HTTP_200_OK, result except Exception as error: print("Error------------------", error) return HTTP_400_BAD_REQUEST, None
def get(self, id): user_schema = UserSchema() try: data = {'id': id} user = User.retrieve_by(**data) if not user: raise Exception(f'There are not user ID {id}') except Exception as e: return jsonify(error=str(e)) else: return user_schema.jsonify(user).json, 200
def post(self): """ Check that the username and email are not already in use by another user and check the password strength is sufficient as the average user will need this check. If this is successful then create the user. """ form = UserSchema().validate_or_400(request.get_json()) user = User.create(form) user.set_role(Roles.user) if commit_to_db(): user.send_confirmation_email() return success({"confirm": "Please confirm email address"}) error(500, {"user": "******"})
def get_sort_by(): """ Return the string for sqlalchemy to use for order_by from query_params. """ sort_by = snakecase(request.args.get("sortby", "id")) if sort_by not in UserSchema().field_names(): fail(400, {"sortby": "Sortby is not a valid field for resource"}) order = request.args.get("order", "asc").lower() if order not in ["asc", "desc"]: fail(400, {"order": "Order must be asc or desc"}) return sql.text(f"{sort_by} {order}")
def update_user(id): user = User.query.get_or_404(id) username = request.json.get('username') password = request.json.get('password') if username and user.username != username: duplicate = User.query.filter_by(username=username).first() if duplicate: return jsonify(message_code=1007), 409 user.username = username db.session.commit() return jsonify(UserSchema().dump(user)), 200
def post(self): user_schema = UserSchema() try: data_json = request.json if not data_json: raise Exception('The request does not have json data.') user = User.create(**data_json) except Exception as e: return jsonify(error=str(e)) else: return user_schema.jsonify(user).json, 201
def update_user(current_user, public_id): if not current_user.admin: return jsonify({'message': 'Cannot perform that function!'}) user = User.query.filter_by(public_id=public_id).first() if not user: return jsonify({'message': 'No user found'}) user.name = request.json['name'] user.admin = request.json['admin'] db.session.commit() return UserSchema().jsonify(user)
def create_user(): username = request.json.get('username') password = request.json.get('password') if not username or not password: return jsonify(message_code=1005), 400 if username and User.query.filter_by(username=username).first(): return jsonify(message_code=1007), 409 user = User(username=username) user.hashed_password = user.hash_password(password) db.session.add(user) db.session.commit() return jsonify(UserSchema().dump(user)), 201
def create(user_data): try: schema = UserSchema() new_item = schema.make(user_data) new_item.password = lazy_hashing(user_data['password']) db.session.add(new_item) # commit db.session.commit() # dump data result = schema.dump(new_item, many=False) print("items-------------", result) return HTTP_201_CREATED, result except Exception as error: print("Error----------------", error) db.session.rollback() return HTTP_400_BAD_REQUEST, None
def get_all(page_number, page_size): # return http_status, data, total try: schema = UserSchema() total = UserModel.query.count() if total == 0: return HTTP_404_NOT_FOUND, None, 0 items = UserModel.query.paginate(page_number, page_size).items if items in [None, {}]: return HTTP_404_NOT_FOUND, None, 0 # dump data result = schema.dump(items, many=True) return HTTP_200_OK, result, total except Exception as error: print("Error----------------", error) return HTTP_400_BAD_REQUEST, None, 0
def update_user(id): user = User.query.get_or_404(id) username = request.json.get('username') password = request.json.get('password') if username and user.username != username: duplicate = User.query.filter_by(username=username).first() if duplicate: return jsonify({ "Error": [{ "Type": "business", "message_error": "This username is not exist" }] }), 409 user.username = username db.session.commit() return jsonify(status="User changed", user=UserSchema().dump(user)), 200
def update(user_id, user_data): try: schema = UserSchema() item = UserModel.query.filter_by(id=user_id).first() print(item) if item is None: return HTTP_404_NOT_FOUND, None if user_data.get('password') is not None: user_data['password'] = lazy_hashing(user_data['password']) new_item = UserModel.query.filter_by(id=user_id).update(user_data) db.session.commit() item = UserModel.query.filter_by(id=user_id).first() result = schema.dump(item, many=False) return HTTP_201_CREATED, result except Exception as error: print("Error-------------", error) db.session.rollback() return HTTP_400_BAD_REQUEST, None
def post(self): """ Check if the user exists and if their email has been confirmed. Check the password and if correct returns an auth cookie. For auth we only need the email and password to identify a user. """ user_schema = UserSchema(only=["email", "password"]) form = user_schema.validate_or_400(request.get_json()) user = User.query.filter_by(email=form["email"]).first() # Check the email and password are correct. if not user or not user.check_password(form["password"]): fail(401, {"form": "Incorrect email address or password"}) # Check the user has confirmed their email. if not user.confirmed_on: fail(401, {"form": "Please confirm email"}) return _login_success_response(user)