Ejemplo n.º 1
0
    async def send_password(request):
        try:
            data = send_password_schema.load(await request.json())
        except ValidationError as err:
            return VError(detail=err.messages)

        async with request.app['db'].acquire() as conn:
            result = await conn.execute(
                users.select().where(users.c.email == data['email'].lower()))
            user = await result.first()
            response, status = {}, 200
            if not user:
                response = {"error": "Email does not exist"}
                status = 404
            else:
                try:
                    from executors.email.email_cli import EmailClient
                    email_cli = EmailClient()
                    sent, err = await email_cli.send_forgotten_password(
                        to_email=user.email, password=user.password)
                    assert sent and not err
                    response = "Sent"
                except:
                    response = {"error": "Could not send passord"}
                    status = 500
            return web.json_response(data=response, status=status)
Ejemplo n.º 2
0
    async def login_driver(self, request):
        # todo request: keep me logedin
        print(">> auth")
        try:
            data = login_schema.load(await request.json())
        except ValidationError as err:
            return VError(detail=err.messages)

        async with request.app['db'].acquire() as conn:
            result = await conn.execute(users.select().where(
                and_(users.c.username == data['username'],
                     users.c.password == data['password'])))
            user = await result.first()
            status = 200
            if user:
                if user.role != UserRole.DRIVER:
                    response = {"error": "Wrong role"}
                    status = 405
                else:
                    try:
                        auth_token = encode_auth_token(user.id)
                        if auth_token:
                            response = {
                                'status': 'success',
                                'message': 'Successfully logged in.',
                                'auth_token': auth_token.decode()
                            }
                    except:
                        response = {"error": "Wrong role"}
                        status = 405
            else:
                response = {"error": "Wrong credentials"}
                status = 401
            return web.json_response(data=response, status=status)
Ejemplo n.º 3
0
    async def create_driver(request):
        org_id = 1
        # await user_view.check_permission(request, 'admin')
        driver_client = DriverClient()
        user_client = UserClient()
        data = await request.json()

        try:
            serialized_data = driver_schema.load(data)
            serialized_data['organization_id'] = org_id
        except ValidationError as err:
            raise HTTPServiceError()

        await user_view.is_unique(request)

        try:
            result = await driver_client.add(data=serialized_data)
        except UniqueViolationError as e:
            return VError(detail={e.constraint_name: e.args[0]})
        except Exception as ex:
            raise ex

        return web.json_response(status=200,
                                 data={
                                     "driver_id": result.get('id'),
                                 })
Ejemplo n.º 4
0
 async def is_unique(self, request, **kwargs):
     data = await request.json()
     async with request.app['db'].acquire() as conn:
         result = await conn.execute(users.select().where(
             and_(users.c.username == data['username'])))
         user = await result.first()
         if user:
             VError("Username exists. Please, choose another one")
Ejemplo n.º 5
0
    async def insert(self, request):
        org_id = 1  # request.user['org_id']
        try:
            data = event_schema.load(await request.json())
            data['organization_id'] = org_id
        except ValidationError as err:
            return VError(detail=err.messages)

        try:
            from executors.event.event_cli import EventClient
            event_cli = EventClient()
            event = await event_cli.add(data=data)
        except UniqueViolationError as e:
            return VError(detail={e.constraint_name: e.args[0]})
        except Exception as ex:
            raise ex

        return web.json_response(status=200, data=event)
Ejemplo n.º 6
0
    async def create(self, request):
        org_id = 1
        data = await request.json()

        try:
            serialized_data = event_schema.load(data)
            serialized_data['organization_id'] = org_id
        except ValidationError as err:
            return VError(detail=err.messages)

        try:
            event_id = await self.client.add(data=serialized_data)
        except UniqueViolationError as e:
            return VError(detail={e.constraint_name: e.args[0]})
        except Exception as ex:
            raise ex

        return web.json_response(status=200,
                                 data={"event_id": event_id.get('id')})
Ejemplo n.º 7
0
    async def deactivate(self, request):
        user_id = request.match_info['user_id']
        if not user_id:
            VError("user_id missing")
        try:
            user_cli = UserClient()
            response = await user_cli.set_status(data={
                "id": int(user_id),
                "status": 0,
            })
            if not response:
                return web.json_response(status=500)
        except Exception as ex:
            raise ex

        return web.json_response(status=200)
Ejemplo n.º 8
0
    async def update(self, request):
        data = await request.json()
        event_id = request.match_info['event_id']

        data['id'] = int(event_id)

        try:
            serialized_data = event_edit_schema.load(data)
        except ValidationError as err:
            return VError(detail=err.messages)

        try:
            event_update = await self.client.modify(data=serialized_data)
        except Exception as ex:
            raise ex

        return web.json_response(data=event_update, dumps=custom_dumps)
Ejemplo n.º 9
0
    async def create(self, request):
        data = await request.json()

        try:
            validated_data = terminal_schema.load(data)
        except ValidationError as err:
            return VError(detail=err.messages)

        try:
            terminal_id = await self.client.add(data=validated_data)
        except Exception as ex:
            raise ex

        return web.json_response(
            status=200,
            data={"terminal_id": terminal_id.get('id')}
        )
Ejemplo n.º 10
0
    async def change_password(request):
        try:
            data = change_password_schema.load(await request.json())
        except ValidationError as err:
            return VError(detail=err.messages)

        async with request.app['db'].acquire() as conn:
            result = await conn.execute(users.update().where(
                and_(users.c.username == request.user['username'],
                     users.c.password == data['old_password'])).values(
                         password=data['new_password']).returning(users.c.id))
            response, status = {}, 200
            id = await result.first()
            if not id:
                response = {"error": "Wrong Credentials"}
                status = 401
            return web.json_response(data=response, status=status)
Ejemplo n.º 11
0
    async def get_list(request):
        try:
            data = log_edit_request_schema.load(await request.json())
        except ValidationError as err:
            return VError(detail=err.messages)

        org_id = request.user['org_id']
        try:
            vehicles = await db_get_first_by_status(
                EventEditedCodeEnum.WAITING, org_id, int(data['driver_id']))
        except Exception as ex:
            return HTTPServiceError()

        return web.json_response(
            data={"data": vehicles},
            dumps=custom_dumps,
        )
Ejemplo n.º 12
0
    async def update_vehicle(self, request):
        vehicle_id = request.match_info['vehicle_id']
        data = await request.json()

        data['id'] = int(vehicle_id)
        try:
            validated_data = vehicle_edit_schema.load(data)
        except ValidationError as err:
            return VError(detail=err.messages)

        try:
            vehicle_update = await self.client.modify(data=validated_data)
        except Exception as ex:
            raise ex
        return web.json_response(
            data={"vehicle_id": vehicle_update}
        )
Ejemplo n.º 13
0
    async def update(self, request):
        event_id = request.match_info['event_id']

        try:
            serialized_data = event_schema.load(await request.json())
            serialized_data['id'] = int(event_id)
        except ValidationError as err:
            return VError(detail=err.messages)

        try:
            from executors.event.event_cli import EventClient
            event_cli = EventClient()
            event_update = await event_cli.modify(data=serialized_data)
        except Exception as ex:
            raise ex

        return web.json_response(data=event_update, dumps=custom_dumps)
Ejemplo n.º 14
0
    async def update_eld(self, request):
        data = await request.json()
        eld_id = request.match_info['eld_id']

        try:
            validated_data = eld_edit_schema.load(data)
        except ValidationError as err:
            return VError(detail=err.messages)

        validated_data['id'] = int(eld_id)
        try:
            eld_update = await self.client.modify(data=validated_data)
        except Exception as ex:
            raise ex

        return web.json_response(
            data=eld_update
        )
Ejemplo n.º 15
0
    async def update(self, request):
        data = await request.json()
        terminal_id = request.match_info['terminal_id']

        data['id'] = int(terminal_id)
        try:
            validated_data = terminal_schema.load(data)
        except ValidationError as err:
            return VError(detail=err.messages)

        try:
            terminal_update = await self.client.modify(data=validated_data)
        except Exception as ex:
            raise ex

        return web.json_response(
            data=terminal_update
        )
Ejemplo n.º 16
0
    async def create_eld(self, request):
        org_id = 1
        data = await request.json()

        try:
            validated_data = eld_schema.load(data)
            validated_data['organization_id'] = org_id
        except ValidationError as err:
            return VError(detail=err.messages)

        try:
            eld_id = await self.client.add(data=validated_data)
        except Exception as ex:
            raise ex

        return web.json_response(
            status=200,
            data={"eld_id": eld_id.get('id')}
        )
Ejemplo n.º 17
0
    async def create(self, request):
        org_id = 1
        data = await request.json()

        try:
            if isinstance(data['groups'], list):
                data['groups'] = dict(
                    zip(map(lambda x: str(x), data['groups']), data['groups']))
            serialized_data = unit_schema.load(data)
            serialized_data['organization_id'] = org_id
        except ValidationError as err:
            return VError(detail=err.messages)

        try:
            unit_id = await self.client.add(data=serialized_data)
        except Exception as ex:
            raise ex

        return web.json_response(status=200,
                                 data={"unit_id": unit_id.get('id')})
Ejemplo n.º 18
0
    async def update(self, request):
        data = await request.json()
        unit_id = request.match_info['unit_id']

        data['id'] = int(unit_id)

        try:
            if isinstance(data['groups'], list):
                data['groups'] = dict(
                    zip(map(lambda x: str(x), data['groups']), data['groups']))
            serialized_data = unit_edit_schema.load(data)
        except ValidationError as err:
            return VError(detail=err.messages)

        try:
            unit_update = await self.client.modify(data=serialized_data)
        except Exception as ex:
            raise ex

        return web.json_response(data={"unit_id": unit_update},
                                 dumps=custom_dumps)
Ejemplo n.º 19
0
    async def get_list(self, request):
        org_id = 1
        limit = request.rel_url.query.get("limit")
        offset = request.rel_url.query.get("offset")
        start_date = request.rel_url.query.get("startDate")
        end_date = request.rel_url.query.get("endDate")
        driver_id = request.rel_url.query.get("driver_id")
        vehicle_id = request.rel_url.query.get("vehicle_id")

        try:
            if isinstance(start_date, datetime.date):
                start_date = str(start_date)
            if isinstance(end_date, datetime.date):
                end_date = str(end_date)
            if isinstance(start_date, datetime.datetime):
                start_date = str(start_date.date())
            if isinstance(end_date, datetime.datetime):
                end_date = str(end_date.date())
        except:
            return VError(
                detail="date, datetime or str-date expected: '2020-01-30'")

        vehicles = {}
        try:
            if limit and offset:
                vehicles = await db_paginate(
                    limit=int(limit),
                    offset=int(offset),
                    organization_id=org_id,
                    start_date=start_date,
                    end_date=end_date,
                    driver_id=driver_id,
                    vehicle_id=vehicle_id,
                )
            else:
                pass
        except Exception as ex:
            raise ex

        return web.json_response(data={"data": vehicles}, dumps=custom_dumps)
Ejemplo n.º 20
0
    async def hand_review(request):
        # https://docs.aiohttp.org/en/2.0.7/web.html#file-uploads
        # https://stackoverflow.com/questions/34121814/aiohttp-serve-single-static-file
        org_id = request.user['org_id']
        start_date = request.rel_url.query.get("startDate")
        end_date = request.rel_url.query.get("endDate")
        try:
            assert start_date and end_date
            start_date = parse(start_date)
            end_date = parse(end_date)
        except:
            return VError(
                detail="Invalid query, startDate and endDate expected")

        result, driver = {}, {}
        try:
            # Get Events and Log
            from executors.log.log_cli import LogClient
            log_cli = LogClient()
            result: dict = await log_cli.get_by_date(org_id=org_id,
                                                     start_date=start_date,
                                                     end_date=end_date)
            if not len(result) or not result:
                return web.json_response(data={"data": {}}, dumps=custom_dumps)
            # todo get: driver, org, terminal, log, eld, timezone, vehicle
            # Get Driver
            # driver_id = result.values()[0]
            # from executors.driver.driver_client import DriverClient
            # driver_cli = DriverClient()
            # driver = await driver_cli.get_one()
            # assert driver_cli
            data = {}
            location = await to_pdf('inspection.html', 'inspection.pdf', data)

        except Exception as ex:
            return HTTPServiceError(ex.__cause__)

        return web.FileResponse('./index.html')
Ejemplo n.º 21
0
    async def get_by_date(request):
        org_id = request.user['org_id']
        start_date = request.rel_url.query.get("startDate")
        end_date = request.rel_url.query.get("endDate")
        try:
            assert start_date and end_date
            start_date = parse(start_date)
            end_date = parse(end_date)
        except:
            return VError(
                detail="Invalid query, startDate and endDate expected")

        result = {}
        try:
            from executors.log.log_cli import LogClient
            log_cli = LogClient()
            vehicles = await log_cli.get_by_date(org_id=org_id,
                                                 start_date=start_date,
                                                 end_date=end_date)
        except Exception as ex:
            raise ex

        return web.json_response(data={"data": vehicles}, dumps=custom_dumps)