예제 #1
0
class TestRegion(unittest.TestCase):
    def setUp(self):
        os.system("rm -rf ./test_content/*")
        self.account_dao = AccountDao(Path("./test_content"))
        trilogy = self.account_dao.load({
            'identifier': 1,
            'name': 'Trilogy Partners',
            'email': '*****@*****.**'
        })
        self.account_dao.create(trilogy)
        self.region_dao = RegionDao(Path("./test_content"), trilogy.identifier)

    def test_create(self):
        # Note -- don't use the Account constructor directly. Use the AccountDao instead
        italy = self.region_dao.load({
            'account_id': 1,
            'region_id': 'Italy',
            'description': 'Locations in Italy',
            'polygon': 'Not implemented'
        })
        self.region_dao.create(italy)
        x = self.region_dao.retrieve('Italy')
        self.assertEqual(type(x.region_id), type(italy.region_id))
        self.assertEqual(x.region_id, italy.region_id)
        self.assertEqual(x.account_id, italy.account_id)
        self.assertEqual(x.description, italy.description)
        self.assertEqual(x.polygon, italy.polygon)
예제 #2
0
class TestSeason(unittest.TestCase):
    def setUp(self):
        os.system("rm -rf ./test_content/*")
        self.account_dao = AccountDao(Path("./test_content"))
        trilogy = self.account_dao.load({
            'identifier': 1,
            'name': 'Trilogy Partners',
            'email': '*****@*****.**'
        })
        self.vessel_dao = VesselDao(Path("./test_content"), trilogy.identifier)
        self.season_dao = SeasonDao(Path("./test_content"))
        self.account_dao.create(trilogy)
        trilogy = self.vessel_dao.load({
            'account_id': 1,
            'identifier': 'trilogy',
            'name': 'SV Trilogy',
            'flag': 'Australian',
            'rego': '806176',
            'speed_kts': 7.6,
        })
        self.vessel_dao.create(trilogy)
        x = self.vessel_dao.retrieve('trilogy')

    def test_create(self):
        season = self.season_dao.load({
            'account_id': 1,
            'identifier': 'med_summer_2019',
            'name': 'Mediterranean 2019'
        })
        self.season_dao.create(season)
        x = self.season_dao.retrieve(1, 'med_summer_2019')
        self.assertEqual(type(x.identifier), type(season.identifier))
        self.assertEqual(x.identifier, season.identifier)
        self.assertEqual(x.name, season.name)
예제 #3
0
    def post_sign_in(self, connection, data):
        account_dao = AccountDao()

        try:
            user_info = account_dao.get_user_info(connection, data)

            # 데이터베이스에 nickname이 존재하지 않으면 에러 처리.
            if not user_info:
                raise InvalidRequest(WRONG_ID_OR_PW, 400)

            password_check = bcrypt.checkpw(
                data["password"].encode("utf-8"),
                user_info["password"].encode("utf-8"))

            # 데이터베이스의 비밀번호와 일치하지 않으면 에러 처리.
            if password_check is not True:
                raise InvalidRequest(WRONG_ID_OR_PW, 400)

            # nickname, password 모두 일치하면 토큰 생성.
            access_token = jwt.encode({"account_id": user_info["account_id"]},
                                      SECRET_KEY,
                                      algorithm=ALGORITHM)

            return {"message": "login succeed", "access_token": access_token}

        except Exception as e:
            raise e
    def create_account(self, data, connection):    
        
        account_dao = AccountDao()
        is_existed  = account_dao.is_existed_account(data, connection)
        
        if is_existed:
            raise AlreadyExistError(ALREADY_EXISTS, 409)

        account_id         = account_dao.join(data,connection)
    
        data['Id']         = account_id
        data['account_id'] = account_id
        account_type       = data['account_type_id']
            
        hashed_password  = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
        data['password'] = hashed_password

        if account_type == SELLER_ACCOUNT_TYPE:
            account_dao.seller_join_info(data, connection)
            data['seller_id']        = account_id
            data['action_status_id'] = STAND_BY
            return account_dao.seller_join_history(data, connection)
        
        if account_type == MASTER_ACCOUNT_TYPE:
            account_dao.master_join_info(data, connection) 
            data['master_id'] = account_id
            return account_dao.master_join_history(data, connection)
예제 #5
0
 def setUp(self):
     os.system("rm -rf ./test_content/*")
     self.account_dao = AccountDao(Path("./test_content"))
     trilogy = self.account_dao.load({
         'identifier': 1,
         'name': 'Trilogy Partners',
         'email': '*****@*****.**'
     })
     self.vessel_dao = VesselDao(Path("./test_content"), trilogy.identifier)
     self.account_dao.create(trilogy)
예제 #6
0
class TestVessel(unittest.TestCase):
    def setUp(self):
        os.system("rm -rf ./test_content/*")
        self.account_dao = AccountDao(Path("./test_content"))
        trilogy = self.account_dao.load({
            'identifier': 1,
            'name': 'Trilogy Partners',
            'email': '*****@*****.**'
        })
        self.vessel_dao = VesselDao(Path("./test_content"), trilogy.identifier)
        self.account_dao.create(trilogy)

    def test_create(self):
        # Note -- don't use the Account constructor directly. Use the AccountDao instead
        trilogy = self.vessel_dao.load({
            'account_id': 1,
            'identifier': 'trilogy',
            'name': 'SV Trilogy',
            'flag': 'Australian',
            'rego': '806176',
            'speed_kts': 7.6,
        })
        self.vessel_dao.create(trilogy)
        x = self.vessel_dao.retrieve('trilogy')
        self.assertEqual(type(x.identifier), type(trilogy.identifier))
        self.assertEqual(x.identifier, trilogy.identifier)
        self.assertEqual(x.name, trilogy.name)
        self.assertEqual(x.flag, trilogy.flag)
        self.assertEqual(x.rego, trilogy.rego)
        self.assertEqual(x.speed_kts, trilogy.speed_kts)

    def test_find_all(self):
        trilogy = self.vessel_dao.load({
            'account_id': 1,
            'identifier': 'trilogy',
            'name': 'SV Trilogy',
            'flag': 'Australian',
            'rego': '806176',
            'speed_kts': 7.6,
        })
        self.vessel_dao.create(trilogy)
        namadgi = self.vessel_dao.load({
            'account_id': 1,
            'identifier': 'namadgi',
            'name': 'Namadgi 3',
            'flag': 'Australian',
            'rego': '1234',
            'speed_kts': 7.0,
        })
        self.vessel_dao.create(namadgi)
        r = self.vessel_dao.find_all()
        self.assertEqual(len(r), 2)
예제 #7
0
def create_app(test_config=None):
    app = Flask(__name__)
    app.json_encoder = CustomEncoder
    CORS(app, resources={r'*': {'origins': '*'}})
    if test_config is None:
        app.config.from_pyfile('config.py')
    else:
        app.config.update(test_config)

    #persistence layer

    account_dao = AccountDao()
    seller_dao = SellerDao()
    order_dao = OrderDao()
    product_dao = ProductDao()

    #business layer
    account_service = AccountService(account_dao, config)
    seller_service = SellerService(seller_dao, config)
    order_service = OrderService(order_dao)
    product_service = ProductService(product_dao)

    #presentation layer(엔드포인트 생성)
    app.register_blueprint(create_account_endpoints(account_service))
    app.register_blueprint(create_seller_endpoints(seller_service))
    app.register_blueprint(create_order_endpoints(order_service))

    app.register_blueprint(create_product_endpoints(product_service))

    return app
예제 #8
0
    def setUp(self):
        os.system("rm -rf ./test_content/*")
        self.account_dao = AccountDao(Path("./test_content"))
        trilogy_acc = self.account_dao.load({
            'identifier': 1,
            'name': 'Trilogy Partners',
            'email': '*****@*****.**'
        })
        self.account_dao.create(trilogy_acc)
        self.region_dao = RegionDao(Path("./test_content"),
                                    trilogy_acc.identifier)

        italy = self.region_dao.load({
            'account_id': 1,
            'region_id': 'italy',
            'description': 'Locations in Italy',
            'polygon': 'Not implemented'
        })
        self.region_dao.create(italy)
예제 #9
0
 def setUp(self):
     os.system("rm -rf ./test_content/*")
     self.account_dao = AccountDao(Path("./test_content"))
     trilogy = self.account_dao.load({
         'identifier': 1,
         'name': 'Trilogy Partners',
         'email': '*****@*****.**'
     })
     self.vessel_dao = VesselDao(Path("./test_content"), trilogy.identifier)
     self.season_dao = SeasonDao(Path("./test_content"))
     self.account_dao.create(trilogy)
     trilogy = self.vessel_dao.load({
         'account_id': 1,
         'identifier': 'trilogy',
         'name': 'SV Trilogy',
         'flag': 'Australian',
         'rego': '806176',
         'speed_kts': 7.6,
     })
     self.vessel_dao.create(trilogy)
     x = self.vessel_dao.retrieve('trilogy')
예제 #10
0
class TestPerson(unittest.TestCase):
    def setUp(self):
        os.system("rm -rf ./test_content/*")
        self.account_dao = AccountDao(Path("./test_content"))
        trilogy = self.account_dao.load({
            'identifier': 1,
            'name': 'Trilogy Partners',
            'email': '*****@*****.**'
        })
        self.person_dao = PersonDao(Path("./test_content"), trilogy.identifier)
        self.account_dao.create(trilogy)

    def test_create(self):
        fred = self.person_dao.load({
            'account_id': 1,
            'identifier': "fas",
            'surname': 'Smith',
            'first_names': 'Frederick Alexander',
            'address': '17 Constitution Ave, Canberra, ACT 2612',
            'email': '*****@*****.**',
            'phone': '+61234567273',
            'gender': 'MALE',
            'passport_no': 'P1234543212',
            'passport_country': 'Australia',
            'passport_issued': '2012-10-25',
            'passport_expiry': '2022-10-25',
            'skills': "",
            'blood_group': 'O+ve',
            'allergies': '',
            'medication': '',
            'quals': 'Yachtmaster, senior first aid'
            #      'nok_id=None,
            #      'nok_relationship=None,
            #      'next_flight_in=None,
            #      'next_flight_out=None,
        })
        self.person_dao.create(fred)
        x = self.person_dao.retrieve('fas')
        self.assertEqual(type(x.identifier), type(fred.identifier))
        self.assertEqual(x.identifier, fred.identifier)
예제 #11
0
    def wrapper(*args, **kwargs):
        access_token = request.headers.get("Authorization")

        if access_token is None:
            raise LoginRequiredError(LOGIN_REQUIRED, 401)

        connection = None

        try:
            # 헤더에 있는 토큰을 디코드해서 payload에 담는다.
            payload = jwt.decode(access_token, SECRET_KEY, ALGORITHM)

            # payload = {"account_id"    : user_info["account_id"]}

            account_dao = AccountDao()
            connection = connect_db()

            account = account_dao.account_check(connection, payload)

            if account["account_type_id"] != USER_ACCOUNT_TYPE:
                raise InvalidAccessError(UNAUTHORIZED_TOKEN, 401)

            if account["is_deleted"] == 1:
                raise InvalidAccessError(UNAUTHORIZED_TOKEN, 401)

            g.account_info = {"account_id": payload["account_id"]}

        except jwt.InvalidTokenError:
            raise InvalidAccessError(UNAUTHORIZED_TOKEN, 401)

        except Exception as e:
            raise e

        finally:
            if connection is not None:
                connection.close()

        return func(*args, **kwargs)
예제 #12
0
    def wrapper(*args, **kwargs):
        access_token = request.headers.get('Authorization')
        if access_token is None:
            raise LoginRequiredError(LOGIN_REQUIRED, 401) 

        connection = None
        try:
            payload = jwt.decode(access_token, SECRET_KEY['secret'], ALGORITHM)

            data         = {'account_id' : payload['Id']}
            account_dao  = AccountDao()
            connection   = connect_db()
            
            if payload['account_type'] == SELLER_ACCOUNT_TYPE:
                seller_check = account_dao.check_seller(data, connection)
                is_deleted   = seller_check['is_deleted']
                
                if is_deleted:
                    raise InvalidAccessError(UNAUTHORIZED_TOKEN, 401)

            if payload['account_type'] == MASTER_ACCOUNT_TYPE:
                is_deleted = account_dao.check_master(data, connection)['is_deleted']
                if is_deleted:
                    raise InvalidAccessError(UNAUTHORIZED_TOKEN, 401)

            g.account_info = {'account_id'   : payload['Id'], 
                                'account_type' : payload['account_type']}
            
        except jwt.InvalidTokenError:
            raise InvalidAccessError(UNAUTHORIZED_TOKEN, 401)
        
        finally:
            if connection is not None:
                connection.close()
               
        return func(*args, **kwargs)
예제 #13
0
class TestAccount(unittest.TestCase):
    def setUp(self):
        os.system("rm -rf ./test_content/*")
        self.dao = AccountDao(Path("./test_content"))

    def test_illegal_operation(self):
        try:
            x = self.dao.find_all()
        except IllegalOperation as e:
            return
        except Exception as e:
            self.fail(
                "Failed to raise IllegalOperation on 'find_all', raised {} instead"
                .format(type(e)))

        self.fail("Failed to raise IllegalOperation on 'find_all'")

    def test_create(self):

        # Note -- don't use the Account constructor directly. Use the AccountDao instead
        trilogy = self.dao.load({
            'identifier': 1,
            'name': 'Trilogy Partners',
            'email': '*****@*****.**'
        })
        self.dao.create(trilogy)
        x = self.dao.retrieve(1)
        print(type(x.identifier))
        self.assertEqual(type(x.identifier), type(trilogy.identifier))
        self.assertEqual(x.identifier, trilogy.identifier)
        self.assertEqual(x.name, trilogy.name)
        self.assertEqual(x.email, trilogy.email)
        self.assertEqual(self.dao.next_sequential_id(), 2)

    def test_create_bad_data(self):

        # Account identifier must be numeric
        try:
            trilogy = self.dao.load({
                'identifier': 'abc',
                'name': 'Trilogy Partners',
                'email': '*****@*****.**'
            })
        except ValidationError as e:
            return
        self.fail(
            "Should have got a validation error - non-integer identifier")
예제 #14
0
    def login(self, data, connection):
        """어드민 로그인 서비스 로직

        어드민이 로그인했을때 계정 타입을 확인하고 마스터 또는 셀러이면
        account_id 와 account_type을 토큰화하여 토큰을 발급한다.

        Author:
            김현영

        Args:
            data (dict): 사용자가 입력한 nickname, password 값을 가지는 dictionary
            connection (객체): pymysql 객체

        Raises:
            InvalidUserError: 해당 nickname를 가진 계정이 없을때
            InvalidUserError: 해당 seller 계정이 삭제된 계정일 때
            InvalidUserError: 해당 master 계정이 삭제된 계정일 때
            InvalidUserError: 해당 계정의 계정 타입이 일반 유저일 때
            InvalidUserError: 패스워드가 일치하지 않을 때

        Returns:
            {
                "access_token" : "token"
            }
        """
        account_dao = AccountDao()
        
        account_info    = account_dao.get_account_id(data, connection)
        
        if account_info is None:
            raise InvalidUserError(INVALID_USER, 401)

        data['account_id'] = account_info['Id']
        account_type       = account_info['account_type_id']
        
        if account_type == SELLER_ACCOUNT_TYPE:
            result        = account_dao.check_seller(data, connection)
            is_deleted    = result['is_deleted']
            action_status = result['action_status_id']
            if is_deleted:
                raise InvalidUserError(INVALID_USER, 401)
            if action_status == STAND_BY:
                raise InvalidUserError(UNPERMITTED_USER, 401)
            password = result['password']
        
        if account_type == MASTER_ACCOUNT_TYPE:
            result = account_dao.check_master(data, connection)
            is_deleted = result['is_deleted']
            if is_deleted:
                raise InvalidUserError(INVALID_USER, 401)
            password = result['password']
        
        if account_type == USER_ACCOUNT_TYPE:
            raise InvalidUserError(ACCESS_DENIED, 401)
        
        if not bcrypt.checkpw(data['password'].encode('utf-8'), password.encode('utf-8')):
            raise InvalidUserError(INVALID_USER, 401)
        
        access_token = jwt.encode(
            {'Id'           : data['account_id'], 
             'account_type' : account_type},
              SECRET_KEY['secret'],
              ALGORITHM
        )
        
        return access_token      
예제 #15
0
 def setUp(self):
     os.system("rm -rf ./test_content/*")
     self.dao = AccountDao(Path("./test_content"))
예제 #16
0
class TestLocation(unittest.TestCase):
    def setUp(self):
        os.system("rm -rf ./test_content/*")
        self.account_dao = AccountDao(Path("./test_content"))
        trilogy_acc = self.account_dao.load({
            'identifier': 1,
            'name': 'Trilogy Partners',
            'email': '*****@*****.**'
        })
        self.account_dao.create(trilogy_acc)
        self.region_dao = RegionDao(Path("./test_content"),
                                    trilogy_acc.identifier)

        italy = self.region_dao.load({
            'account_id': 1,
            'region_id': 'italy',
            'description': 'Locations in Italy',
            'polygon': 'Not implemented'
        })
        self.region_dao.create(italy)

    def test_create(self):
        location_dao = LocationDao("./test_content", 1, 'italy')
        rome = location_dao.load({
            'account_id': 1,
            'region_id': 'italy',
            'identifier': 'Rome',
            'name': 'Rome, Italy',
            'coords': {
                'longitude': 20.0,
                'latitude': 40.0,
                'altitude': 200.0
            },
            'timezone_name': 'Europe/Rome'
        })
        location_dao.create(rome)

        x = location_dao.retrieve('Rome')
        self.assertEqual(type(x.region_id), type(rome.region_id))
        self.assertEqual(x.region_id, rome.region_id)
        self.assertEqual(x.account_id, rome.account_id)
        self.assertEqual(x.name, rome.name)

        # can't create twice

        try:
            location_dao.create(rome)
        except ValueError as e:
            return
        self.fail("Should have got a duplication ValueError")

    def test_geocode(self):
        location_dao = LocationDao("./test_content", 1, 'italy')
        rome = Location(1, 'italy', 'Rome', 'Rome, Italy')
        print(rome)
        location_dao.create(rome)
        x = location_dao.retrieve('Rome')
        print(x)
        self.assertEqual(type(x.region_id), type(rome.region_id))
        self.assertEqual(x.region_id, rome.region_id)
        self.assertEqual(x.account_id, rome.account_id)
        self.assertEqual(x.name, rome.name)
        self.assertEqual(x.timezone_name, rome.timezone_name)
        self.assertEqual(x.coords, rome.coords)
예제 #17
0
class TestPlan(unittest.TestCase):
    def setUp(self):
        os.system("rm -rf ./test_content/*")
        self.account_dao = AccountDao(Path("./test_content"))
        account = self.account_dao.load({
            'identifier': 1,
            'name': 'Trilogy Partners',
            'email': '*****@*****.**'
        })
        self.account_dao.create(account)
        self.vessel_dao = VesselDao(Path("./test_content"), account.identifier)
        trilogy = self.vessel_dao.load({
            'account_id': 1,
            'identifier': 'trilogy',
            'name': 'SV Trilogy',
            'flag': 'Australian',
            'rego': '806176',
            'speed_kts': 7.6,
        })
        self.vessel_dao.create(trilogy)
        x = self.vessel_dao.retrieve('trilogy')
        self.plan_dao = PlanDao(Path("./test_content"), account.identifier)

    def test_create(self):
        # Note -- don't use the Account constructor directly. Use the AccountDao instead
        plan = self.plan_dao.load({
            'account_id':
            1,
            'vessel_id':
            'trilogy',
            'season_id':
            'med_summer_2019',
            'plan_id':
            self.plan_dao.get_random_id(),
            'cdl':
            "This is cruise description language\nit breaks over multiple lines"
        })
        self.plan_dao.create(plan)
        x = self.plan_dao.retrieve(plan.plan_id)
        self.assertEqual(type(x.plan_id), type(plan.plan_id))
        self.assertEqual(x.plan_id, plan.plan_id)
        self.assertEqual(x.account_id, plan.account_id)
        self.assertEqual(x.vessel_id, plan.vessel_id)
        self.assertEqual(x.season_id, plan.season_id)
        self.assertEqual(x.cdl, plan.cdl)

    def test_create_with_cdl(self):
        with open("../grammar/plan_B.cdl", 'r') as infile:
            cdl = infile.read()
        plan = self.plan_dao.load({
            'account_id': 1,
            'vessel_id': 'trilogy',
            'season_id': 'med_summer_2019',
            'plan_id': self.plan_dao.get_random_id(),
            'cdl': cdl
        })
        self.plan_dao.create(plan)
        x = self.plan_dao.retrieve(plan.plan_id)
        self.assertEqual(type(x.plan_id), type(plan.plan_id))
        self.assertEqual(x.plan_id, plan.plan_id)
        self.assertEqual(x.account_id, plan.account_id)
        self.assertEqual(x.vessel_id, plan.vessel_id)
        self.assertEqual(x.season_id, plan.season_id)
        self.assertEqual(x.cdl, plan.cdl)