Exemplo n.º 1
0
def update_goods(id):
    session = Session()
    goods_data = GoodsToUpdate().load(request.json)
    original_goods_data = session.query(Goods).filter_by(id=id).one()
    for key, value in goods_data.items():
        setattr(original_goods_data, key, value)
    session.commit()
    return jsonify(GoodsData().dump(original_goods_data)), 200
Exemplo n.º 2
0
 def setUp(self):
     session = Session()
     query = session.query(Post.id)
     self.result = Paginate(query, 1, 10)
     self.keys = [
         'prev', 'next', 'has_prev', 'has_next', 'size', 'pages', 'total',
         'current'
     ]
Exemplo n.º 3
0
def update_customer(id):
    session = Session()
    customer_data = CustomerToUpdate().load(request.json)
    original_customer_data = session.query(Customer).filter_by(id=id).one()
    for key, value in customer_data.items():
        setattr(original_customer_data, key, value)
    session.commit()
    return jsonify(CustomerData().dump(original_customer_data)), 200
Exemplo n.º 4
0
def create_buy():
    buy_data = BuyGoodsData().load(request.json)
    session = Session()
    goods = session.query(Goods).filter_by(
        id=int(buy_data.get("g_id"))).first()
    if (goods.status - int(buy_data.get("quantity"))) >= 0:
        buy = func.create_entry(Buy, **buy_data)
        goods.update(
            {Goods.status: goods.status - int(buy_data.get("quantity"))})
    else:
        return jsonify({"Error": "request not available"}), 400
    session.commit()
    return jsonify(BuyGoodsData().dump(buy))
Exemplo n.º 5
0
class AuthUtils():
    def __init__(self):

        self.session = Session()

    def get_logged_in(self):
        """Get the logged user if the given token is valid, otherwise, return False."""

        token = request.headers.get('Authorization')
        if token:
            try:
                access = decode_token(token)
                if 'identity' in access:
                    identity = access['identity']
                    if 'id' in identity and 'login' in identity and 'role' in identity:
                        user = self.session.query(User).filter_by(
                            login=identity['login']).first()
                        if user:
                            return {'user': user, 'access': access}
            except Exception as e:
                return False
        return False

    def get_authorized_passport(self,
                                from_where='Authorization',
                                verify_blacklist=True,
                                token_key='token'):
        """Get the authorized user based on the given token. This can come from Authorization or Request."""

        token: None

        if from_where == 'Authorization':
            token = request.headers.get('Authorization')

        elif from_where == 'Request':
            data = request.get_json()
            if token_key in data and data[token_key] != '':
                token = data[token_key]

        else:
            raise BadRequestError('Invalid resource origin.')

        if token:

            if verify_blacklist:
                blacklist = self.session.query(
                    Blacklist.id).filter_by(value=token).first()
                if blacklist:
                    raise NotAuthorizedError('Token revoked.')

            try:
                access = decode_token(token)
                if 'identity' in access:
                    identity = access['identity']
                    if 'id' in identity and 'login' in identity and 'role' in identity:
                        user = self.session.query(User).filter_by(
                            login=identity['login']).first()
                        if user:
                            return {'user': user, 'access': access}
                        else:
                            raise NotFoundError('No user found.')
                    else:
                        raise BadRequestError('Invalid identity.')
                else:
                    raise BadRequestError('Invalid Token.')
            except Exception as e:
                raise NotAuthorizedError('Token already expired.')
        else:
            raise NotAuthorizedError('No Token send.')

    def verify_capabilities(self,
                            capabilities,
                            capability_type=None,
                            permission=None,
                            owner_id=None,
                            user_id=None,
                            new_owner_id=None,
                            post_type_id=None):
        """Verify from the given capabilities if it matches with the given capability type and permission."""

        has_comparators = False
        if owner_id and user_id:
            has_comparators = True

        # verify the post type id
        for capability in capabilities:
            the_type = getattr(capability, 'type')
            the_target = getattr(capability, 'target_id')
            if the_type == 'specific-post-type':
                if post_type_id and not the_target:
                    raise NotAuthorizedError('The target id must be sent.')
                    return True
                if post_type_id and post_type_id != the_target:
                    raise NotAuthorizedError(
                        'You cannot access elements that belongs to this post type.'
                    )
                    return True

        for capability in capabilities:
            if capability_type == getattr(capability, 'type') and getattr(
                    capability, permission) == True and getattr(
                        capability, 'only_themselves') == False:
                return True
            elif capability_type == getattr(capability, 'type') and getattr(
                    capability, permission) == True and has_comparators:
                if new_owner_id and owner_id != new_owner_id:
                    raise NotAuthorizedError(
                        'You cannot change the owner ID of this element.')
                    return True
                if owner_id != user_id:
                    raise NotAuthorizedError(
                        'You only can access your own element by this action.')
                    return True
                return True
            elif capability_type == getattr(capability, 'type') and getattr(
                    capability, permission) == True:
                return True

        raise NotAuthorizedError(
            'Your profile does not has permission to access this resource.')
Exemplo n.º 6
0
class AuthController(Resource):
    """This flask_restful API's Resource works like a controller to AuthRepository."""
    def __init__(self):
        self.session = Session()

    def post(self):
        """Sets the available endpoints to deal with Tokens."""

        if str(request.url_rule) == '/api/get-token':
            return self._get_token()
        elif str(request.url_rule) == '/api/refresh-token':
            return self._refresh_token()
        elif str(request.url_rule) == '/api/revoke-token':
            return self._revoke_token()
        elif str(request.url_rule) == '/api/test-token':
            return self._test_token()
        return ErrorHandler().get_error(405, 'Method not allowed.')

    def _get_token(self):
        """Gets the Token and Refresh Token to valid user."""

        data = request.get_json()
        if 'login' in data and 'password' in data and data[
                'login'] != '' and data['password'] != '':
            user = self.session.query(User).filter_by(
                login=data['login']).first()
            if user:
                if bcrypt.check_password_hash(user.password, data['password']):
                    user_identity = {
                        'id': user.id,
                        'login': user.login,
                        'role': user.role.name
                    }
                    try:
                        token = create_access_token(identity=user_identity)
                        refresh_token = create_refresh_token(
                            identity=user_identity)
                        user.refresh_token = refresh_token
                        self.session.commit()
                        return {
                            'access_token': token,
                            'refresh_token': refresh_token
                        }, 200
                    except Exception as e:
                        return ErrorHandler().get_error(
                            500, 'Error to process your login.')
                else:
                    return ErrorHandler().get_error(401,
                                                    'Invalid credencials.')
            else:
                return ErrorHandler().get_error(401, 'Invalid credencials.')
        else:
            return ErrorHandler().get_error(
                400, 'Insufficient data to authenticate.')

    def _refresh_token(self):
        """Refreshes the Token by the given Refresh Token only if it is valid yet."""
        def fn():
            passport = AuthUtils().get_authorized_passport(
                from_where='Request',
                verify_blacklist=False,
                token_key='refresh_token')
            print(passport)
            data = request.get_json()
            if passport['user'].refresh_token == data['refresh_token']:
                try:
                    token = create_access_token(
                        identity=passport['access']['identity'])
                    refresh_token = create_refresh_token(
                        identity=passport['access']['identity'])
                    passport['user'].refresh_token = refresh_token
                    self.session.commit()
                    return {
                        'access_token': token,
                        'refresh_token': refresh_token
                    }, 200
                except Exception as e:
                    print(e)
                    return ErrorHandler().get_error(
                        500, 'Error to process the token refreshing.')
            else:
                return ErrorHandler().get_error(
                    401, 'The given Refresh Token is not available.')

        return self.run_if_not_raise(fn)

    def _revoke_token(self):
        """Revokes the given Token by adding it into a blacklist and empties the user Refresh Token."""
        def fn():
            passport = AuthUtils().get_authorized_passport(
                from_where='Request', verify_blacklist=True)
            if not passport['user'].refresh_token or passport[
                    'user'].refresh_token == '':
                return ErrorHandler().get_error(401, 'Token already revoked.')
            try:
                data = request.get_json()
                passport['user'].refresh_token = None
                blacklist = Blacklist(type='token',
                                      value=data['token'],
                                      target='auth')
                self.session.add(blacklist)
                self.session.commit()
                return {'message': 'Token revoked successfully.'}, 200
            except Exception as e:
                self.session.rollback()
                return ErrorHandler().get_error(
                    500, 'Error to process the token revoking.')

        return self.run_if_not_raise(fn)

    def _test_token(self):
        """Just a endpoint to test the given Token sent by request header into the Authorization key."""
        def fn():
            passport = AuthUtils().get_authorized_passport()
            schema = UserSchema(many=False,
                                exclude=('password', 'refresh_token', 'medias',
                                         'socials'))
            return {
                'user': schema.dump(passport['user']),
                'access': passport['access']
            }, 200

        return self.run_if_not_raise(fn)

    def run_if_not_raise(self, fn):
        """Catch exception if it occurs, if not, execute the given function."""

        try:
            return fn()
        except NotAuthorizedError as e:
            return ErrorHandler().get_error(401, str(e))
        except BadRequestError as e:
            return ErrorHandler().get_error(400, str(e))
        except NotFoundError as e:
            return ErrorHandler().get_error(404, str(e))
        except Exception as e:
            return ErrorHandler().get_error(500, str(e))
Exemplo n.º 7
0
def list_goods(*filters):
    session = Session()
    return (session.query(Goods).all())
Exemplo n.º 8
0
def get_entry_by_id(model_class, id, **kwargs):
    session = Session()
    return session.query(model_class).filter_by(id=id, **kwargs).one()
Exemplo n.º 9
0
def delete_entry(model_class, id, *, commit=True):
    session = Session()
    session.query(model_class).filter_by(id=id).delete()
    session.commit()