class PrivateChatSchema(ma.Schema):
    """Class to serialize PrivateChat models."""

    RESOURCE_NAME = "private_chat"
    COLLECTION_NAME = "private_chats"

    _id = ma.UUID(required=True, data_key="id")
    _primary_user = ma.Nested(UserSchema(),
                              dump_only=True,
                              data_key="primary_user")
    _secondary_user = ma.Nested(UserSchema(),
                                dump_only=True,
                                data_key="secondary_user")
    resource_type = ma.Str(dump_only=True, default="PrivateChat")

    # Links
    messages_url = ma.URLFor("api.get_private_chat_messages",
                             private_chat_id="<_id>")

    @post_load
    def convert_uuid_to_hex(self, data, **kwargs):
        """Convert all UUID fields to their 32-character hexadecimal equivalent."""
        for key in data:
            value = data[key]
            if isinstance(value, uuid.UUID):
                data[key] = data[key].hex
        return data
예제 #2
0
def test_delete_user(db: Session, client: TestClient, http_basic_auth: HTTPBasicAuth):
    user = user_crud.get_multi(db)[0]  # there is already one from basic auth
    response = client.delete(f'/users/{user.id}', auth=http_basic_auth)
    assert response.status_code == status.HTTP_200_OK

    actual_user = UserSchema.from_orm(user)
    retrieved_user = UserSchema.parse_raw(response.text)
    assert actual_user == retrieved_user
예제 #3
0
def test_get_user(client: TestClient, http_basic_auth: HTTPBasicAuth):
    user = UserFactory()
    response = client.get(f'/users/{user.id}', auth=http_basic_auth)
    assert response.status_code == status.HTTP_200_OK

    actual_user = UserSchema.from_orm(user)
    retrieved_user = UserSchema.parse_raw(response.text)
    assert actual_user == retrieved_user
예제 #4
0
def new_user():
    user_data = request.json
    schema = UserSchema()
    schema.load(user_data)
    user = UserModel(user_data['full_name'], user_data['username'],
                     user_data['password'], user_data['email'])
    user.save_to_db()
    return jsonify({
        'id': user.id,
        'username': user.username,
        'full_name': user.full_name,
        'password': user.password,
        'email': user.email
    }), 201
예제 #5
0
 def put(cls, user_id):
     data = request.get_json()
     create_error = UserSchema().validate(data)
     update_error = UserUpdateSchema().validate(data)
     if update_error:
         return {'message': update_error}, 400
     if data.get('password', None):
         data['password'] = bcrypt.generate_password_hash(
             data['password'], 10)
     user_by_id = UserModel.get_by_id(user_id)
     if user_by_id:
         try:
             UserModel.update_by_id(user_id, data)
             return {'message': 'user was updated'}, 200
         except IntegrityError as err:
             return {'message': err.args}, 400
     if create_error:
         return {'message': create_error}, 400
     user = UserModel(**data)
     if UserModel.get_by_email(user.email):
         return {
             'message': f'User with email {user.email} already exist'
         }, 400
     user.password = bcrypt.generate_password_hash(user.password)
     user.save()
     return {'message': 'User was created'}, 201
예제 #6
0
        def get(self, user_id: int):

            user = User.query.get(user_id)
            if not user:
                abort(404, "User was not found")

            return jsonify(UserSchema().dump(user))
예제 #7
0
def login():

    errors = LoginSchema().validate(request.get_json())
    if errors:
        return {'message': 'Error','Error': errors}

    params = request.get_json()
    email = params.get('email')
    password = params.get('password')
    rtn = User.query.filter_by(email=email).all()

    if not rtn:
        return {'token': False,'message': 'Wrong Username'}

    user = vars(rtn[0])
    print(user)
    if user and bcrypt.check_password_hash(user['password'], password):
        
        token = jwt.encode({'id': user['id'], 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=60)}, current_app.config['SECRET_KEY'], algorithm="HS256")
        return jsonify({
            'token': token,
            **UserSchema().dump(user)
        })

    return {
        'token': False,
        'message': 'Wrong Password'
    }
예제 #8
0
def test_create_user(client: TestClient, http_basic_auth: HTTPBasicAuth):
    actual_user_data = UserCreateFactory()
    response = client.post(
        '/users', json=jsonable_encoder(actual_user_data), auth=http_basic_auth
    )
    assert response.status_code == status.HTTP_201_CREATED

    retrieved_user_data = UserSchema.parse_raw(response.text)
    assert actual_user_data.login == retrieved_user_data.login
예제 #9
0
class UserResource(Resource):
	user_schema = UserSchema()

	@jwt_required
	def get(self, user_id):
		user = User.query.filter_by(id=user_id).first()
		if user is None:
			return {'error': 'No user found'}, 404

		return self.user_schema.dump(user)
예제 #10
0
def test_update_user(db: Session, client: TestClient, http_basic_auth: HTTPBasicAuth):
    user = user_crud.get_multi(db)[0]  # there is already one from basic auth
    new_user_data = UserUpdateSchema(**UserCreateFactory().dict())
    response = client.put(
        f'/users/{user.id}', json=jsonable_encoder(new_user_data), auth=http_basic_auth
    )
    assert response.status_code == status.HTTP_200_OK

    retrieved_user_data = UserSchema.parse_raw(response.text)
    assert new_user_data.login == retrieved_user_data.login
예제 #11
0
def register(data):
    """A new user sends username & password to register."""

    # check if username exists
    if UserModel.query.filter_by(username=data['username']).first():
        raise BadRequest('Username existed.')

    # save user's data & response a successful message
    user = UserModel(**data)
    user.save_to_db()
    return jsonify(UserSchema(exclude=("password",)).dump(user)), 201
예제 #12
0
class SignupResource(Resource):
    schema = UserSchema()

    @jwt_required
    def post(self):
        username = request.json['username']
        password = request.json['password']
        user = User(username=username, password=password)
        db.session.add(user)
        db.session.commit()

        return self.schema.dump(user)
예제 #13
0
 def post(cls):
     data = request.get_json()
     error = UserSchema().validate(data)
     if error:
         return {'message': error}, 400
     user = UserModel(**data)
     if UserModel.get_by_email(user.email):
         return {
             'message': f'User with email {user.email} already exist'
         }, 400
     user.password = bcrypt.generate_password_hash(user.password, 10)
     user.save()
     return {'message': 'User was created'}, 201
예제 #14
0
class UserListResource(Resource):
	user_schema = UserSchema()

	@jwt_required
	def get(self):
		return [self.user_schema.dump(user) for user in User.query.all()]

	def post(self):
		email = request.json['email']
		password = request.json['password']
		user = User(email=email, password=password)
		db.session.add(user)
		db.session.commit()

		return self.user_schema.dump(user)
예제 #15
0
def getUserById(loged_user, user_id):
    # print(user_id)
    rtn = User.query.filter_by(id=user_id).all()
    if not rtn:
        return {
            'status': False,
            'message': 'Wrong user id'
        }

    user = UserSchema().dump(rtn[0])
    
    return {
        'status': True,
        'user': user
    }
예제 #16
0
    def decorated(*args, **kwargs):
        bearer = request.headers.get('Authorization')
        if not bearer:
            return jsonify({'message': 'Token is missing'}), 401

        token = bearer.split(' ')[1].strip('"')
        try:
            data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=["HS256"])
        except Exception as e:
            return jsonify({'message': f'Token is invalid: {e}'}), 401

        rtn = User.query.filter_by(id=data['id']).all()

        if not rtn:
            return {'token': False,'message': 'User doesnt exist'}
        loged_user = UserSchema().dump(rtn[0])
        return f(loged_user, *args, **kwargs)
예제 #17
0
def register():
    ## TODO: INPUT VALIDATOR DECORATOR
    data = request.json
    data['password'] = bcrypt.generate_password_hash(data.get('password')).decode('utf-8')

    newUser = User(**data)
    try:
        db.session.add(newUser)
        db.session.commit()
    except Exception as e:
        error = str(e.__dict__['orig'])
        return {'message': f'Error', 'Error': error}

    return {
        'status': True,
        'message': f"New {data.get('username')} created.",
        'user': UserSchema().dump(newUser)
    }
예제 #18
0
class UserListResource(Resource):
    schema = UserSchema()

    @jwt_required
    def get(self):
        users = User.query.all()
        result = []
        for user in users:
            result.append(self.schema.dump(user))

        return result

    def post(self):
        email = request.json['email']
        password = request.json['password']
        user = User(email=email, password=password)
        db.session.add(user)
        db.session.commit()

        return self.schema.dump(user)
예제 #19
0
    if not user:
        abort(400, 'Could not authenticate user with provided token')
    elif not user.is_active:
        abort(400, 'Inactive user')
    access_token_expires = timedelta(
        minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(identity=user.id,
                                       expires_delta=access_token_expires)
    return {'access_token': access_token}


@docs.register
@doc(description='Test access token', tags=['login'], security=security_params)
@app.route(f'{config.API_V1_STR}/login/test-token', methods=['POST'])
@use_kwargs({'test': fields.Str(required=True)})
@marshal_with(UserSchema())
@jwt_required
def route_test_token(test):
    current_user = get_current_user()
    if current_user:
        return current_user
    else:
        abort(400, 'No user')
    return current_user


@docs.register
@doc(
    description=
    'Test access token manually, same as the endpoint to "Test access token" but copying and adding the Authorization: Bearer <token>',
    params={
예제 #20
0
# Import Schemas
from app.schemas.user import UserSchema
from app.schemas.msg import MsgSchema


@docs.register
@doc(description="Retrieve users", security=security_params, tags=["users"])
@app.route(f"{config.API_V1_STR}/users/", methods=["GET"])
@use_kwargs(
    {
        "skip": fields.Int(default=0),
        "limit": fields.Int(default=100)
    },
    locations=["query"],
)
@marshal_with(UserSchema(many=True))
@jwt_required
def route_users_get(skip=0, limit=100):
    current_user = get_current_user()

    if not current_user:
        abort(400, "Could not authenticate user with provided token")
    elif not check_if_user_is_active(current_user):
        abort(400, "Inactive user")
    elif not check_if_user_is_superuser(current_user):
        abort(400, "Not a superuser")
    db_users = get_db_users()
    result = db_users.get_query_result(selector={"type": "user"})
    return result[skip:skip + limit]

예제 #21
0
def get_all_users(loged_user):
    users = User.query.all()
    return jsonify(UserSchema(many=True).dump(users))
예제 #22
0
from flask_restful import Resource

from app.models.user import UserModel
from app.schemas.user import UserSchema
from app.libs.strings import gettext

user_schema = UserSchema()
user_list_schema = UserSchema(many=True)


class User(Resource):
    def get(self, person_id):
        user = UserModel.find_by_person_id(person_id)
        if user:
            return user_schema.dump(user)
        return {"message": gettext("person_id_not_found")}, 404

    def post(self, person_id):
        if UserModel.find_by_person_id(person_id):
            return {
                "message":
                gettext("person_id_already_exists").format(person_id)
            }, 400

        user = UserModel(person_id=person_id)
        try:
            user.save_to_db()
        except:
            return {"message": gettext("person_id_error_inserting")}, 500

        return user_schema.dump(user), 201
예제 #23
0
    def marsh():

        users = User.query.all()

        return jsonify(UserSchema(many=True).dump(users))
예제 #24
0
        def get(self):

            users = User.query.all()

            return jsonify(UserSchema(many=True).dump(users))
예제 #25
0
 def get(cls, user_id):
     user = UserModel.get_by_id(user_id)
     if not user:
         return {'massage': 'user not found'}, 404
     return UserSchema().dump(user)
예제 #26
0
 def get(cls):
     users = UserModel.get_all()
     return {'user': UserSchema(many=True).dump(users)}