Esempio n. 1
0
def create_user_and_get_token(email):
    os.environ['ONE_AUTH_ENV'] = 'test'
    APP.config['TESTING'] = True
    app = APP.test_client()
    Mail(APP)

    db_connection = get_db_session(APP.db_engine)
    user_service = UserService(db_connection)

    user_service.delete_user(email)
    with patch.object(one_auth.ValidationCodeService,
                      'generate_validation_code', lambda: '123456'):
        app.post('/one_auth/api/user',
                 data='{"email": "%s"}' % email,
                 content_type='application/json')

    update_data = '{"email": "%s", "validation_code": "123456", "password": "******"}' % email

    app.put('/one_auth/api/user',
            data=update_data,
            content_type='application/json')

    response = app.get(
        '/one_auth/api/access_tokens',
        content_type='application/json',
        headers={'Authorization': basic_auth(email, 'password1')})

    return json.loads(response.data.decode('utf8'))['access_token']
Esempio n. 2
0
class APIValidationCode(unittest.TestCase):
    def setUp(self):
        os.environ['ONE_AUTH_ENV'] = 'test'
        APP.config['TESTING'] = True
        self.app = APP.test_client()

        self.db_connection = get_db_session(APP.db_engine)
        self.user_service = UserService(self.db_connection)
        self.validation_code_service = ValidationCodeService(
            self.db_connection)
        self.user_service.delete_user('*****@*****.**')

    def test_use_last_validation_code_verify(self):
        with patch.object(one_auth.ValidationCodeService,
                          'generate_validation_code', lambda: '123456'):
            self.app.post('/one_auth/api/user',
                          data='{"email": "*****@*****.**"}',
                          content_type='application/json')
        code_data = '{"email": "*****@*****.**", "validation_code": "123456"}'
        response = self.app.put('/one_auth/api/validation_code',
                                data=code_data,
                                content_type='application/json')

        self.assertEquals(200, response.status_code)
        self.assertEquals(
            'active',
            self.validation_code_service.get_validation_code('123456').status)

    def test_return_422_if_code_is_invalid(self):
        self.app.post('/one_auth/api/user',
                      data='{"email": "*****@*****.**"}',
                      content_type='application/json')

        code_data = '{"email": "*****@*****.**", "validation_code": "invalid_code"}'
        response = self.app.put('/one_auth/api/validation_code',
                                data=code_data,
                                content_type='application/json')

        self.assertEquals(422, response.status_code)
Esempio n. 3
0
def get_user(user_id):
    if request.method == "GET":
        # get user
        user = UserService.get_user(user_id)
        return make_response(jsonify(user.serialize), 200)
        # update user
    if request.method == 'PUT':
        req = request.get_json()
        user = UserService.change_my_name(req, user_id)
        return user.serialize
        # delete user
    if request.method == 'DELETE':
        req = request.get_json()
        user = UserService.delete_user(req['userId'])
        return make_response(f'DELETED USER: {user}:', 200)
Esempio n. 4
0
                                          "\n\t---------------------")
                                    print(Fore.LIGHTRED_EX, "\n\tback.返回上一层")
                                    print(Fore.LIGHTRED_EX, "\n\tprev.上一页")
                                    print(Fore.LIGHTRED_EX, "\n\tnext.下一页")
                                    print(Style.RESET_ALL)
                                    opt = input("\n\t请输入操作编号:")
                                    if opt == "back":
                                        break
                                    elif opt == "prev" and page > 1:
                                        page -= 1
                                    elif opt == "next" and page < count_page:
                                        page += 1
                                    elif opt.isdigit() and 1 <= int(opt) <= 10:
                                        os.system("clear")
                                        user_id = result[int(opt) - 1][0]
                                        __user_service.delete_user(
                                            user_id=user_id)
                                        print(Fore.GREEN,
                                              "\n\t删除成功。( 3 秒后自动返回)")
                                        print(Style.RESET_ALL)
                                        time.sleep(3)
                                    else:
                                        continue
                    elif opt == "back":
                        break
                    elif opt == "exit":
                        sys.exit(0)
        else:
            print(Fore.RED, "\n\t登录失败!(3 秒后自动返回)")
            print(Style.RESET_ALL)
            time.sleep(3)
Esempio n. 5
0
def device_repo_test():

    user_service = UserService()

    print "\n\n\n=======DEVICE REPO TEST======="
    print "\ncreating a test user"
    user, msg = user_service.add_user("muhaftab", "1234", "Muhammad", "Aftab", "*****@*****.**")
    print msg

    print "adding a new device for user:  %s" % user.username
    device1 = device_repo.add_device(user.username, "TableLamp")
    print "returned device is ", device1
    device2 = device_repo.add_device(user.username, "Kettle")
    print "returned device is ", device2

    print "\nfetching the new device from db"
    device = device_repo.find_device(user.username, device1.device_id)[0]
    print device

    print "\nfetching the user to see if device is added for user"
    user = user_service.get_user(user.username)
    print [d.serialize() for d in user.devices]

    print "\nadding some consumption data for the device"
    c1 = DeviceConsumption(10.0, 0.12, False, datetime.datetime.now())
    c2 = DeviceConsumption(11.0, 2.12, True, datetime.datetime.now())
    device_repo.add_device_consumption(device, c1)
    device_repo.add_device_consumption(device, c2)

    print "\ntesting if consumption data is added to device"
    print [c.serialize() for c in device.consumption]

    print "\nModifying device"
    new_device = Device("CoffeeMaker")
    updated_device = device_repo.update_device(user.username, device.device_id, new_device)
    print updated_device

    print "\ntesting if consumption data exists for updated device"
    print [c.serialize() for c in updated_device.consumption]

    print "\nadding device model to the device"
    json_params = {"p_peak": 80.8, "p_stable": 50.0, "lambda": 0.31}
    m1 = DeviceModel("ExponentialDecay", json_params)
    device_repo.add_device_model(updated_device, m1)
    print updated_device.serialize()

    print "\nfetching the user again to see if updated device is shown"
    user = user_service.get_user(user.username)
    print user.serialize()

    print "\nfetching list of devices for the user"
    print [device.serialize() for device in user_service.get_devices(user.username)]

    print "\ndeleting device"
    status = device_repo.delete_device(user.username, device.device_id)
    print status

    print "\nfetching the user agian to see if device is indeed deleted"
    user = user_service.get_user(user.username)
    print [d for d in user.devices]

    print "\nfinally deleting user"
    status = user_service.delete_user(user.username)
    print status
Esempio n. 6
0
class OneAuthTests(unittest.TestCase):
    def setUp(self):
        os.environ['ONE_AUTH_ENV'] = 'test'
        APP.config['TESTING'] = True
        self.app = APP.test_client()
        self.mail = Mail(APP)
        self.db_connection = get_db_session(APP.db_engine)
        self.user_service = UserService(self.db_connection)
        self.validation_code_service = ValidationCodeService(self.db_connection)

    def test_should_return_415_while_not_passing_json(self):
        data = '{"email": "*****@*****.**"}'
        response = self.app.post('/one_auth/api/user', data=data, content_type='application/xml')
        self.assertEquals(415, response.status_code)

    def test_should_return_400_if_the_any_mandatory_field_is_not_exist_in_request_when_update_the_user_password(self):
        self.user_service.delete_user('*****@*****.**')
        with patch.object(one_auth.ValidationCodeService, 'generate_validation_code', lambda: '123456'):
            self.app.post('/one_auth/api/user', data='{"email": "*****@*****.**"}', content_type='application/json')

        update_data = '{"email": "*****@*****.**", "validation_code": "123456"}'
        response = self.app.put('/one_auth/api/user', data=update_data, content_type='application/json')
        self.assertEquals(400, response.status_code)

        update_data = '{"email": "*****@*****.**", "password": "******"}'
        response = self.app.put('/one_auth/api/user', data=update_data, content_type='application/json')
        self.assertEquals(400, response.status_code)

    def test_update_user_password(self):
        self.user_service.delete_user('*****@*****.**')
        with patch.object(one_auth.ValidationCodeService, 'generate_validation_code', lambda: '123456'):
            self.app.post('/one_auth/api/user', data='{"email": "*****@*****.**"}', content_type='application/json')

        update_data = '{"email": "*****@*****.**", "validation_code": "123456", "password": "******"}'

        response = self.app.put('/one_auth/api/user', data=update_data, content_type='application/json')

        self.db_connection.commit()
        created_user = self.user_service.get_user('*****@*****.**')
        response_json = json.loads(response.data.decode('utf8'))
        self.assertEquals(200, response.status_code)
        self.assertEquals('active', created_user.status)
        self.assertIsNotNone(response_json['access_token'])
        self.assertIsNotNone(created_user.password)

    def test_update_user_password_when_password_in_wrong_format(self):
        self.user_service.delete_user('*****@*****.**')
        with patch.object(one_auth.ValidationCodeService, 'generate_validation_code', lambda: '123456'):
            self.app.post('/one_auth/api/user', data='{"email": "*****@*****.**"}', content_type='application/json')

        update_data = '{"email": "*****@*****.**", "validation_code": "123456", "password": "******"}'

        response = self.app.put('/one_auth/api/user', data=update_data, content_type='application/json')

        # self.assertEquals(400, response.status_code)

    def test_create_and_get_user(self):
        self.user_service.delete_user('*****@*****.**')
        user = self.user_service.create_user('*****@*****.**')

        assert '*****@*****.**' == user.email
        self.user_service.delete_user('*****@*****.**')

    def test_should_return_access_token_when_login_with_correct_email_and_password(self):
        some_email = '*****@*****.**'
        self.user_service.delete_user(some_email)
        with patch.object(one_auth.ValidationCodeService, 'generate_validation_code', lambda : '123456'):
            self.app.post('/one_auth/api/user', data='{"email": "*****@*****.**"}', content_type='application/json')

        update_data = '{"email": "*****@*****.**", "validation_code": "123456", "password": "******"}'

        response = self.app.put('/one_auth/api/user', data=update_data, content_type='application/json')

        response = self.app.get('/one_auth/api/access_tokens', content_type='application/json',

                                headers={'Authorization': 'Basic eHh4QHRlc3QuY29tOnBhc3N3b3JkMQ=='})

        result_data = json.loads(response.data.decode('utf8'))

        self.assertEquals(200, response.status_code)
        self.assertIsNotNone(result_data['access_token'])

        self.user_service.delete_user(some_email)

    def test_should_return_401_when_login_with_incorrect_email_and_password(self):
        some_email = '*****@*****.**'
        self.user_service.delete_user(some_email)
        with patch.object(one_auth.ValidationCodeService, 'generate_validation_code', lambda : '123456'):
            self.app.post('/one_auth/api/user', data='{"email": "*****@*****.**"}', content_type='application/json')

        update_data = '{"email": "*****@*****.**", "validation_code": "123456", "password": "******"}'

        self.app.put('/one_auth/api/user', data=update_data, content_type='application/json')
        response = self.app.get('/one_auth/api/access_tokens', content_type='application/json',
                                headers={'Authorization': 'Basic OmFhYWE='})

        self.assertEquals(401, response.status_code)
        self.user_service.delete_user(some_email)

    def test_should_return_200_when_access_token_validation_success(self):
        access_token = create_user_and_get_token('*****@*****.**')
        authorization = basic_auth('*****@*****.**', access_token)

        response = self.app.get('/one_auth/api/validations', headers={
            'Authorization': authorization
        })

        self.assertEquals(200, response.status_code)

        result_data = json.loads(response.data.decode('utf8'))
        self.assertEquals('*****@*****.**', result_data['email'])
        self.assertEquals('', result_data['first_name'])
        self.assertEquals('', result_data['last_name'])
        self.assertEquals('', result_data['country'])
        self.assertEquals('', result_data['department'])
        self.assertEquals('', result_data['avatar'])

    @patch('one_auth.UserService')
    def test_should_return_401_when_access_token_validation_fail(self, mock_user_service):
        mock_user_service.encode_access_token_for = MagicMock(return_value='invalid_token')

        response = self.app.get('/one_auth/api/validations', headers={
            'Authorization': 'Basic eHh4QHRlc3QuY29tOnRlc3RfdG9rZW4='
        })

        self.assertEquals(401, response.status_code)