Esempio n. 1
0
    def get(self):
        ensure_allowed('read', 'user')

        parser = reqparse.RequestParser()
        parser.add_argument('login', type=str, location='values')
        parser.add_argument('first_name', type=str, location='values')
        parser.add_argument('last_name', type=str, location='values')
        args = parser.parse_args()
        
        query = request.dbs.query(User).join(model.Entity)\
                                       .filter(not_(model.User.deleted))\
                                       .filter(not_(model.Entity.deleted))

        # Optional filters
        if args.get('login', None):
            query = query.filter(User.login == args['login'])

        if args.get('first_name', None):
            name_search = '%' + args['first_name'] + '%'
            query = query.filter(User.first_name.like(name_search))

        if args.get('last_name', None):
            name_search = '%' + args['last_name'] + '%'
            query = query.filter(User.first_name.like(name_search))

        return {'users': map(lambda u: marshal(u.to_dict(), user_fields), query.all())}
Esempio n. 2
0
    def get(self):
        ensure_allowed('read', 'user')

        parser = reqparse.RequestParser()
        parser.add_argument('login', type=str, location='values')
        parser.add_argument('first_name', type=str, location='values')
        parser.add_argument('last_name', type=str, location='values')
        args = parser.parse_args()

        query = request.dbs.query(User).join(model.Entity)\
                                       .filter(not_(model.User.deleted))\
                                       .filter(not_(model.Entity.deleted))

        # Optional filters
        if args.get('login', None):
            query = query.filter(User.login == args['login'])

        if args.get('first_name', None):
            name_search = '%' + args['first_name'] + '%'
            query = query.filter(User.first_name.like(name_search))

        if args.get('last_name', None):
            name_search = '%' + args['last_name'] + '%'
            query = query.filter(User.first_name.like(name_search))

        return {
            'users': map(lambda u: marshal(u.to_dict(), user_fields),
                         query.all())
        }
Esempio n. 3
0
    def get(self):
        ensure_allowed('read', 'transaction')
        query = request.dbs.query(Transaction)

        # Optional filters
        args = self.reqparse.parse_args()
        if args.get('user_id', None):
            query = query.filter(Transaction.user_id == args['user_id'])

        if args.get('from', None):
            try:
                date_from = datetime.strptime(args['from'], '%Y-%m-%d')
                query = query.filter(Transaction.date_time >= date_from)
            except ValueError:
                abort(412)

        if args.get('to', None):
            try:
                date_to = datetime.strptime(args['to'], '%Y-%m-%d')
                query = query.filter(Transaction.date_time <= date_to)
            except ValueError:
                abort(412)

        return {
            'transactions':
            map(lambda t: marshal(t.to_dict(), t.get_fields()), query.all())
        }
Esempio n. 4
0
    def post(self):
        """Creates a new user"""
        # Parse the arguments.
        parser = reqparse.RequestParser()
        parser.add_argument('login', type=str, location='json', required=True, help='Missing login')
        parser.add_argument('password_hash', type=str, location='json', required=True, help='Missing password')
        parser.add_argument('role', type=str, location='json', required=True, help='Missing role')
        parser.add_argument('entity_id', type=str, location='json', required=True, help='Missing entity_id.')
        parser.add_argument('last_name', type=str, location='json')
        parser.add_argument('first_name', type=str, location='json')
        args = parser.parse_args()

        first_name = args.get('first_name', None)
        last_name = args.get('last_name', None)
        role = args['role']
        entity_id = args['entity_id']
        login = args['login']
        password_hash = args['password_hash']

        ensure_allowed('create', 'user')

        # Check if the role is correct
        if role not in roles:
            app.logger.warning('Request on POST UserListAPI for non existing or missing role')
            return {'error': 'Role POSTed is not allowed'}, 412

        # We check if another non deleted user has the same login
        user_same_login_exists = request.dbs.query(exists().where(and_(User.login == login,
                                                                       not_(User.deleted)))).scalar()
        if user_same_login_exists:
            return {'error': 'User with the same login exists.'}, 412

        # Check if the entity exists
        if not request.dbs.query(exists().where(and_(model.Entity.id == entity_id,
                                                     not_(model.Entity.deleted)))).scalar():
            app.logger.warning('Request on POST UserListAPI with entity_id {} not found'.format(entity_id))
            return {'error': 'entity_id doesn\'t exists'}, 412

        # Write the user in DB.
        user_id = generate_uuid_for(request.dbs, User)
        u = User(
            id=user_id,
            login=login,
            password_hash=hashlib.sha1(password_hash).hexdigest(),
            last_name=last_name,
            first_name=first_name,
            role=role,
            deleted=False,
            entity_id=entity_id
        )
        request.dbs.add(u)
        app.logger.info('User {} (uuid: {}) created'.format(login, user_id))
        return marshal(u.to_dict(), user_fields), 201
Esempio n. 5
0
    def get(self, user_id):
        """
        GET the balance of a given user.
        """
        resource = 'own_transaction' if user_id == request.ws_session.user_id else 'transaction'
        ensure_allowed('read', resource)

        balance = request.dbs.query(func.sum(Transaction.amount).label('sum'))\
                             .filter(Transaction.user_id == user_id).scalar()

        return {
            'user_id': user_id,
            'balance': balance if balance is not None else 0
        }
Esempio n. 6
0
    def get(self, id):
        """
        GET a transaction with a given id.
        """
        try:
            # Find the transaction.
            t = request.dbs.query(Transaction).filter_by(id=id).one()

            # Check permissions (issue: allow to know about the data even with credentials)
            resource = 'own_transaction' if t.user_id == request.ws_session.user_id else 'transaction'
            ensure_allowed('read', resource)

            return marshal(t.to_dict(), t.get_fields())
        except NoResultFound:
            return '', 404

        except MultipleResultsFound:
            # TODO: log something
            return '', 500
Esempio n. 7
0
    def get(self, id):
        """
        GET a transaction with a given id.
        """
        try:
            # Find the transaction.
            t = request.dbs.query(Transaction).filter_by(id=id).one()

            # Check permissions (issue: allow to know about the data even with credentials)
            resource = 'own_transaction' if t.user_id == request.ws_session.user_id else 'transaction'
            ensure_allowed('read', resource)

            return marshal(t.to_dict(), t.get_fields())
        except NoResultFound:
            return '', 404

        except MultipleResultsFound:
            # TODO: log something
            return '', 500
Esempio n. 8
0
    def post(self):
        """Creates a new user"""
        # Parse the arguments.
        parser = reqparse.RequestParser()
        parser.add_argument('login',
                            type=str,
                            location='json',
                            required=True,
                            help='Missing login')
        parser.add_argument('password_hash',
                            type=str,
                            location='json',
                            required=True,
                            help='Missing password')
        parser.add_argument('role',
                            type=str,
                            location='json',
                            required=True,
                            help='Missing role')
        parser.add_argument('entity_id',
                            type=str,
                            location='json',
                            required=True,
                            help='Missing entity_id.')
        parser.add_argument('last_name', type=str, location='json')
        parser.add_argument('first_name', type=str, location='json')
        args = parser.parse_args()

        first_name = args.get('first_name', None)
        last_name = args.get('last_name', None)
        role = args['role']
        entity_id = args['entity_id']
        login = args['login']
        password_hash = args['password_hash']

        ensure_allowed('create', 'user')

        # Check if the role is correct
        if role not in roles:
            app.logger.warning(
                'Request on POST UserListAPI for non existing or missing role')
            return {'error': 'Role POSTed is not allowed'}, 412

        # We check if another non deleted user has the same login
        user_same_login_exists = request.dbs.query(exists().where(
            and_(User.login == login, not_(User.deleted)))).scalar()
        if user_same_login_exists:
            return {'error': 'User with the same login exists.'}, 412

        # Check if the entity exists
        if not request.dbs.query(exists().where(
                and_(model.Entity.id == entity_id, not_(
                    model.Entity.deleted)))).scalar():
            app.logger.warning(
                'Request on POST UserListAPI with entity_id {} not found'.
                format(entity_id))
            return {'error': 'entity_id doesn\'t exists'}, 412

        # Write the user in DB.
        user_id = generate_uuid_for(request.dbs, User)
        u = User(id=user_id,
                 login=login,
                 password_hash=hashlib.sha1(password_hash).hexdigest(),
                 last_name=last_name,
                 first_name=first_name,
                 role=role,
                 deleted=False,
                 entity_id=entity_id)
        request.dbs.add(u)
        app.logger.info('User {} (uuid: {}) created'.format(login, user_id))
        return marshal(u.to_dict(), user_fields), 201
Esempio n. 9
0
    def post(self):
        """
        Create a new transaction.
        """
        args = self.reqparse.parse_args()

        # Check if the required fields are present.
        transaction_type = get_or_412(args, 'transaction_type')
        amount = get_or_412(args, 'amount')
        currency = get_or_412(args, 'currency')
        user_id = get_or_412(args, 'user_id')

        resource = 'own_transaction' if request.ws_session.user_id == user_id else 'transaction'
        ensure_allowed('create', resource)

        if len(user_id) != 32:
            return {'error': 'The user id has not the good length.'}, 412
        if len(currency) != 3:
            return {'error': 'The currency has not the good length.'}, 412
        #TODO check if the user exists.

        if transaction_type == 'printing':
            pages_color = args.get('pages_color', 0)
            pages_grey_level = args.get('pages_grey_level', 0)

            # Check if the printing has pages (grey or color).
            if pages_color == 0 and pages_grey_level == 0:
                return {'error': 'No color or grey level page.'}, 412

            copies = get_or_412(args, 'copies')

            # Check if the printing has a positive number of copies.
            if copies <= 0:
                return {'error': 'Null number of copies.'}, 412

            if amount >= 0:
                return {
                    'error':
                    'Positive amount (should be negative for a printing).'
                }, 412

            # Check the user balance
            balance = request.dbs.query(func.sum(Transaction.amount).label('sum'))\
                             .filter(Transaction.user_id == user_id).scalar()

            if balance < -amount:
                return {'error': 'insufficient_balance'}

            # TODO check the coherence between the amount and others variables.
            t = Printing(generate_uuid_for(request.dbs,
                                           Transaction), user_id, amount,
                         currency, pages_color, pages_grey_level, copies)

        elif transaction_type == 'loading_credit_card':
            if amount <= 0:
                return {
                    'error':
                    'Negative amount (should be positive for a printing).'
                }, 412

            t = LoadingCreditCard(generate_uuid_for(request.dbs, Transaction),
                                  user_id, amount, currency)

        elif transaction_type == 'help_desk':
            id = generate_uuid_for(request.dbs, Transaction)
            t = HelpDesk(id, user_id, amount, currency)

        # If the type is not good
        else:
            return {'error': 'Unknown type.'}, 412

        request.dbs.add(t)

        return marshal(t.to_dict(), t.get_fields()), 201