コード例 #1
0
ファイル: func.py プロジェクト: Lyubomyr21/Lab4OOP
def create_entry(model_class, *, commit=True, **kwargs):
    session = Session()
    entry = model_class(**kwargs)
    session.add(entry)
    if commit:
        session.commit()
    return entry
コード例 #2
0
ファイル: blueprint.py プロジェクト: Lyubomyr21/Lab4OOP
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
コード例 #3
0
ファイル: blueprint.py プロジェクト: Lyubomyr21/Lab4OOP
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
コード例 #4
0
ファイル: setup.py プロジェクト: welisonmenezes/comsys
def add_primary_data():

    session = Session()

    _add_primary_language(session)
    _add_primary_template(session)
    _add_primary_post_type(session)
    _add_primary_role(session)
    _add_primary_user(session)
    _add_primary_configuration(session)

    session.commit()
コード例 #5
0
ファイル: blueprint.py プロジェクト: Lyubomyr21/Lab4OOP
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))
コード例 #6
0
ファイル: Add_Models.py プロジェクト: Lyubomyr21/Lab4OOP
from Models import Session, Customer, Goods
Session1 = Session()
customer1 = Customer(id = 118, customername = 'Kiborg', firstName = 'Andriy', lastName = 'Levitskiy', email = '*****@*****.**', password = '******', phone = '+380504658342')
customer2 = Customer(id = 128, customername = 'Lider', firstName = 'Bob', lastName = 'Vey', email = '*****@*****.**', password = '******', phone = '+380504658342')

goods1 = Goods(id = 111, name = "Watch", price = 2750, status = 3)
goods2 = Goods(id = 122, name = "Phone", price = 27000, status = 2)

Session1.add(customer1)
Session1.add(customer2)
Session1.add(goods1)
Session1.add(goods2)

Session1.commit()
Session1.close()
コード例 #7
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))
コード例 #8
0
ファイル: func.py プロジェクト: Lyubomyr21/Lab4OOP
def delete_entry(model_class, id, *, commit=True):
    session = Session()
    session.query(model_class).filter_by(id=id).delete()
    session.commit()