def post(self): user_schema_register = UserRegistrationSchema() user_json = request.get_json() try: user = user_schema_register.load(user_json) except ValidationError as e: return e.messages if UserService.get_by_username(user["username"]): return {"message": USER_ALREADY_EXISTS}, 400 if UserService.get_by_email(user["email"]): return {"message": EMAIL_ALREADY_EXISTS}, 400 try: user = UserService.create( user["username"], user["email"], user["password"], user["first_name"], user["last_name"], ) user_schema = UserSchema() return user_schema.dump(user), 201 except: # failed to save user to db traceback.print_exc() if user: user.delete() return {"message": FAILED_TO_CREATE}, 500
def create_user(): app.logger.info('entered action') data = request.json user_schema = UserSchema() app.logger.info('created schema') parsed_data = { 'username': data['username'], 'email': data['email'], 'password_hash': bcrypt.generate_password_hash(data['password']).decode('utf-8') } if "role" in data: parsed_data['role'] = data['role'] if not session.query(User).filter( User.username == parsed_data['username']).one_or_none() is None: return 'username busy', 400 try: user = user_schema.load(parsed_data) except ValidationError as err: return err.messages, 400 app.logger.info('created user') session.add(user) session.commit() return user_schema.dump(user), 201
def post(self): data = parser.parse_args() username = data['username'] # Searching user by username current_user = UserModel.find_by_username(username) # user does not exists if not current_user: return {'message': f'User {username} doesn\'t exist'}, 404 # user exists, comparing password and hash if UserModel.verify_hash(data['password'], current_user.password): # generating access token and refresh token access_token = create_access_token(identity=username) refresh_token = create_refresh_token(identity=username) user_schema = UserSchema(exclude=['id', 'password']) user = user_schema.dump(current_user) return { 'user': f'{user}', 'message': f'Logged in as {username}', 'access_token': access_token, 'refresh_token': refresh_token } else: return {'message': "Wrong credentials"}, 404
def on_get(self, req, resp): user = req.context['user'] user_schema = UserSchema() result = user_schema.dump(user) resp.context['result'] = result.data
def get_all_users(): try: users = session.query(User).all() except: users = [] users_dto = UserSchema(many=True) return jsonify(users_dto.dump(users)), 200
def login_user(self, user_data): user = self.db.query(UserModel).filter_by( username=user_data.get("username")).first() if not user: raise NotFound('Order with id {} not found'.format( user_data.get("username"))) if not check_password_hash(user.password, user_data.get("password")): raise ValueError schemas = UserSchema() return schemas.dump(user).data
def find_user(user_id): try: UserSchema(only=['id']).load({'id': user_id}) except ValidationError as err: return 'invalid id', 400 found_user = session.query(User).filter(User.id == user_id).one_or_none() if found_user is None: return 'user not found', 404 user_schema = UserSchema(exclude=['password_hash']) user = user_schema.dump(found_user) return user
class UserRegistration(Resource): def __init__(self): self.user_schema = UserSchema() self.validator = Validator({ 'username': { 'type': 'string', 'empty': False, 'minlength': 4, 'maxlength': 30 }, 'password': { 'type': 'string', 'empty': False, 'minlength': 4, }, 'email': { 'type': 'string', 'regex': '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', 'empty': False, 'minlength': 5 } }) super().__init__ def post(self): args = request.get_json() self.validator.validate(args) if len(self.validator.errors) > 0: return {'error': self.validator.errors}, 400 existing_user = UserModel.query.filter_by( username=args.get('username')).first() if existing_user: return {'error': 'Username already taken'}, 400 try: # Overriding value in dictionary to encrypted password args['password'] = _flask_bcrypt.generate_password_hash( password=args.get('password'), rounds=15).decode('utf-8') new_user = self.user_schema.load(args) new_user.save() except ValidationError as e: return {'error': f'{e}'}, 400 except Exception as e: return {'error': f'{e}'}, 500 return { 'message': 'New user created!', 'data': self.user_schema.dump(new_user) }, 201
def on_get(self, req, resp): session = req.context['session'] query = req.params.get('query', '') user_schema = UserSchema(many=True) users = session.query(User).\ filter(or_( User.last_name.ilike('%' + query + '%'), User.first_name.ilike('%' + query + '%'), )).\ limit(100).\ all() result = user_schema.dump(users) resp.context['result'] = result.data
def edit_user(user_id): data = request.json try: validate_update(data, user_id) except ValidationError as err: return jsonify(err.messages), 400 found_user = session.query(User).filter(User.id == user_id).one_or_none() if auth.current_user().id != found_user.id: return "no permission", 403 found_user.username = data['username'] found_user.email = data['email'] # found_user.role = data['role'] session.commit() return_schema = UserSchema(exclude=['password_hash']) return_user = return_schema.dump(found_user) return return_user
def signup(): """ Create User """ user_data = request.json schema = UserSchema() try: user = schema.load(user_data).data except ValidationError as err: response.status = 400 return schema.get_validation_errors(err) try: query = User.insert(username=user.username, password=fn.make_password( user.password)).execute() except IntegrityError as err: return { "code": "username_already_exist", "description": "User does not exist" } result = schema.dump(user).data return HTTPResponse(result, status=201)
def create_user(): email = request.json.get('email', None) password = request.json.get('password', None) passport = request.json.get('passport', None) adress = request.json.get('adress', None) money_amount = request.json.get('money_amount', None) telephone_number = request.json.get('telephone_number', None) super_user = request.json.get('super_user', False) print(session.query(Users).filter_by(email=email)) if session.query(Users).filter_by(email=email).first() is None: new_user = Users(email=email, password=hashlib.md5(password.encode()).hexdigest(), passport=passport, adress=adress, money_amount=money_amount, telephone_number=telephone_number, super_user=super_user) session.add(new_user) session.commit() schemas = UserSchema() return jsonify(schemas.dump(new_user)), 200 return jsonify({"msg": "Email is already in use"}), 404
def user_detail(user_id): try: user = session.query(User).filter(User.id == user_id).one() except NoResultFound: raise if request.method == 'GET': schema = UserSchema() data = schema.dump(user).data return Response(response=json.dumps({"data": data}), status=200, mimetype="application/json") if request.method == 'PUT': args = parse_args(UserSchema(dump_only=( "account", "password", ))) user.nickname = args['nickname'] if args['nickname'] else user.nickname session.commit() return Response(status=200, mimetype="application/json") if request.method == 'DELETE': session.delete(user) session.commit() return Response(status=204, mimetype="application/json")
def show_user(id): user = session.query(Users).filter_by(id=id).first() if user is not None: schemas = UserSchema() return jsonify(schemas.dump(user)) return jsonify({"msg": "Not Found"}), 404