Beispiel #1
0
 def get(self, user_id):
     """Get user details"""
     try:
         user = User.get(id=user_id)
     except User.DoesNotExist:
         abort(404, message='User not found')
     return user
Beispiel #2
0
    def get(self, import_id, citizen_id):
        citizen = Citizen.query.get((citizen_id, import_id))

        if not citizen:
            abort(HTTPStatus.BAD_REQUEST)
        
        return citizen
Beispiel #3
0
    def patch(self, import_id, citizen_id):

        #TODO Проверять, существуют ли указанные relatives

        update_data = request.json
        update_data["import_id"] = import_id
        update_data["citizen_id"] = citizen_id

        if "relatives" in update_data:
            for id in update_data["relatives"]:
                item = Citizen.query.get((id, import_id))
                if not item:
                    abort(HTTPStatus.BAD_REQUEST)

        update_data = CitizenPatchSchema().load(update_data)

        citizen = Citizen.query.get((citizen_id, import_id))

        has_changes = False

        for field_name in ["name", "gender", "birth_date", "as_left_edges", "as_right_edges", "town", "street", "building", "apartment"]:
            if hasattr(update_data, field_name):
                has_changes = True
                setattr(citizen, field_name, getattr(update_data, field_name))
        
        if not has_changes:
            abort(HTTPStatus.BAD_REQUEST)

        db.session.commit()
        return citizen
Beispiel #4
0
    def get(self, import_id):
        import_instance = Import.query.get(import_id)

        if not import_instance:
            abort(HTTPStatus.BAD_REQUEST)
        
        data = {
            "1":[],
            "2":[],
            "3":[],
            "4":[],
            "5":[],
            "6":[],
            "7":[],
            "8":[],
            "9":[],
            "10":[],
            "11":[],
            "12":[]
        }


        for citizen in import_instance.citizens:
            birth_month = str(citizen.birth_date.month)
            presents = len(citizen.as_left_edges) + len(citizen.as_right_edges)
            data[birth_month].append({"citizen_id": citizen.citizen_id, "presents": presents})
        
        return jsonify({
            "data": data
        })
Beispiel #5
0
 def get(self):
     """Get user details"""
     try:
         user = User.get(email=get_jwt_identity())
     except User.DoesNotExist:
         abort(404, message='User not found')
     return user
Beispiel #6
0
 def delete(self, user_id):
     try:
         user = User.get(id=user_id)
     except User.DoesNotExist:
         abort(404, message='User not found')
     user.delete_instance()
     return user
Beispiel #7
0
    def get(self, import_id):
        import_instance = Import.query.get(import_id)

        if not import_instance:
            abort(HTTPStatus.BAD_REQUEST)
        
        return import_instance.citizens
Beispiel #8
0
    def get(self, pk) -> BaseQuery:
        if not self.get_enabled:
            abort(405)

        item = self._lookup(pk)
        self._check_can_read(item)

        return item
Beispiel #9
0
 def delete(self, role_id):
     """Remove role"""
     try:
         role = Role.get(id=role_id)
     except Role.DoesNotExist:
         abort(404, message='Role not found')
     role.delete_instance()
     return role
Beispiel #10
0
 def get(self, role_id):
     """Get role details"""
     try:
         role = Role.get(id=role_id)
     except Role.DoesNotExist:
         abort(404, message='Role not found')
     role.users = [user.user for user in role.users]
     return role
Beispiel #11
0
    def delete(self, pk) -> BaseQuery:
        if not self.delete_enabled:
            abort(405)

        item = self._lookup(pk)
        self._check_can_write(item)

        self._db.session.delete(item)
        self._db.session.commit()
Beispiel #12
0
 def get(self, id):
     """Get information on workflow by workflow id"""
     try:
         return db.session.query(WorkflowExecution)\
             .filter(WorkflowExecution.fargateTaskArn==id)\
             .filter(WorkflowExecution.workgroup.in_(get_jwt_groups()))\
             .one()
     except sqlalchemy.orm.exc.NoResultFound:
         abort(404)
Beispiel #13
0
    def get(self, category_id):
        """
        Get category by id
        """
        category = Category.query.get(category_id)
        if not category:
            abort(404, message='Category not found')

        return category
Beispiel #14
0
    def get(self) -> BaseQuery:
        """List collection."""
        if not self.list_enabled:
            abort(405)

        query = self.query_for_user()

        query = self._add_prefetch(query)

        return query
Beispiel #15
0
 def patch(self, args, role_id):
     """Edit role"""
     try:
         role = Role.get(id=role_id)
     except Role.DoesNotExist:
         abort(404, message='Role not found')
     for field in args:
         setattr(role, field, args[field])
     role.save()
     return role
Beispiel #16
0
    def get(self, import_id):
        import_instance = Import.query.get(import_id)

        if not import_instance:
            abort(HTTPStatus.BAD_REQUEST)
        
        towns = {}

        for citizen in import_instance.citizens:
            if citizen.town in towns: 
                towns[citizen.town].append(citizen)
            else:
                towns[citizen.town] = [citizen]
        
        data = []
        now = datetime.utcnow()

        for town, citizens in towns.items():

            ages = []

            for citizen in citizens:
                yearsdelta = now.year - citizen.birth_date.year
                monthdelta = now.month - citizen.birth_date.month
                daysdelta = now.day - citizen.birth_date.day

                age = 0

                if now.month > citizen.birth_date.month:
                    age = yearsdelta
                elif now.month < citizen.birth_date.month:
                    age = yearsdelta - 1
                elif now.day >= citizen.birth_date.day:
                    age = yearsdelta
                else:
                    age = yearsdelta - 1
                
                ages.append(age)

            p50 = percentile(ages, 50) 
            p75 = percentile(ages, 75)
            p99 = percentile(ages, 99)

            data.append({
                "town": town,
                "p50": p50,
                "p75": p75,
                "p99": p99
            })
            
            ages = []
        
        return jsonify({
            "data": data
        })
Beispiel #17
0
 def patch(self, args, user_id):
     try:
         user = User.get(id=user_id)
     except User.DoesNotExist:
         abort(404, message='User not found')
     for field in args:
         setattr(user, field, args[field])
     if 'password' in args:
         user.password = hash_password(user.password)
     user.save()
     return user
Beispiel #18
0
    def get(self, product_id):
        """
        Get product by id
        """
        product = Product.query.get(product_id)
        if not product:
            abort(404, message='Product not found')
        product.views += 1
        db.session.commit()

        return product
Beispiel #19
0
    def delete(self, category_id):
        """
        Delete empty category
        """
        category = Category.query.get(category_id)
        if not category:
            abort(404, message='Category not found')

        if category.products_count > 0:
            abort(405, message='Category non empty')
        db.session.delete(category)
        db.session.commit()
Beispiel #20
0
 def delete(self, product_id):
     """
     Delete product
     """
     product = Product.query.get(product_id)
     if not product:
         abort(404, message='Product not found')
     if product.owner_id != flask_praetorian.current_user().user_id and \
             flask_praetorian.current_user().role != 'admin':
         abort(400, message='You are not owner of this product')
     db.session.delete(product)
     db.session.commit()
Beispiel #21
0
 def post(self, args):
     """Register new user"""
     email = args.get('email')
     password = args.get('password')
     try:
         User.get(email=args.get('email'))
         abort(409, message='User already registered')
     except User.DoesNotExist:
         user = User(email=email, password=hash_password(password))
     user.active = False
     user.save()
     return user
Beispiel #22
0
 def post(self, new_data):
     """
     Register new user
     """
     user = User.query.filter_by(username=new_data['username']).first()
     if user:
         abort(400, message='User with this username is already registered')
     user = User(username=new_data['username'],
                 password=guard.encrypt_password(new_data['password']),
                 role='user')
     db.session.add(user)
     db.session.commit()
Beispiel #23
0
    def patch(self, args=None, pk=None) -> BaseQuery:
        if not self.update_enabled:
            abort(405)

        if not pk:
            raise Exception("pk not passed to patch()")

        item = self._lookup(pk)
        self._check_can_write(item)

        update_attrs(item, **args)
        self._db.session.commit()
        return item
Beispiel #24
0
    def post(self, new_data):
        """
        Add new product
        """
        category = Category.query.get(new_data['category_id'])
        if not category:
            abort(400, message='Category not found')
        product = Product(**new_data,
                          owner_id=flask_praetorian.current_user().user_id)
        db.session.add(product)
        db.session.commit()

        return product
Beispiel #25
0
    def post(self, args=None):
        """Create new model."""
        if not self.create_enabled:
            abort(405)

        # create
        item = self.model(**args)

        # access check should be done in subclass (for now)
        # self._check_can_create(item, args=args)

        self._db.session.add(item)

        self._db.session.commit()
        return item
Beispiel #26
0
    def get(self, id):
        """Get top level workflow logs"""
        try:
            db_res = db.session.query(WorkflowExecution)\
                .filter(WorkflowExecution.fargateTaskArn==id)\
                .filter(WorkflowExecution.workgroup.in_(get_jwt_groups()))\
                .one()
        except sqlalchemy.orm.exc.NoResultFound:
            abort(404)

        res = logs_client.get_log_events(
            logGroupName=db_res.fargateLogGroupName,
            logStreamName=db_res.fargateLogStreamName,
            startFromHead=False)
        return res
Beispiel #27
0
 def get(self, id):
     """Get nextflow script for workflow"""
     FILE = request.path.split("/")[-1]
     try:
         db_res = db.session.query(WorkflowExecution)\
             .filter(WorkflowExecution.fargateTaskArn==id).one()
         if FILE == "script":
             s3_url = db_res.launchMetadata["workflow_loc"]
         elif FILE == "config":
             s3_url = db_res.launchMetadata["config_loc"]
         elif FILE == "params":
             s3_url = db_res.launchMetadata["params_loc"]
         else:
             abort(500)
     except sqlalchemy.orm.exc.NoResultFound:
         abort(404)
     p = urllib.parse.urlparse(s3_url)
     res = s3_client.get_object(Bucket=p.netloc, Key=p.path[1:])
     return jsonify({"contents": res['Body'].read().decode('utf-8')})
Beispiel #28
0
 def post(self):
     """Refresh access token"""
     email = get_jwt_identity()
     try:
         user = User.get(email=email)
     except User.DoesNotExist:
         abort(403, message='No such user, or wrong password')
     access_expire = current_app.config['JWT_ACCESS_TOKEN_EXPIRES']
     access_token = create_access_token(identity=user.email)
     refresh_expire_date = datetime.strptime(
         request.cookies['refresh_expire'],
         '%Y-%m-%d %H:%M:%S.%f'
     )
     refresh_delta = refresh_expire_date - datetime.now()
     resp = jsonify(
         {
             'access': access_token,
             'accessExpire': int(access_expire.total_seconds()),
             'refreshExpire': int(refresh_delta.total_seconds()),
         }
     )
     set_access_cookies(resp, access_token)
     return resp
Beispiel #29
0
 def post(self, args):
     """Authenticates and generates a token"""
     email = args.get('email', None)
     password = args.get('password', None)
     if email is None:
         abort(403, message='Email not provided')
     try:
         user = User.get(email=email)
     except User.DoesNotExist:
         abort(403, message='No such user, or wrong password')
     if not user or not user.active:
         abort(403, message='No such user, or wrong password')
     if not verify_password(password, user.password):
         abort(403, message='No such user, or wrong password')
     access_token = create_access_token(identity=user.email)
     refresh_token = create_refresh_token(identity=user.email)
     access_expire = current_app.config['JWT_ACCESS_TOKEN_EXPIRES']
     refresh_expire = current_app.config['JWT_REFRESH_TOKEN_EXPIRES']
     resp = jsonify(
         {
             'access': access_token,
             'refresh': refresh_token,
             'accessExpire': int(access_expire.total_seconds()),
             'refreshExpire': int(refresh_expire.total_seconds()),
         }
     )
     set_access_cookies(resp, access_token)
     set_refresh_cookies(resp, refresh_token)
     refresh_path = current_app.config['JWT_REFRESH_COOKIE_PATH']
     refresh_secure = current_app.config['JWT_COOKIE_SECURE']
     refresh_expire_date = datetime.now() + refresh_expire
     resp.set_cookie(
         'refresh_expire',
         value=str(refresh_expire_date),
         expires=refresh_expire_date,
         path=refresh_path,
         httponly=True,
         secure=refresh_secure,
     )
     return resp
Beispiel #30
0
 def delete(self, role_id, user_id):
     """Remove user from role"""
     try:
         role = Role.get(id=role_id)
     except Role.DoesNotExist:
         abort(404, message='No such role')
     try:
         user = User.get(user_id)
     except User.DoesNotExist:
         abort(404, message='No such user')
     for user in role.users:
         if user.user.id == int(user_id):
             user.delete_instance()
             return user
     abort(409, message='User not assigned to role')