Example #1
0
    def test_add_new_user(self):
        new_user = {
            'username': '******',
            'password': '******',
            'displayName': {
                'firstName': 'Aaron',
                'lastName': 'Smith'
            },
            'email': '*****@*****.**',
            'adminRights': False,
            'paymentInfo': {
                'name': 'Aaron Smith',
                'cardType': 'VISA',
                'num': 451535486,
                'expiry': datetime.datetime(2017, 1, 1)
            },
            'address': {
                'number': 123,
                'name': 'Main',
                'streetType': 'Boulevard',
                'postalCode': 'M3E5R1'
            }
        }

        with flask_app.app_context():
            User.save(new_user)
            found_user = User.get_by_email(new_user['email'])
            self.assertEqual(new_user['email'], found_user['email'],
                             "User emails not equal")
            User.remove(new_user['email'])
    def test_admin_add_restaurant(self):
        json_response_reg = self.__register_user(self.__admin_user_data)
        admin_token = self.__login_user(json.loads(self.__admin_user_data))

        # add restaurant as admin
        result = self.app.post('/admin/restaurant/add',
                               headers={
                                   'Content-Type': 'application/json',
                                   'token': admin_token
                               },
                               data=json.dumps(self.__test_restaurant_data_1))

        json_data = json.loads(result.data)
        self.assertTrue(json_data['data']['restaurant'] is not None,
                        'restaurant not added')

        with flask_app.app_context():
            Restaurant.remove(json_data['data']['restaurantId'])
            User.remove(json_response_reg['data']['user']['email'])

        return {
            'id': json_data['data']['restaurantId'],
            'token': admin_token,
            'restaurant': json_data['data']['restaurant']
        }
Example #3
0
    def test_add_new_order(self):
        json_response_reg = self.__register_user()

        login = self.app.post('/login',
                              headers={
                                  'username': '******',
                                  'password': '******'
                              })
        json_login = json.loads(login.data)
        data = '{"date": "12:05:2017","delivery": true,"items": [' \
               '{"58cb056f98717507c730d78b": 5},{"58cb0577630cc007c7870772": 2},' \
               '{"58d13f3e63ae2507c70a7d5e": 1}' \
               '],"price": 25.06}'

        result = self.app.post('/order/add/',
                               headers={'token': json_login['data']['token']},
                               data=data,
                               content_type='application/json')
        json_response = json.loads(result.data)
        self.assertIsNotNone(json_response['data']['orderId'],
                             'error in response')

        with flask_app.app_context():
            Order.remove(json_response['data']['orderId'])
            User.remove(json_response_reg['data']['user']['email'])
    def test_get_customer_info(self):
        json_response_reg = self.__register_user()

        token = self.__login()
        result = self.app.get('/customer/profile', headers={'token': token})
        self.assertIsNotNone(result, 'No user info')

        with flask_app.app_context():
            User.remove(json_response_reg['data']['user']['email'])
    def test_get_customer_payment_info(self):
        json_response_reg = self.__register_user()

        token = self.__login()
        result = self.app.get('/customer/payment', headers={'token': token})
        json_data = json.loads(result.data)
        self.assertTrue(json_data['data']['paymentInfo'] is not None,
                        'no payment info')

        with flask_app.app_context():
            User.remove(json_response_reg['data']['user']['email'])
Example #6
0
    def test_register_new_users(self):
        data = '{"address": {"name": "Main", "number": 123, "postalCode": "M3E5R1", "streetType": "Street"}, ' \
               '"adminRights": false, "displayName": {"firstName": "Aaron", "lastName": "Smith"}, ' \
               '"email": "*****@*****.**", "password": "******", "paymentInfo": {"cardType": "VISA", ' \
               '"expiry": "1/1/17 12:00:00 AM UTC", "name": "steve Smith", "num": 451535486}, "username": "******"}'

        json_response = self.__register_user(data)

        self.assertEqual(json.dumps(json_response['data']['user']), data,
                         'data returned is not the same')

        with flask_app.app_context():
            User.remove(json_response['data']['user']['email'])
Example #7
0
def login() -> tuple:
    """

    swagger_from_file: ../swagger/login/login.yml

    Login to the api
    Pass in the username and password in the header
    A token is returned
    {"data": {"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJleHAiOjE0ODkxODUyMjAsInNvbWVQY"}}
    :return: token
    """
    # import here because of circular reference
    from hopkin.models.users import User

    if ('username' in request.headers) and ('password' in request.headers):
        username = request.headers['username']
        password = request.headers['password']
    else:
        return jsonify({'error': 'no username or password provided'}), 403

    # find user from database
    user = User.get_by_username(username)
    if user is None:
        return jsonify({'error': 'wrong username or password'}), 403
    else:
        # verify password
        if not check_password_hash(user['password'], password):
            return jsonify({'error': 'wrong username or password'}), 403

    if hasattr(user, 'token'):
        jwt_token = user['token']
    else:
        # generate a new token for the user for 1 week
        token = jwt.encode(
            {
                'exp':
                datetime.datetime.utcnow() + datetime.timedelta(weeks=1),
                'user_id': str(user['_id'])
            },
            'secret',
            algorithm='HS512')
        jwt_token = token.decode("utf-8")
        user['token'] = jwt_token
        User.save(user)

    return jsonify(
        {'data': {
            'token': jwt_token,
            'adminRights': user['adminRights']
        }})
Example #8
0
    def test_admin_register(self):
        data = '{"username": "******","password": "******","displayName": {"firstName": "Aaron",' \
               '"lastName": "Fernandes"},"email": "*****@*****.**","adminRights": true, ' \
               '"paymentInfo": {"name": "Aaron Fernandes","cardType": "VISA","num": 451535486,' \
               '"expiry": "1/1/17 12:00:00 AM UTC"},"address":{"number": 345,"name": "Fake","streetType": ' \
               '"Street","postalCode": "M3H5R1"}}'
        json_response = self.__register_user(data)

        self.assertTrue(
            json.dumps(json_response['data']['user']['adminRights']),
            'admin register failed')

        with flask_app.app_context():
            User.remove(json_response['data']['user']['email'])
Example #9
0
def before_request() -> tuple:
    """
    Checks if a token header in requests
    :return:
    """
    if request.method == 'GET' or request.method == 'POST':
        flask_app.logger.log(10, 'Headers: %s', request.headers)
        flask_app.logger.log(10, 'Body: %s', request.get_data())

        from hopkin.models.users import User
        no_auth_paths = [
            '/spec', '/favicon.ico', '/item', '/login', '/restaurant'
        ]
        auth_required = True
        for path in no_auth_paths:
            if request.path.startswith(path):
                auth_required = False
        if '/' is request.path:
            auth_required = False
        if auth_required and 'token' in request.headers:
            token = request.headers['token']
            user = User.get_by_token(token)

            if user is None:
                return jsonify({'error': 'not a valid token'}), 403
            else:
                g.user_id = user['_id']
                g.is_admin = user['adminRights']
        elif auth_required and 'token' not in request.headers:
            return jsonify({'error': 'no token provided'}), 403
Example #10
0
    def test_get_user_orders(self):
        json_response_reg = self.__register_user()

        login = self.app.post('/login',
                              headers={
                                  'username': '******',
                                  'password': '******'
                              })
        json_response = json.loads(login.data)['data']['token']
        self.assertIsNotNone(json_response)
        result = self.app.get('/order', headers={'token': json_response})
        json_data = json.loads(result.data)
        self.assertIsNotNone(len(json_data), 'no orders in db')

        with flask_app.app_context():
            User.remove(json_response_reg['data']['user']['email'])
Example #11
0
def customer_profile_info() -> dict:
    """

    swagger_from_file: ../swagger/customer/profile.yml

    Gets a customers profile info
    :return:
    """
    from hopkin.models.users import User
    request = User.get_by_id(g.user_id)

    user_info = {
        'username': request['username'],
        'displayName': {
            'firstName': request['displayName']['firstName'],
            'lastName': request['displayName']['lastName']
        },
        'email': request['email'],
        'paymentInfo': {
            'name': request['paymentInfo']['name'],
            'cardType': request['paymentInfo']['cardType'],
            'num': get_cc_number(request['paymentInfo']['num']),
            'expiry': request['paymentInfo']['expiry']
        },
        'address': {
            'number': int(request['address']['number']),
            'name': request['address']['name'],
            'streetType': request['address']['streetType'],
            'postalCode': request['address']['postalCode']
        }
    }

    return jsonify({'data': {'user': user_info}})
Example #12
0
def customer_profile_update() -> tuple:
    """

    swagger_from_file: ../swagger/customer/profile.yml

    Gets a customers profile info
    :return:
    """
    if request.json is not None:

        from hopkin.models.users import User
        # read the the user to the db
        if request.json is not None:
            user_update = {
                'username': request.json['username'],
                'displayName': {
                    'firstName': request.json['displayName']['firstName'],
                    'lastName': request.json['displayName']['lastName']
                },
                'email': request.json['email'],
                'adminRights': request.json['adminRights'],
                'paymentInfo': {
                    'name':
                    request.json['paymentInfo']['name'],
                    'cardType':
                    request.json['paymentInfo']['cardType'],
                    'num':
                    int(request.json['paymentInfo']['num']),
                    'expiry':
                    datetime.datetime.strptime(
                        request.json['paymentInfo']['expiry'],
                        "%w/%m/%y %I:%M:%S %p UTC")
                },
                'address': {
                    'number': int(request.json['address']['number']),
                    'name': request.json['address']['name'],
                    'streetType': request.json['address']['streetType'],
                    'postalCode': request.json['address']['postalCode']
                }
            }

            User.save(user_update)

        return jsonify({'data': {'user': user_update}})
    else:
        return jsonify({'error': 'user not updated'}), 400
Example #13
0
    def test_login_token(self):
        data = '{"address": {"name": "Main", "number": 123, "postalCode": "M3E5R1", "streetType": "Street"}, ' \
               '"adminRights": false, "displayName": {"firstName": "Aaron", "lastName": "Smith"}, ' \
               '"email": "*****@*****.**", "password": "******", "paymentInfo": {"cardType": "VISA", ' \
               '"expiry": "1/1/17 12:00:00 AM UTC", "name": "steve Smith", "num": 451535486}, "username": "******"}'
        json_response_reg = self.__register_user(data)

        result = self.app.post('/login',
                               headers={
                                   'username': '******',
                                   'password': '******'
                               })
        json_response = json.loads(result.data)
        self.assertTrue(json_response['data']['token'] is not None,
                        'error with json: (' + json.dumps(json_response) + ')')

        with flask_app.app_context():
            User.remove(json_response_reg['data']['user']['email'])
Example #14
0
def register() -> tuple:
    """

    swagger_from_file: ../swagger/login/register.yml

    Register a new user
    :return:
    """
    # import here because of circular reference
    from hopkin.models.users import User
    if request.json is not None:
        new_user = {
            'username': request.json['username'],
            'password': generate_password_hash(request.json['password']),
            'displayName': {
                'firstName': request.json['displayName']['firstName'],
                'lastName': request.json['displayName']['lastName']
            },
            'email': request.json['email'],
            'adminRights': request.json['adminRights'],
            'paymentInfo': {
                'name':
                request.json['paymentInfo']['name'],
                'cardType':
                request.json['paymentInfo']['cardType'],
                'num':
                int(request.json['paymentInfo']['num']),
                'expiry':
                datetime.datetime.strptime(
                    request.json['paymentInfo']['expiry'],
                    "%w/%m/%y %I:%M:%S %p UTC")
            },
            'address': {
                'number': int(request.json['address']['number']),
                'name': request.json['address']['name'],
                'streetType': request.json['address']['streetType'],
                'postalCode': request.json['address']['postalCode']
            }
        }
        User.save(new_user)
        return jsonify({'data': {'user': request.json}})
    else:
        return jsonify({'error': 'no username or password provided'}), 401
Example #15
0
    def test_admin_login(self):
        data = '{"username": "******","password": "******","displayName": {"firstName": "Aaron",' \
               '"lastName": "Fernandes"},"email": "*****@*****.**","adminRights": true, ' \
               '"paymentInfo": {"name": "Aaron Fernandes","cardType": "VISA","num": 451535486,' \
               '"expiry": "1/1/17 12:00:00 AM UTC"},"address":{"number": 345,"name": "Fake","streetType": ' \
               '"Street","postalCode": "M3H5R1"}}'
        json_response_reg = self.__register_user(data)

        result = self.app.post('/login',
                               headers={
                                   'username': '******',
                                   'password': '******'
                               })
        json_response = json.loads(result.data)
        self.assertTrue(json_response['data']['adminRights'],
                        'error with json: (' + json.dumps(json_response) + ')')

        with flask_app.app_context():
            User.remove(json_response_reg['data']['user']['email'])
    def test_admin_del_restaurant(self):
        json_response_reg = self.__register_user(self.__admin_user_data)
        admin_token = self.__login_user(json.loads(self.__admin_user_data))

        # add an restaurant to delete
        restaurant_id = self.__add_restaurant(self.__test_restaurant_data_1)

        result = self.app.post(
            '/admin/restaurant/delete/' + str(restaurant_id),
            headers={
                'Content-Type': 'application/json',
                'token': admin_token
            },
        )
        json_data = json.loads(result.data)
        # self.assertTrue(json_data['data']['success'] is not None, 'fail delete restaurant')
        self.assertDictEqual(json_data, {'data': {
            'success': True
        }}, 'fail delete restaurant')

        with flask_app.app_context():
            Restaurant.remove(restaurant_id)
            User.remove(json_response_reg['data']['user']['email'])
    def test_customer_profile_update(self):
        from hopkin.models.users import User

        # creating new user
        data = '{"address": {"name": "Queen", "number": 155, "postalCode": "M3E5R1", "streetType": "Street"}, ' \
               '"adminRights": false, "displayName": {"firstName": "Jane", "lastName": "Doe"}, ' \
               '"email": "*****@*****.**", "password": "******", "paymentInfo": {"cardType": "VISA", ' \
               '"expiry": "1/1/17 12:00:00 AM UTC", "name": "Jane Doe", "num": 451535486}, "username": "******"}'
        self.app.post('/login/register',
                      data=data,
                      content_type='application/json')

        # login to get token
        login_result = self.app.post('/login',
                                     headers={
                                         'username': '******',
                                         'password': '******'
                                     })
        json_response = json.loads(login_result.data)['data']['token']
        self.assertIsNotNone(json_response)

        # update user info
        updated_data = '{"address": {"name": "Baker", "number": 221, "postalCode": "M3E5R1", "streetType": "Street"}, ' \
                       '"adminRights": false, "displayName": {"firstName": "Jane", "lastName": "Doe"}, ' \
                       '"email": "*****@*****.**", "paymentInfo": {"cardType": "VISA", ' \
                       '"expiry": "1/1/17 12:00:00 AM UTC", "name": "Jane Doe", "num": 451535486}, "username": "******"}'

        result = self.app.post('/customer/profile/edit',
                               data=updated_data,
                               headers={'token': json_response})
        json_data = json.loads(result.data)
        self.assertIsNotNone(len(json_data))

        with flask_app.app_context():
            user = User.get_by_token(json_response)
            User.remove(user['email'])
Example #18
0
def customer_payment_info() -> dict:
    """

    swagger_from_file: ../swagger/customer/paymentInfo.yml

    Gets a customers payment info
    """
    from hopkin.models.users import User
    user = User.get_by_id(g.user_id)
    payment_info = user['paymentInfo']

    return jsonify({
        'data': {
            'paymentInfo': {
                'name': payment_info['name'],
                'cardType': payment_info['cardType'],
                'num': get_cc_number(payment_info['num']),
                'expiry': payment_info['expiry']
            }
        }
    })