def put(cls, id):
        cart = models.Cart.query.get(id)
        data = _update_cart_parser.parse_args()
        cartline_id = data["cartline_id"]
        quantity = data["quantity"]

        if not cart:
            return api.abort(404, NOT_FOUND_ERROR.format(f"Cart {id}"))
        cartline = (
            models.CartLine.query.filter_by(id=cartline_id)
            .filter_by(cart_id=id)
            .first()
        )
        if not cartline:
            return api.abort(404, NOT_FOUND_ERROR.format(f"Cartline {cartline_id}"))
        if quantity <= 0:
            return api.abort(400, "0 or negative quantity is not allowed")
        cartline.quantity = quantity
        try:
            db.session.add(cartline)
            db.session.commit()
        except Exception as ex:
            db.session.rollback()
            print(ex)
            return api.abort(500, ex)
        return cartline, 200
예제 #2
0
    def post(self):
        """
        Reboot host
        """
        args = host_reboot_parser.parse_args()

        if not args.message:
            message = 'Reboot from RESTful API'
        else:
            message = args.message

        msg = '*** LXC Web Panel *** \
                \n%s' % message

        try:
            # DEBUG
            subprocess.check_call('echo \'%s\' | wall' % msg, shell=True)

            # subprocess.check_call('/sbin/shutdown -r now \'%s\'' % msg, shell=True)
            return {
                'status': 'success',
                'message': message
            }
        except:
            api.abort(code=500, message='Error during system call')
예제 #3
0
    def post(self):
        """
        Create user
        """
        data = request.get_json()
        if User.query.filter_by(username=data['attributes']['username']).first():
            api.abort(code=409, message='User already exists')

        user = User()

        user.username = data['attributes']['username']
        user.name = data['attributes']['name']
        user.hash_password(data['attributes']['password'])

        if 'admin' in data['attributes'] and current_identity.admin:
            user.admin = data['attributes']['admin']
        if 'email' in data['attributes']:
            user.email = data['attributes']['email']

        try:
            user.groups = list(id['id'] for id in data[
                               'relationships']['groups']['data'])
        except KeyError:
            pass

        try:
            user.containers = list(id['id'] for id in data[
                                   'relationships']['containers']['data'])
        except KeyError:
            pass

        db.session.add(user)
        db.session.commit()

        return user.__jsonapi__(), 201
    def patch(cls, id):
        cart = models.Cart.query.get(id)
        data = _add_to_cart_parser.parse_args()
        product_id = data["product_id"]
        if not cart:
            return api.report(404, NOT_FOUND_ERROR.format(f"Cart {id}"))

        cartline = (
            models.CartLine.query.filter_by(cart_id=id)
            .filter_by(product_id=product_id)
            .first()
        )
        if cartline:
            cartline.quantity += 1
        else:
            product = models.Product.query.get(product_id)
            if not product:
                return api.abort(404, NOT_FOUND_ERROR.format(f"Product {product_id}"))
            cartline = models.CartLine()
            cartline.product = product
            cartline.cart = cart
            cartline.quantity = 1
        try:
            db.session.add(cart)
            db.session.commit()
        except Exception as ex:
            db.session.rollback()
            print(ex)
            return api.abort(500, ex)
        return cartline, 200
예제 #5
0
    def post(self):
        """
        Create user
        """
        current_identity = import_user()
        data = request.get_json()['data']
        if User.query.filter_by(
                username=data['attributes']['username']).first():
            api.abort(code=409, message='User already exists')

        user = User()

        user.username = data['attributes']['username']
        user.name = data['attributes']['name']
        user.hash_password(data['attributes']['password'])

        if 'admin' in data['attributes'] and current_identity.admin:
            user.admin = data['attributes']['admin']
        if 'email' in data['attributes']:
            user.email = data['attributes']['email']
        if 'phone' in data['attributes']:
            user.phone = data['attributes']['phone']
        if 'address' in data['attributes']:
            user.address = data['attributes']['address']
        if 'city' in data['attributes']:
            user.city = data['attributes']['city']
        if 'country' in data['attributes']:
            user.country = data['attributes']['country']
        if 'postal_code' in data['attributes']:
            user.postal_code = data['attributes']['postal_code']
        if 'ico' in data['attributes']:
            user.ico = data['attributes']['ico']
        if 'ic_dph' in data['attributes']:
            user.ic_dph = data['attributes']['ic_dph']
        if 'dic' in data['attributes']:
            user.dic = data['attributes']['dic']
        if 'language' in data['attributes']:
            user.language = data['attributes']['language']
        if 'otp_type' in data['attributes']:
            if data['attributes']['otp_type'] == 'none':
                user.otp_type = None
            else:
                user.otp_type = data['attributes']['otp_type']

        try:
            user.groups = list(
                id['id'] for id in data['relationships']['groups']['data'])
        except KeyError:
            pass

        try:
            user.containers = list(
                id['id'] for id in data['relationships']['containers']['data'])
        except KeyError:
            pass

        db.session.add(user)
        db.session.commit()

        return {'data': user.__jsonapi__()}, 201
예제 #6
0
    def get(self):
        """
        Get LXD config
        :return data
        """

        current_identity = import_user()

        data = {}

        if current_identity.admin:
            Config = configparser.ConfigParser()
            try:
                Config.read('lxdconfig.conf')
                data['endpoint'] = Config['remote']['endpoint']
                data['cert_crt'] = Config['remote']['cert_crt']
                data['cert_key'] = Config['remote']['cert_key']
                data['verify'] = Config['remote']['verify']

                data['sender'] = Config['smtp']['sender']
                data['recipient'] = Config['smtp']['recipient']
                data['server'] = Config['smtp']['server']
                data['port'] = Config['smtp']['port']
                data['login'] = Config['smtp']['login']
                data['password'] = Config['smtp']['password']

                data['production_name'] = Config['app']['production_name']
            except Exception as e:
                api.abort(code=404, message='Error when read config file.')

            return {'data': {'attributes': data}}

        api.abort(code=404, message='You has not admin privileges')
예제 #7
0
    def post(self):
        args = password_reset_post.parse_args()
        email = args['email']
        user = user_model.get_by_email(email)
        if user is None:
            api.abort(404, 'User not found')
        token = user.get_session_token(expiration=21600, password_reset=True)
        if mail.is_email_valid(config.get('mail_sender')):
            sender = config.get('mail_sender')
        else:
            app_id = app_identity.get_application_id()
            sender = "%s <noreply@%s.appspotmail.com>" % (app_id, app_id)
        try:
            message = mail.EmailMessage()
            message.sender = sender
            message.subject = 'Password reset request'
            message.to = email
            message.body = '''
You're receiving this email because you requested a password reset.
Visit the following page to reset your password:

%s?reset_token=%s
''' % (config.get('password_reset_url'), token)
            message.send()
        except:
            api.abort(500)
        return '', 200
예제 #8
0
    def post(self, group_id):
        """

        :param group_id:
        :return:
        """

        try:
            cards = json.loads(request.data)
            user = get_user()

            success = []

            for id in cards:
                card = db.Card.find_one({'_id': ObjectId(id)})
                if not card:
                    break

                card.is_studying = False
                card.save()

                self._add_to_training(user, card)
                success.append(id)
            return {
                'data': success
            }
        except Exception as ex:
            logger.error(ex.message)
            api.abort(500)
예제 #9
0
    def post(self, id):
        """
        Clone container
        """
        current_identity = import_user()
        data = request.get_json()['data']

        if 'name' in data['attributes']:
            container = Container.query.get(id)
            c = lxc.Container(container.name)

            if c.defined and (id in current_identity.containers or current_identity.admin):
                c2 = lxc.Container(data['attributes']['name'])
                if not c2.defined:
                    c2 = c.clone(data['attributes']['name'],
                                 flags=lxc.LXC_CLONE_MAYBE_SNAPSHOT)
                    if c2.defined:
                        # Add container to database
                        container = Container(name=data['attributes']['name'])
                        db.session.add(container)
                        db.session.commit()
                        # Get container ID
                        container = Container.query.filter_by(
                            name=data['attributes']['name']).first()
                        # Add container to allowed user's containers
                        user = User.query.get(current_identity.id)
                        user.containers.append(container.id)
                        db.session.commit()

                        return Containers.get(self, container.id), 201

            api.abort(code=404, message='Container doesn\'t exists')
예제 #10
0
    def put(self, id):
        """
        Update group
        """
        group = Group.query.get(id)

        if not group:
            api.abort(code=404, message='Group not found')

        data = request.get_json()['data']

        if 'name' in data['attributes']:
            group.name = data['attributes']['name']

        try:
            group.abilities = list(id['id'] for id in data[
                                   'relationships']['abilities']['data'])
        except KeyError:
            pass

        try:
            group.users = list(id['id'] for id in data[
                'relationships']['users']['data'])
        except KeyError:
            pass

        if len(data) > 0:
            db.session.commit()

        return {'data': group.__jsonapi__()}
예제 #11
0
 def post(self):
     args = login_post.parse_args()
     email = args['email']
     password = args['password']
     user = user_model.get_by_email(email)
     if user is None or not user.verify_password(password):
         api.abort(400, message='Wrong email or password')
     return user, 200
예제 #12
0
    def put(self, id):
        """
        Update user
        """
        current_identity = import_user()
        user = User.query.get(id)

        if not user:
            api.abort(code=404, message='User not found')

        data = request.get_json()['data']

        if 'admin' in data['attributes'] and current_identity.admin:
            user.admin = data['attributes']['admin']
        if 'name' in data['attributes']:
            user.name = data['attributes']['name']
        if 'email' in data['attributes']:
            user.email = data['attributes']['email']
        if 'phone' in data['attributes']:
            user.phone = data['attributes']['phone']
        if 'address' in data['attributes']:
            user.address = data['attributes']['address']
        if 'city' in data['attributes']:
            user.city = data['attributes']['city']
        if 'country' in data['attributes']:
            user.country = data['attributes']['country']
        if 'postal_code' in data['attributes']:
            user.postal_code = data['attributes']['postal_code']
        if 'ico' in data['attributes']:
            user.ico = data['attributes']['ico']
        if 'ic_dph' in data['attributes']:
            user.ic_dph = data['attributes']['ic_dph']
        if 'dic' in data['attributes']:
            user.dic = data['attributes']['dic']
        if 'language' in data['attributes']:
            user.language = data['attributes']['language']

        if 'password' in data['attributes'] and current_identity.admin:
            user.hash_password(data['attributes']['password'])

        try:
            user.groups = list(
                id['id'] for id in data['relationships']['groups']['data'])
        except KeyError:
            pass

        try:
            user.containers = list(
                id['id'] for id in data['relationships']['containers']['data'])
        except KeyError:
            pass

        if len(data) > 0:
            db.session.commit()

        return {'data': user.__jsonapi__()}
예제 #13
0
    def get(self, id):
        """
        Get user
        """
        user = User.query.get(id)

        if not user:
            api.abort(code=404, message='User not found')

        return {'data': user.__jsonapi__()}
예제 #14
0
    def get(self, id):
        """
        Get group
        """
        group = Group.query.get(id)

        if not group:
            api.abort(code=404, message='Group not found')

        return {'data': group.__jsonapi__()}
예제 #15
0
 def delete(self):
     """
     Revoke token
     """
     jti = get_raw_jwt()['jti']
     if not jti:
         api.abort(code=404, message='Token not found')
     redis_store.set('access_jti:' + jti, 'true',
                     app.config['ACCESS_TOKEN_EXPIRES'])
     return {"msg": "Access token revoked"}, 200
예제 #16
0
    def get(self, id):
        """
        Get ability
        """
        ability = Ability.query.get(id)

        if not ability:
            api.abort(code=404, message='Ability not found')

        return {'data': ability.__jsonapi__()}
예제 #17
0
    def put(self):
        """
        Update me
        """
        current_identity = import_user()
        user = User.query.get(current_identity.id)

        data = request.get_json()['data']

        if 'name' in data['attributes']:
            user.name = data['attributes']['name']
        if 'email' in data['attributes']:
            user.email = data['attributes']['email']
        if 'phone' in data['attributes']:
            user.phone = data['attributes']['phone']
        if 'address' in data['attributes']:
            user.address = data['attributes']['address']
        if 'city' in data['attributes']:
            user.city = data['attributes']['city']
        if 'country' in data['attributes']:
            user.country = data['attributes']['country']
        if 'postal_code' in data['attributes']:
            user.postal_code = data['attributes']['postal_code']
        if 'ico' in data['attributes']:
            user.ico = data['attributes']['ico']
        if 'ic_dph' in data['attributes']:
            user.ic_dph = data['attributes']['ic_dph']
        if 'dic' in data['attributes']:
            user.dic = data['attributes']['dic']
        if 'langugage' in data['attributes']:
            user.language = data['attributes']['language']
        if 'otp_type' in data['attributes']:
            if data['attributes']['otp_type'] == 'none':
                user.otp_type = None
            else:
                user.otp_type = data['attributes']['otp_type']

        if 'cur_password' in data['attributes']:
            cur_password = data['attributes']['cur_password']
            #print('before verify')
            #print(data['attributes'])
            if 'new_password' in data['attributes'] and user.verify_password(
                    cur_password):
                if data['attributes']['new_password'] == data['attributes'][
                        'confirm_password']:
                    user.hash_password(data['attributes']['new_password'])
            else:
                api.abort(code=401, message='Incorrect user or password')

        # Not secure for user to change his group or container

        if len(data) > 0:
            db.session.commit()

        return {'data': user.__jsonapi__()}
예제 #18
0
 def post(self):
     args = password_confirm_post.parse_args()
     token = args['reset_token']
     password = args['password']
     valid, data = user_model.verify_session_token(token)
     if not valid or not data.get('password_reset'):
         api.abort(400, 'Reset token is invalid')
     user = user_model.get_by_id(data.get('user_id'))
     user.set_password(password)
     user.put()
     return '', 200
예제 #19
0
    def get(self, id):
        """
        Get user
        """
        populate_containers_table()
        user = User.query.get(id)

        if not user:
            api.abort(code=404, message='User not found')

        return {'data': user.__jsonapi__()}
예제 #20
0
    def fetchByUserId(self, phone_num):

        user = User.query.filter_by(username=phone_num).first()
        if user is None:
            return {"error": "User cannot be found"}, 404

        complaints = Complaint.query.filter_by(user_id=user.id)
        if complaints:
            return complaints_schema.jsonify(complaints)
        else:
            api.abort(404,
                      "Complaint by user {} doesn't exist".format(phone_num))
예제 #21
0
    def post(self):
        """
        returns a booking

        [terms of use](https://www.bahn.de/p/view/home/agb/nutzungsbedingungen.shtml)
        """
        booking = Buchung(api.payload.get('referenceNumber'),
                          api.payload.get('lastName'))
        if booking.valid:
            return booking
        else:
            api.abort(404, error='booking not found', payload=api.payload)
예제 #22
0
 def get(self, auftragsnummer):
     """
     returns an itinerary
     
     [terms of use](https://www.bahn.de/p/view/home/agb/nutzungsbedingungen.shtml)
     """
     try:
         return Reiseplan(auftragsnummer)
     except ValueError:
         api.abort(404,
                   error='itinerary not found',
                   referenceNumber=auftragsnummer)
예제 #23
0
 def log_workout(self, workout_dict):
     user = DB.find_one("users", {"username": self.username})
     if not user:
         api.abort(404, "User {} not found".format(self.username))
     # update workout history
     hist = user['history'].append(workout_dict['id'])
     # update entry in DB
     DB.update("users", {"username": self.username},
               {"$set": {
                   "history": hist
               }})
     DB.insert("workouts", workout_dict)
     self.history = hist
예제 #24
0
    def delete(self, id):
        """
        Delete user
        """
        user = User.query.get(id)

        if not user:
            api.abort(code=404, message='User not found')

        db.session.delete(user)
        db.session.commit()

        return {}, 204
예제 #25
0
    def delete(self, id):
        """
        Delete group
        """
        group = Group.query.get(id)

        if not group:
            api.abort(code=404, message='Group not found')

        db.session.delete(group)
        db.session.commit()

        return {}, 204
예제 #26
0
    def get(self, id):
        """
        Get container
        """
        container = Container.query.get(id)
        c = lxc.Container(container.name)

        if c.defined and (id in current_identity.containers or current_identity.admin):
            infos = lwp.ct_infos(container.name)
            container_json = container.__jsonapi__()
            container_json['attributes'] = infos

            return container_json
        api.abort(code=404, message='Container doesn\'t exists')
예제 #27
0
    def post(self, id):
        """
        Restart container
        """
        container = Container.query.get(id)
        c = lxc.Container(container.name)

        if c.defined and (id in current_identity.containers or current_identity.admin):
            try:
                if ContainersStop.post(self, id)[1] == 204 and ContainersStart.post(self, id)[1] == 204:
                    return {}, 204
            except KeyError:
                api.abort(code=500, message='Unknown error')

        api.abort(code=404, message='Container doesn\'t exists')
예제 #28
0
    def post(self, id):
        """
        Shutdown container
        """
        container = Container.query.get(id)
        c = lxc.Container(container.name)

        if c.defined and (id in current_identity.containers or current_identity.admin):
            c.shutdown(10)
            if c.wait('STOPPED', 30):
                return {}, 204
            else:
                api.abort(code=500, message='Shutdown timed out')

        api.abort(code=404, message='Container doesn\'t exists')
예제 #29
0
    def get(self, id):
        """
        Get group
        """
        group = Group.query.get(id)

        current_identity = import_user()

        if not group:
            api.abort(code=404, message='Group not found')

        if id in current_identity.groups or current_identity.admin:
            return {'data': group.__jsonapi__()}
        else:
            api.abort(code=403, message='You do not have access')
예제 #30
0
 def put(self, object_id):
     user = user_model.get_or_404(object_id, message='User not found')
     if g.user != user and not g.user.admin:
         api.abort(403)
     args = users_put.parse_args()
     email = args['email']
     password = args['password']
     if email is not None and user.email != email:
         if user_model.get_by_email(email) is not None:
             api.abort(400, 'Email is already registered')
         user.email = email
     if password is not None:
         user.set_password(password)
     user.put()
     return '', 200
예제 #31
0
    def post(self, id):
        """
        Unfreeze container
        """
        container = Container.query.get(id)
        c = lxc.Container(container.name)

        if c.defined and (id in current_identity.containers or current_identity.admin):
            c.unfreeze()
            if c.wait('RUNNING', 30):
                return {}, 204
            else:
                api.abort(code=500, message='Unfreeze timed out')

        api.abort(code=404, message='Container doesn\'t exists')
예제 #32
0
    def post(self):
        """
        Get Json Web Token
        """
        request_data = request.get_json()
        username = request_data['username']
        password = request_data['password']

        user = User.query.filter_by(username=username).first()

        if not user or not user.verify_password(password):
            api.abort(code=401, message='Incorrect user or password')

        ret = {'access_token': create_access_token(identity=user)}
        return ret
예제 #33
0
    def get(self, id):
        """
        Get container
        """
        current_identity = import_user()
        container = Container.query.get(id)
        c = lxc.Container(container.name)

        if c.defined and (id in current_identity.containers or current_identity.admin):
            infos = lwp.ct_infos(container.name)
            container_json = container.__jsonapi__()
            container_json['attributes'] = infos

            return {'data': container_json}
        api.abort(code=404, message='Container doesn\'t exists')
예제 #34
0
    def post(self, id):
        """
        Shutdown container
        """
        current_identity = import_user()
        container = Container.query.get(id)
        c = lxc.Container(container.name)

        if c.defined and (id in current_identity.containers or current_identity.admin):
            c.shutdown(30)
            if c.wait('STOPPED', 30):
                return {}, 204
            else:
                api.abort(code=500, message='Shutdown timed out')

        api.abort(code=404, message='Container doesn\'t exists')
예제 #35
0
    def post(self, id):
        """
        Unfreeze container
        """
        current_identity = import_user()
        container = Container.query.get(id)
        c = lxc.Container(container.name)

        if c.defined and (id in current_identity.containers or current_identity.admin):
            c.unfreeze()
            if c.wait('RUNNING', 30):
                return {}, 204
            else:
                api.abort(code=500, message='Unfreeze timed out')

        api.abort(code=404, message='Container doesn\'t exists')
예제 #36
0
        def set_config(container, config_item, config_value):
            if container.set_config_item(config_item, config_value):
                container.save_config()

                # python-lxc workaround (issue #1415 on lxc/lxc)
                f = open(container.config_file_name, "r")
                lines = f.readlines()
                f.close()
                f = open(container.config_file_name, "w")
                for line in lines:
                    if not line.endswith(' = \n'):
                        f.write(line)
                f.close()
            else:
                api.abort(
                    code=500, message='Error while setting container\'s parameter')
예제 #37
0
    def post(self, id):
        """
        Restart container
        """
        current_identity = import_user()
        container = Container.query.get(id)
        c = lxc.Container(container.name)

        if c.defined and (id in current_identity.containers or current_identity.admin):
            try:
                if ContainersStop.post(self, id)[1] == 204 and ContainersStart.post(self, id)[1] == 204:
                    return {}, 204
            except KeyError:
                api.abort(code=500, message='Unknown error')

        api.abort(code=404, message='Container doesn\'t exists')
    def post(cls):
        data = _merge_carts_parser.parse_args()
        from_cart_id = data.get("from_cart_id")
        to_cart_id = data.get("to_cart_id")
        user_id = data.get("user_id")
        from_cart = (
            models.Cart.query.filter_by(status=models.Cart.CartStatus.OPEN)
            .filter_by(id=from_cart_id)
            .first()
        )
        to_cart = (
            models.Cart.query.filter_by(status=models.Cart.CartStatus.OPEN)
            .filter_by(id=to_cart_id)
            .first()
        )
        user = models.User.query.filter_by(id=user_id).filter_by(active=True).first()

        if not from_cart:
            return api.abort(404, NOT_FOUND_ERROR.format("From cart"))

        if not user:
            return api.abort(404, NOT_FOUND_ERROR.format(f"User {user_id}"))

        if not to_cart:
            to_cart = from_cart
            to_cart.user = user
            db.session.add(to_cart)
        else:
            for line in from_cart.cart_lines:
                final_cart_line = (
                    models.CartLine.query.filter_by(cart_id=to_cart_id)
                    .filter_by(product_id=line.product_id)
                    .first()
                )
                if not final_cart_line:
                    final_cart_line = line
                    final_cart_line.cart = to_cart
                else:
                    final_cart_line.quantity += line.quantity
                db.session.add(final_cart_line)

        try:
            db.session.commit()
        except Exception as ex:
            db.session.rollback()
            return api.abort(500, ex)
        return to_cart, 200
    def post(cls):
        data = api.payload

        new_order = models.Order()
        if data["cart_id"] > 0:
            cart_id = data["cart_id"]
            cart = models.Cart.query.get(cart_id)
            if cart:
                for cartline in cart.cart_lines:
                    new_orderline = models.OrderLine()
                    new_orderline.order = new_order
                    new_orderline.product_id = cartline.product_id
                    new_orderline.quantity = cartline.quantity
                    db.session.add(new_orderline)

            if data["user_id"] > 0:
                user_id = data["user_id"]
                user = models.User.query.get(user_id)
                if user:
                    new_order.user = user

            new_order.billing_address1 = data["billing_address1"]
            new_order.billing_address2 = data["billing_address2"]
            new_order.billing_city = data["billing_city"]
            new_order.billing_state = data["billing_state"]
            new_order.billing_zip = data["billing_zip"]
            new_order.shipping_address1 = data["shipping_address1"]
            new_order.shipping_address2 = data["shipping_address2"]
            new_order.shipping_city = data["shipping_city"]
            new_order.shipping_state = data["shipping_state"]
            new_order.shipping_zip = data["shipping_zip"]
            new_order.contact = data["contact"]
            new_order.date_created = datetime.now()
            cart.status = models.Cart.CartStatus.CLOSE
        else:
            return api.abort(400)

        try:
            db.session.add(new_order)
            db.session.add(cart)
            db.session.commit()
        except Exception as ex:
            db.session.rollback()
            return api.abort(500, ex)
        return {"order_id": new_order.id}, 200
예제 #40
0
    def post(self):
        """
        Create container
        """
        current_identity = import_user()
        data = request.get_json()['data']

        if 'name' in data['attributes']:
            c = lxc.Container(data['attributes']['name'])
            if not c.defined:
                try:
                    if not isinstance(data['attributes']['template']['args'], str):
                        data['attributes']['template']['args'] = ''
                except KeyError:
                    data['attributes']['template']['args'] = ''
                if not c.create(
                    template=data['attributes']['template']['name'],
                    flags=lxc.LXC_CREATE_QUIET,
                    args=data['attributes']['template']['args'],
                    bdevtype=None
                ):
                    api.abort(code=500, message='Can\'t create container')

                # Add container to database
                container = Container(name=data['attributes']['name'])
                db.session.add(container)
                db.session.commit()
                # Get container ID
                container = Container.query.filter_by(
                    name=data['attributes']['name']).first()
                # Add container to allowed user's containers
                user = User.query.get(current_identity.id)
                user.containers.append(container.id)
                db.session.commit()

                return Containers.put(self, container.id, d=data), 201
            api.abort(code=409, message='Container already exists')
예제 #41
0
    def put(self, id):
        """
        Update user
        """
        current_identity = import_user()
        user = User.query.get(id)

        if not user:
            api.abort(code=404, message='User not found')

        data = request.get_json()['data']

        if 'name' in data['attributes']:
            user.name = data['attributes']['name']
        if 'admin' in data['attributes'] and current_identity.admin:
            user.admin = data['attributes']['admin']
        if 'email' in data['attributes']:
            user.email = data['attributes']['email']
        if 'password' in data['attributes']:
            user.hash_password(data['attributes']['password'])

        try:
            user.groups = list(id['id'] for id in data[
                               'relationships']['groups']['data'])
        except KeyError:
            pass

        try:
            user.containers = list(id['id'] for id in data[
                                   'relationships']['containers']['data'])
        except KeyError:
            pass

        if len(data) > 0:
            db.session.commit()

        return {'data': user.__jsonapi__()}
예제 #42
0
    def post(self):
        """
        Create user
        """
        current_identity = import_user()
        data = request.get_json()['data']
        if User.query.filter_by(username=data['attributes']['username']).first():
            api.abort(code=409, message='User already exists')

        user = User()

        user.username = data['attributes']['username']
        user.name = data['attributes']['name']
        user.hash_password(data['attributes']['password'])

        if 'admin' in data['attributes'] and current_identity.admin:
            user.admin = data['attributes']['admin']
        if 'email' in data['attributes']:
            user.email = data['attributes']['email']

        try:
            user.groups = list(id['id'] for id in data[
                               'relationships']['groups']['data'])
        except KeyError:
            pass

        try:
            user.containers = list(id['id'] for id in data[
                                   'relationships']['containers']['data'])
        except KeyError:
            pass

        db.session.add(user)
        db.session.commit()

        return {'data': user.__jsonapi__()}, 201
예제 #43
0
    def delete(self, id):
        """
        Destroy container
        """
        current_identity = import_user()
        container = Container.query.get(id)
        c = lxc.Container(container.name)

        if c.defined and (id in current_identity.containers or current_identity.admin):
            if c.running:
                if not c.stop():
                    api.abort(
                        code=409, message='Can\'t destroy and/or stop container')
            if not c.destroy():
                api.abort(
                    code=409, message='Can\'t destroy and/or stop container')
            return {}, 204
        api.abort(code=404, message='Container doesn\'t exists')
예제 #44
0
 def decorated_view(*args, **kwargs):
     if g.user is None:
         api.abort(401)
     return func(*args, **kwargs)
예제 #45
0
    def put(self, id, d=None):
        """
        Update container
        """
        def set_config(container, config_item, config_value):
            if container.set_config_item(config_item, config_value):
                container.save_config()

                # python-lxc workaround (issue #1415 on lxc/lxc)
                f = open(container.config_file_name, "r")
                lines = f.readlines()
                f.close()
                f = open(container.config_file_name, "w")
                for line in lines:
                    if not line.endswith(' = \n'):
                        f.write(line)
                f.close()
            else:
                api.abort(
                    code=500, message='Error while setting container\'s parameter')

        # Get data from ContainersList.post()
        # or
        # from Containers.put()
        if d:
            data = d
        else:
            data = request.get_json()['data']

        current_identity = import_user()
        container = Container.query.get(id)

        c = lxc.Container(container.name)

        if c.defined and (id in current_identity.containers or current_identity.admin):
            if 'name' in data['attributes']:
                if data['attributes']['name'] != c.name:
                    if c.rename(data['attributes']['name']):
                        c = lxc.Container(data['attributes']['name'])
                    else:
                        api.abort(
                            code=500, message='Error while instantiate container')

            if 'lxc' in data['attributes']:
                if 'aa_allow_incomplete' in data['attributes']['lxc']:
                    set_config(c, 'lxc.aa_allow_incomplete', data['attributes'][
                               'lxc']['aa_allow_incomplete'])
                if 'aa_profile' in data['attributes']['lxc']:
                    set_config(c, 'lxc.aa_profile', data[
                               'attributes']['lxc']['aa_profile'])
                if 'arch' in data['attributes']['lxc']:
                    set_config(c, 'lxc.arch', data[
                               'attributes']['lxc']['arch'])
                if 'autodev' in data['attributes']['lxc']:
                    set_config(c, 'lxc.autodev', data[
                               'attributes']['lxc']['autodev'])
                if 'cap' in data['attributes']['lxc']:
                    if 'drop' in data['attributes']['lxc']['cap']:
                        set_config(c, 'lxc.cap.drop', data['attributes'][
                                   'lxc']['cap']['drop'])
                    if 'keep' in data['attributes']['lxc']['cap']:
                        set_config(c, 'lxc.cap.keep', data['attributes'][
                                   'lxc']['cap']['keep'])
                if 'cgroup' in data['attributes']['lxc']:
                    if 'memory' in data['attributes']['lxc']['cgroup']:
                        if 'limit_in_bytes' in data['attributes']['lxc']['cgroup']['memory']:
                            set_config(c, 'lxc.cgroup.memory.limit_in_bytes', data['attributes'][
                                       'lxc']['cgroup']['memory']['limit_in_bytes'])
                        if 'memsw' in data['attributes']['lxc']['cgroup']['memory']:
                            if 'limit_in_bytes' in data['attributes']['lxc']['cgroup']['memory']['memsw']:
                                set_config(c, 'lxc.cgroup.memory.memsw.limit_in_bytes', data['attributes'][
                                           'lxc']['cgroup']['memory']['memsw']['limit_in_bytes'])
                    if 'cpu' in data['attributes']['lxc']['cgroup']:
                        if 'shares' in data['attributes']['lxc']['cgroup']['cpu']:
                            set_config(c, 'lxc.cgroup.cpu.shares', data['attributes'][
                                       'lxc']['cgroup']['cpu']['shares'])
                    if 'cpuset' in data['attributes']['lxc']['cgroup']:
                        if 'cpus' in data['attributes']['lxc']['cgroup']['cpuset']:
                            set_config(c, 'lxc.cgroup.cpuset.cpus', data['attributes'][
                                       'lxc']['cgroup']['cpuset']['cpus'])
                if 'console' in data['attributes']['lxc']:
                    if '_' in data['attributes']['lxc']['console']:
                        set_config(c, 'lxc.console', data['attributes'][
                                   'lxc']['console']['_'])
                    if 'logfile' in data['attributes']['lxc']['console']:
                        set_config(c, 'lxc.console.logfile', data['attributes'][
                                   'lxc']['console']['logfile'])
                if 'devttydir' in data['attributes']['lxc']:
                    set_config(c, 'lxc.devttydir', data[
                               'attributes']['lxc']['devttydir'])
                if 'environment' in data['attributes']['lxc']:
                    set_config(c, 'lxc.environment', data['attributes'][
                               'lxc']['environment'])
                if 'ephemeral' in data['attributes']['lxc']:
                    set_config(c, 'lxc.ephemeral', data[
                               'attributes']['lxc']['ephemeral'])
                if 'group' in data['attributes']['lxc']:
                    set_config(c, 'lxc.group', data[
                               'attributes']['lxc']['group'])
                if 'haltsignal' in data['attributes']['lxc']:
                    set_config(c, 'lxc.haltsignal', data[
                               'attributes']['lxc']['haltsignal'])
                if 'hook' in data['attributes']['lxc']:
                    if 'autodev' in data['attributes']['lxc']['hook']:
                        set_config(c, 'lxc.hook.autodev', data['attributes'][
                                   'lxc']['hook']['autodev'])
                    if 'clone' in data['attributes']['lxc']['hook']:
                        set_config(c, 'lxc.hook.clone', data['attributes'][
                                   'lxc']['hook']['clone'])
                    if 'destroy' in data['attributes']['lxc']['hook']:
                        set_config(c, 'lxc.hook.destroy', data['attributes'][
                                   'lxc']['hook']['destroy'])
                    if 'mount' in data['attributes']['lxc']['hook']:
                        set_config(c, 'lxc.hook.mount', data['attributes'][
                                   'lxc']['hook']['mount'])
                    if 'post-stop' in data['attributes']['lxc']['hook']:
                        set_config(c, 'lxc.hook.post-stop',
                                   data['attributes']['lxc']['hook']['post-stop'])
                    if 'pre-mount' in data['attributes']['lxc']['hook']:
                        set_config(c, 'lxc.hook.pre-mount',
                                   data['attributes']['lxc']['hook']['pre-mount'])
                    if 'pre-start' in data['attributes']['lxc']['hook']:
                        set_config(c, 'lxc.hook.pre-start',
                                   data['attributes']['lxc']['hook']['pre-start'])
                    if 'start' in data['attributes']['lxc']['hook']:
                        set_config(c, 'lxc.hook.start', data['attributes'][
                                   'lxc']['hook']['start'])
                    if 'stop' in data['attributes']['lxc']['hook']:
                        set_config(c, 'lxc.hook.stop', data['attributes'][
                                   'lxc']['hook']['stop'])
                if 'id_map' in data['attributes']['lxc']:
                    set_config(c, 'lxc.id_map', data[
                               'attributes']['lxc']['id_map'])
                if 'include' in data['attributes']['lxc']:
                    set_config(c, 'lxc.include', data[
                               'attributes']['lxc']['include'])
                if 'init_cmd' in data['attributes']['lxc']:
                    set_config(c, 'lxc.init_cmd', data[
                               'attributes']['lxc']['init_cmd'])
                if 'init_gid' in data['attributes']['lxc']:
                    set_config(c, 'lxc.init_gid', data[
                               'attributes']['lxc']['init_gid'])
                if 'init_uid' in data['attributes']['lxc']:
                    set_config(c, 'lxc.init_uid', data[
                               'attributes']['lxc']['init_uid'])
                if 'kmsg' in data['attributes']['lxc']:
                    set_config(c, 'lxc.kmsg', data[
                               'attributes']['lxc']['kmsg'])
                if 'logfile' in data['attributes']['lxc']:
                    set_config(c, 'lxc.logfile', data[
                               'attributes']['lxc']['logfile'])
                if 'loglevel' in data['attributes']['lxc']:
                    set_config(c, 'lxc.loglevel', data[
                               'attributes']['lxc']['loglevel'])
                if 'monitor' in data['attributes']['lxc']:
                    if 'unshare' in data['attributes']['lxc']['monitor']:
                        set_config(c, 'lxc.monitor.unshare', data['attributes'][
                                   'lxc']['monitor']['unshare'])
                if 'mount' in data['attributes']['lxc']:
                    if '_' in data['attributes']['lxc']['mount']:
                        set_config(c, 'lxc.mount', data[
                                   'attributes']['lxc']['mount']['_'])
                    if 'auto' in data['attributes']['lxc']['mount']:
                        set_config(c, 'lxc.mount.auto', data['attributes'][
                                   'lxc']['mount']['auto'])
                    if 'entry' in data['attributes']['lxc']['mount']:
                        set_config(c, 'lxc.mount.entry', data['attributes'][
                                   'lxc']['mount']['entry'])
                if 'network' in data['attributes']['lxc']:
                    for i in range(len(data['attributes']['lxc']['network'])):
                        if 'type' in data['attributes']['lxc']['network'][i]:
                            set_config(c, 'lxc.network.%s.type' %
                                       i, data['attributes']['lxc']['network'][i]['type'])
                        if 'veth' in data['attributes']['lxc']['network'][i]:
                            if 'pair' in data['attributes']['lxc']['network'][i]['veth']:
                                set_config(c, 'lxc.network.%s.veth.pair' %
                                           i, data['attributes']['lxc']['network'][i]['veth']['pair'])
                        if 'vlan' in data['attributes']['lxc']['network'][i]:
                            if 'id' in data['attributes']['lxc']['network'][i]['vlan']:
                                set_config(c, 'lxc.network.%s.vlan.id' %
                                           i, data['attributes']['lxc']['network'][i]['vlan']['id'])
                        if 'macvlan' in data['attributes']['lxc']['network'][i]:
                            if 'mode' in data['attributes']['lxc']['network'][i]['macvlan']:
                                set_config(c, 'lxc.network.%s.macvlan.mode' % i, data['attributes'][
                                           'lxc']['network'][i]['macvlan']['mode'])
                        if 'flags' in data['attributes']['lxc']['network'][i]:
                            set_config(c, 'lxc.network.%s.flags' %
                                       i, data['attributes']['lxc']['network'][i]['flags'])
                        if 'link' in data['attributes']['lxc']['network'][i]:
                            set_config(c, 'lxc.network.%s.link' %
                                       i, data['attributes']['lxc']['network'][i]['link'])
                        if 'mtu' in data['attributes']['lxc']['network'][i]:
                            set_config(c, 'lxc.network.%s.mtu' %
                                       i, data['attributes']['lxc']['network'][i]['mtu'])
                        if 'name' in data['attributes']['lxc']['network'][i]:
                            set_config(c, 'lxc.network.%s.name' %
                                       i, data['attributes']['lxc']['network'][i]['name'])
                        if 'hwaddr' in data['attributes']['lxc']['network'][i]:
                            set_config(c, 'lxc.network.%s.hwaddr' %
                                       i, data['attributes']['lxc']['network'][i]['hwaddr'])
                        if 'ipv4' in data['attributes']['lxc']['network'][i]:
                            if '_' in data['attributes']['lxc']['network'][i]['ipv4']:
                                set_config(c, 'lxc.network.%s.ipv4' %
                                           i, data['attributes']['lxc']['network'][i]['ipv4']['_'])

                            if 'gateway' in data['attributes']['lxc']['network'][i]['ipv4']:
                                set_config(c, 'lxc.network.%s.ipv4.gateway' % i, data['attributes'][
                                           'lxc']['network'][i]['ipv4']['gateway'])
                        if 'ipv6' in data['attributes']['lxc']['network'][i]:
                            if '_' in data['attributes']['lxc']['network'][i]['ipv6']:
                                set_config(c, 'lxc.network.%s.ipv6' %
                                           i, data['attributes']['lxc']['network'][i]['ipv6']['_'])
                            if 'gateway' in data['attributes']['lxc']['network'][i]['ipv6']:
                                set_config(c, 'lxc.network.%s.ipv6.gateway' % i, data['attributes'][
                                           'lxc']['network'][i]['ipv6']['gateway'])
                        if 'script' in data['attributes']['lxc']['network'][i]:
                            if 'up' in data['attributes']['lxc']['network'][i]['script']:
                                set_config(c, 'lxc.network.%s.script.up' %
                                           i, data['attributes']['lxc']['network'][i]['script']['up'])
                            if 'down' in data['attributes']['lxc']['network'][i]['script']:
                                set_config(c, 'lxc.network.%s.script.down' % i, data['attributes'][
                                           'lxc']['network'][i]['script']['down'])
                if 'no_new_privs' in data['attributes']['lxc']:
                    set_config(c, 'lxc.no_new_privs', data['attributes'][
                               'lxc']['no_new_privs'])
                if 'pts' in data['attributes']['lxc']:
                    set_config(c, 'lxc.pts', data['attributes']['lxc']['pts'])
                if 'rebootsignal' in data['attributes']['lxc']:
                    set_config(c, 'lxc.rebootsignal', data['attributes'][
                               'lxc']['rebootsignal'])
                if 'rootfs' in data['attributes']['lxc']:
                    if '_' in data['attributes']['lxc']['rootfs']:
                        set_config(c, 'lxc.rootfs', data[
                                   'attributes']['lxc']['rootfs']['_'])
                    if 'mount' in data['attributes']['lxc']['rootfs']:
                        set_config(c, 'lxc.rootfs.mount', data['attributes'][
                                   'lxc']['rootfs']['mount'])
                    if 'options' in data['attributes']['lxc']['rootfs']:
                        set_config(c, 'lxc.rootfs.options', data['attributes'][
                                   'lxc']['rootfs']['options'])
                    if 'backend' in data['attributes']['lxc']['rootfs']:
                        set_config(c, 'lxc.rootfs.backend', data['attributes'][
                                   'lxc']['rootfs']['backend'])
                if 'se_context' in data['attributes']['lxc']:
                    set_config(c, 'lxc.se_context', data[
                               'attributes']['lxc']['se_context'])
                if 'seccomp' in data['attributes']['lxc']:
                    set_config(c, 'lxc.seccomp', data[
                               'attributes']['lxc']['seccomp'])
                if 'start' in data['attributes']['lxc']:
                    if 'auto' in data['attributes']['lxc']['start']:
                        set_config(c, 'lxc.start.auto', data['attributes'][
                                   'lxc']['start']['auto'])
                    if 'delay' in data['attributes']['lxc']['start']:
                        set_config(c, 'lxc.start.delay', data['attributes'][
                                   'lxc']['start']['delay'])
                    if 'order' in data['attributes']['lxc']['start']:
                        set_config(c, 'lxc.start.order', data['attributes'][
                                   'lxc']['start']['order'])
                if 'stopsignal' in data['attributes']['lxc']:
                    set_config(c, 'lxc.stopsignal', data[
                               'attributes']['lxc']['stopsignal'])
                if 'syslog' in data['attributes']['lxc']:
                    set_config(c, 'lxc.syslog', data[
                               'attributes']['lxc']['syslog'])
                if 'tty' in data['attributes']['lxc']:
                    set_config(c, 'lxc.tty', data['attributes']['lxc']['tty'])
                if 'utsname' in data['attributes']['lxc']:
                    set_config(c, 'lxc.utsname', data[
                               'attributes']['lxc']['utsname'])

            return Containers.get(self, container.id)
        api.abort(code=404, message='Container doesn\'t exists')
예제 #46
0
 def get_or_404(cls, id, message=None):
 	obj = cls.get_by_id(id)
 	if obj is None:
 		api.abort(404, message)
 	return obj
예제 #47
0
 def delete(self, object_id):
     user = user_model.get_or_404(object_id, message='User not found')
     if g.user != user and not g.user.admin:
         api.abort(403)
     user.key.delete()
     return '', 204