Exemple #1
0
class User:
    def __init__(self):
        self.database = Database()
        self.database.create_user_table()

    def create_user(self):
        """create a user account [POST]"""
        parser = reqparse.RequestParser()
        parser.add_argument('username',
                            type=str,
                            required=True,
                            help='Field cannot be blank')
        parser.add_argument('email',
                            type=str,
                            required=True,
                            help='Field cannot be blank')
        parser.add_argument('password',
                            type=str,
                            required=True,
                            help='Field cannot be blank')

        data = parser.parse_args()

        specialCharacters = ['$', '#', '@', '!', '*']

        if any(char in specialCharacters for char in (data['username'])):
            return {'message': 'username cannot have special characters'}, 400
        elif self.find_user_by_name(data['username']):
            return {'message': 'user already exists'}, 409
        elif self.find_user_by_email(data['email']):
            return {'message': 'please use another email address'}, 409
        elif data['username'].isspace() or (' ' in data['username']):
            return {'message': 'Field cannot be blank'}, 400
        elif not re.match('[^@]+@[^@]+\.[^@]+', data['email']):
            return {'message': 'Invalid email'}, 400

        self.database.cursor.execute(
            "INSERT INTO users(username, email, password)\
            VALUES('{}', '{}', '{}')\
            RETURNING userId, username, email, password".format(
                data['username'], data['email'], data['password']))

        return {'message': 'User created successfully'}, 201

    def login_user(self):
        """user login [POST]"""
        parser = reqparse.RequestParser()
        parser.add_argument('username',
                            type=str,
                            required=True,
                            help='Field cannot be blank')
        parser.add_argument('password',
                            type=str,
                            required=True,
                            help='Field cannot be blank')

        data = parser.parse_args()

        if data['username'] == 'admin' and data['password'] == 'mynameisadmin':
            token = jwt.encode(
                {
                    'username':
                    data['username'],
                    'exp':
                    datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
                }, 'adminkey')
            return {
                'message': 'welcome admin',
                'token': token.decode('utf-8')
            }, 200

        elif self.find_user_by_name(
                data['username']
        ) is None or self.find_user_by_password is None:
            return {'message': 'Please Create an account'}, 401

        elif self.find_user_by_name(
                data['username']) == self.find_user_by_password(
                    data['password']):
            token = jwt.encode(
                {
                    'username':
                    data['username'],
                    'exp':
                    datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
                }, 'customerkey')
            return {
                'message': 'You are successfully logged in',
                'token': token.decode('utf-8')
            }, 200

        return {'message': 'username or password is incorrect'}, 401

    def find_user_by_name(self, username):
        query = "SELECT * FROM  users WHERE username = '******'"
        self.database.cursor.execute(query.format(username))
        row = self.database.cursor.fetchone()
        if row:
            return row
        else:
            return None

    def find_user_by_email(self, email):
        query = "SELECT * FROM  users WHERE email = '{}'"
        self.database.cursor.execute(query.format(email))
        row = self.database.cursor.fetchone()
        if row:
            return row
        else:
            return None

    def find_user_by_password(self, password):
        query = "SELECT * FROM  users WHERE password = '******'"
        self.database.cursor.execute(query.format(password))
        row = self.database.cursor.fetchone()
        if row:
            return row
        else:
            return None
Exemple #2
0
class AppTestCase(unittest.TestCase):
    def setUp(self):
        """Initialisez app and defines variables"""
        app.testing = True
        self.tester = app.test_client()
        self.database = Database()
        self.database.create_user_table()
        # self.database.create_menu_table()
        # self.database.create_order_table()
        # self.order = {
        #     'orderId': 1, 'username': '******', 'foodId': 1, 'status': 'New'
        #     }
        # self.menu = {
        #     'foodId': 1, 'name': 'pizza', 'description': 'hawain',
        #     'price': 25000
        #     }

    def tearDown(self):
        """Crashes down all initialized variables"""
        # self.database.cursor.execute("DROP TABLE orders")
        # self.database.cursor.execute("DROP TABLE menu")
        self.database.cursor.execute("DROP TABLE users")
        self.tester = None

    def test_home(self):
        response = self.tester.get('/')
        self.assertTrue(200, response.status_code)
        self.assertIn('Welcome', str(response.data))

    # def test_neworder(self):
    #     """Tests api to place new order without token"""
    #     response = self.tester.post('/api/v1/orders', data=self.order)
    #     self.assertEqual(403, response.status_code)
    #     self.assertIn('Token is missing', str(response.data))
    
        # """Tests api to place new order with token"""
        # response = self.tester.post('/api/v1/menu',
        #                             data=self.menu,
        #                             headers=dict(Authorization='Bearer ' + GetToken.get_admin_token()))
        # response = self.tester.post('/api/v1/orders',
        #                             data=self.order,
        #                             headers=dict(Authorization='Bearer ' + GetToken.get_user_token()))
        # self.assertEqual(201, response.status_code)

    # def test_orders(self):
    #     """Tests api to get all orders without authorization"""
    #     response = self.tester.get('/api/v1/orders', data=self.order)
    #     self.assertEqual(403, response.status_code)
    #     self.assertIn('Token is missing', str(response.data))
        
    #     """Tests api to get all orders with authorization"""
    #     response = self.tester.post('/api/v1/menu',
    #                                 data=self.menu,
    #                                 headers=dict(Authorization='Bearer ' + GetToken.get_admin_token()))
    #     response = self.tester.post('/api/v1/orders',
    #                                 data=self.order,
    #                                 headers=dict(Authorization='Bearer ' + GetToken.get_user_token()))
    #     self.assertEqual(201, response.status_code)
    #     response = self.tester.get('/api/v1/orders',
    #                                data=self.order,
    #                                headers=dict(Authorization='Bearer ' + GetToken.get_admin_token()))
    #     self.assertEqual(200, response.status_code)

    # def test_no_orders(self):
    #     """test for unavailable menu"""
    #     response = self.tester.get('/api/v1/orders',
    #                                data={},
    #                                headers=dict(Authorization='Bearer ' + GetToken.get_admin_token()))
    #     self.assertEqual(404, response.status_code)
    #     self.assertIn('No orders found', str(response.data))

    # def test_history(self):
    #     """test api to get order history"""
    #     response = self.tester.get('/api/v1/users/orders', data=self.order)
    #     self.assertEqual(403, response.status_code)
    #     self.assertIn(b'Token is missing', response.data)

    #     """test api to get order history with token"""
    #     response = self.tester.post('/api/v1/menu',
    #                                 data=self.menu,
    #                                 headers=dict(Authorization='Bearer ' + GetToken.get_admin_token()))
    #     response = self.tester.post('/api/v1/orders',
    #                                 data=self.order,
    #                                 headers=dict(Authorization='Bearer ' + GetToken.get_user_token()))
    #     self.assertEqual(201, response.status_code)
    #     response = self.tester.get('/api/v1/users/orders',
    #                                data=self.order,
    #                                headers=dict(Authorization='Bearer ' + GetToken.get_user_token()))
    #     self.assertEqual(200, response.status_code)

    # def test_no_order_history(self):
    #     """test no order history"""
    #     response = self.tester.post('/api/v1/menu',
    #                                 data=self.menu,
    #                                 headers=dict(Authorization='Bearer ' + GetToken.get_admin_token()))
    #     response = self.tester.get('/api/v1/users/orders',
    #                                data=self.order,
    #                                headers=dict(Authorization='Bearer ' + GetToken.get_user_token()))
    #     self.assertEqual(404, response.status_code)
    #     self.assertIn('No Previous Orders', str(response.data))

    # def test_get_order(self):
    #     """Tests api to get a specific order"""
    #     response = self.tester.get('/api/v1/orders/1', data=self.order)
    #     self.assertEqual(response.status_code, 403)
    #     self.assertIn('Token is missing', str(response.data))

    #     """Tests api to get a specific order with token"""
    #     response = self.tester.post('/api/v1/menu',
    #                                 data=self.menu,
    #                                 headers=dict(Authorization='Bearer ' + GetToken.get_admin_token()))
    #     response = self.tester.post('/api/v1/orders',
    #                                 data=self.order,
    #                                 headers=dict(Authorization='Bearer ' + GetToken.get_user_token()))
    #     self.assertEqual(201, response.status_code)
    #     response = self.tester.get('/api/v1/orders/1',
    #                                 data=self.order,
    #                                 headers=dict(Authorization='Bearer ' + GetToken.get_admin_token()))
    #     self.assertEqual(response.status_code, 200)

    #     """test non existing order"""
    #     response = self.tester.get('/api/v1/orders/7',
    #                                 data=self.order,
    #                                 headers=dict(Authorization='Bearer ' + GetToken.get_admin_token()))
    #     self.assertEqual(response.status_code, 404)
    #     self.assertIn('The order you requested does not exist', str(response.data))

    # def test_put(self):
    #     """Tests api to edit and already existing order with token"""
    #     response = self.tester.put('/api/v1/orders/1',data=self.order)
    #     self.assertEqual(response.status_code, 403)
    #     self.assertIn('Token is missing', str(response.data))

    #     """Tests api to edit and already existing order with token"""
    #     response = self.tester.put('/api/v1/orders/1', data={'status': 'complete'},
    #                                 headers=dict(Authorization='Bearer ' + GetToken.get_admin_token()))
    #     self.assertEqual(response.status_code, 200)
    #     self.assertIn('Order status has been updated', str(response.data))

    #     """test update input validation"""
    #     response = self.tester.put('/api/v1/orders/1', data={'status': '  '},
    #                                 headers=dict(Authorization='Bearer ' + GetToken.get_admin_token()))
    #     self.assertEqual(response.status_code, 400)
    #     self.assertIn('Field cannot be blank', str(response.data))

    # def test_delete(self):
    #     """Test api to delete an order without token"""
    #     response = self.tester.delete('/api/v1/orders/1', data=self.order)
    #     self.assertEqual(403, response.status_code)

    #     """Test api to delete an order with token"""
    #     response = self.tester.delete('/api/v1/orders/1',
    #                                   data=self.order,
    #                                   headers=dict(Authorization='Bearer ' + GetToken.get_user_token()))
    #     self.assertEqual(200, response.status_code)
    #     self.assertIn('Order has been deleted', str(response.data))