def initialize_db(): Base.metadata.create_all(DBSession.bind.engine) if not DBSession.query(User).filter_by(username='******').count(): with transaction.manager: admin = User(username='******', is_admin=True) admin.set_password('admin') DBSession.add(admin)
def setUp(self): super().setUp() testuser = User(username='******', password='******', email='user@host') self.session.add(testuser) testuserw = User(username='******', password='******') self.session.add(testuserw)
def setUp(self): self.config = testing.setUp() self.session = setup_database() with transaction.manager: self.u = User(username='******', password='******') DBSession.add(self.u) self.pu = User(username='******', password='******') self.pu.add_paid_time(datetime.timedelta(days=30)) DBSession.add(self.pu)
def setUp(self): self.config = testing.setUp() self.session = setup_database() self.u = User(username='******', password='******') DBSession.add(self.u) self.session.flush() self.pu = User(username='******', password='******') self.pu.add_paid_time(datetime.timedelta(days=30)) DBSession.add(self.pu) self.session.flush()
def setUp(self): super().setUp() self.u = User(username='******', password='******') DBSession.add(self.u) self.session.flush() self.pu = User(username='******', password='******') self.pu.add_paid_time(datetime.timedelta(days=30)) DBSession.add(self.pu) self.session.flush()
def setUp(self): super().setUp() self.testuser = User(username='******', password='******') self.session.add(self.testuser) self.testadmin = User(username='******', password='******') self.testadmin.is_admin = True self.session.add(self.testadmin) self.session.flush() self.testcode = GiftCode(datetime.timedelta(days=7)) self.session.add(self.testcode) self.session.flush()
def test_paid(self): user = User() self.assertFalse(user.is_paid) self.assertEqual(user.paid_days_left(), 0) user.add_paid_time(datetime.timedelta(days=1)) self.assertTrue(user.is_paid) self.assertEqual(user.paid_days_left(), 1) user.paid_until = datetime.datetime.fromtimestamp(1) user.add_paid_time(datetime.timedelta(days=1)) self.assertTrue(user.is_paid) self.assertEqual(user.paid_days_left(), 1)
def setUp(self): settings = {'mako.directories': 'ccvpn:templates/'} self.config = testing.setUp(settings=settings) setup_routes(self.config) self.session = setup_database() self.testuser = User(username='******', password='******') self.session.add(self.testuser) self.testadmin = User(username='******', password='******') self.testadmin.is_admin = True self.session.add(self.testadmin) self.session.flush() self.testcode = GiftCode(datetime.timedelta(days=7)) self.session.add(self.testcode) self.session.flush()
def setUp(self): super().setUp() self.testuser = User(username='******', password='******') self.session.add(self.testuser) self.testorder = models.Order(user=self.testuser.id, amount=2, method=models.Order.METHOD.BITCOIN, time=timedelta(days=30))
def setUp(self): self.config = testing.setUp() setup_routes(self.config) self.session = setup_database() self.testuser = User(username='******', password='******') self.session.add(self.testuser) self.session.flush()
def setUp(self): self.config = testing.setUp() setup_routes(self.config) self.session = setup_database() self.paiduser = User(username='******', password='******') self.paiduser.add_paid_time(datetime.timedelta(days=30)) self.session.add(self.paiduser) self.session.flush() self.profile = Profile(uid=self.paiduser.id, name='testprofile') self.session.add(self.profile) self.freeuser = User(username='******', password='******') self.session.add(self.freeuser) duser = User(username='******', password='******') duser.is_active = False duser.add_paid_time(datetime.timedelta(days=30)) self.session.add(duser) self.gw0 = Gateway(name='gw0', token='simple_gateway', isp_name='', isp_url='', country='') self.session.add(self.gw0) self.gw1 = Gateway(name='gw1', token='disabled_gateway', isp_name='', isp_url='', country='') self.gw1.enabled = False self.session.add(self.gw1) self.gw2 = Gateway(name='gw2', token='ipv4_gateway', isp_name='', isp_url='', country='', ipv4='1.2.3.4') self.session.add(self.gw2) self.gw3 = Gateway(name='gw3', token='ipv6_gateway', isp_name='', isp_url='', country='', ipv6='1:2:3:4:5:6:7:8') self.session.add(self.gw3) self.session.flush() self.testheaders = { 'X-Gateway-Token': 'simple_gateway', 'X-Gateway-Version': 'alpha', }
def setUp(self): settings = { 'mail.default_sender': 'root@lo', 'mako.directories': 'ccvpn:templates/' } self.config = testing.setUp(settings=settings) setup_routes(self.config) self.config.include('pyramid_mailer.testing') self.session = setup_database() with transaction.manager: testuser = User(username='******', password='******', email='user@host') self.session.add(testuser) testuserw = User(username='******', password='******') self.session.add(testuserw)
def test_send(self): registry = self.config.registry mailer = get_mailer(registry) u = User(username='******', email='*****@*****.**', paid_until=datetime.now()+timedelta(days=4)) expire_mail.send_notice(u, mailer) self.assertEqual(len(mailer.outbox), 1) self.assertIn('test_user_1', mailer.outbox[0].body) self.assertIn('*****@*****.**', mailer.outbox[0].recipients) u = User(username='******', email='*****@*****.**', paid_until=datetime.now()+timedelta(days=-4)) expire_mail.send_notice(u, mailer) self.assertEqual(len(mailer.outbox), 2) self.assertIn('test_user_2', mailer.outbox[1].body) self.assertIn('*****@*****.**', mailer.outbox[1].recipients)
def setUp(self): super().setUp() testuser = User(username='******', password='******', email='user@host') self.session.add(testuser) self.session.flush() self.token = PasswordResetToken(uid=testuser.id) self.session.add(self.token) self.session.flush()
def setUp(self): super().setUp() self.testuser = User(username='******', password='******') self.session.add(self.testuser) self.session.flush() profile = Profile(uid=self.testuser.id, name='testprofile') self.session.add(profile) self.session.flush()
def setUp(self): self.config = testing.setUp() self.session = setup_database() with transaction.manager: self.testuser = User(username='******', password='******') self.session.add(self.testuser) self.testorder = models.Order(user=self.testuser.id, amount=2, method=models.Order.METHOD.BITCOIN, time=datetime.timedelta(days=30))
class TestGiftCodeModel(unittest.TestCase): def setUp(self): self.config = testing.setUp() self.session = setup_database() self.u = User(username='******', password='******') DBSession.add(self.u) self.session.flush() self.pu = User(username='******', password='******') self.pu.add_paid_time(datetime.timedelta(days=30)) DBSession.add(self.pu) self.session.flush() def tearDown(self): testing.tearDown() self.session.remove() def test_username_if_used(self): gc = GiftCode() self.assertIs(gc.username_if_used, False) gc.used = self.u.id gc.user = self.u self.assertEqual(gc.username_if_used, self.u.username) def test_use_freeonly(self): gc = GiftCode() gc.free_only = True self.assertRaises(models.AlreadyUsedGiftCode, gc.use, self.pu) gc.use(self.u) self.assertTrue(self.u.is_paid) def test_use_reuse(self): time = datetime.timedelta(days=30, hours=11) gc = GiftCode(time=time) gc.use(self.u) self.assertEqual(self.u.paid_time_left().days, time.days) self.assertRaises(models.AlreadyUsedGiftCode, gc.use, self.u) self.assertEqual(self.u.paid_time_left().days, time.days) gc.use(self.u, reuse=True) self.assertTrue(self.u.is_paid) self.assertEqual(self.u.paid_time_left().days, time.days*2)
class TestGiftCodeModel(unittest.TestCase): def setUp(self): self.config = testing.setUp() self.session = setup_database() self.u = User(username='******', password='******') DBSession.add(self.u) self.session.flush() self.pu = User(username='******', password='******') self.pu.add_paid_time(datetime.timedelta(days=30)) DBSession.add(self.pu) self.session.flush() def tearDown(self): testing.tearDown() self.session.remove() def test_username_if_used(self): gc = GiftCode() self.assertIs(gc.username_if_used, False) gc.used = self.u.id gc.user = self.u self.assertEqual(gc.username_if_used, self.u.username) def test_use_freeonly(self): gc = GiftCode() gc.free_only = True self.assertRaises(models.AlreadyUsedGiftCode, gc.use, self.pu) gc.use(self.u) self.assertTrue(self.u.is_paid) def test_use_reuse(self): time = datetime.timedelta(days=30, hours=11) gc = GiftCode(time=time) gc.use(self.u) self.assertEqual(self.u.paid_time_left().days, time.days) self.assertRaises(models.AlreadyUsedGiftCode, gc.use, self.u) self.assertEqual(self.u.paid_time_left().days, time.days) gc.use(self.u, reuse=True) self.assertTrue(self.u.is_paid) self.assertEqual(self.u.paid_time_left().days, time.days * 2)
def setUp(self): self.config = testing.setUp() setup_routes(self.config) self.session = setup_database() with transaction.manager: user = User(username='******', password='******') user.add_paid_time(datetime.timedelta(days=30)) baduser = User(username='******', password='******') self.session.add(user) self.session.add(baduser) with transaction.manager: token = APIAccessToken(token='apitoken') self.session.add(token) restricted_token = APIAccessToken(token='restricted_apitoken') restricted_token.remote_addr = '127.0.0.1' self.session.add(restricted_token) with transaction.manager: profile = Profile(uid=user.id, name='testprofile') self.session.add(profile)
def setUp(self): settings = {'mako.directories': 'ccvpn:templates/'} self.config = testing.setUp(settings=settings) setup_routes(self.config) self.session = setup_database() self.testuser = User(username='******', password='******') self.session.add(self.testuser) self.session.flush() profile = Profile(uid=self.testuser.id, name='testprofile') self.session.add(profile) self.session.flush()
def test_existing_email(self): u = User(username='******', email='user@host', password='******') self.session.add(u) req = DummyRequest( post={ 'username': '******', 'password': '******', 'password2': 'newpw', 'email': 'user@host' }) resp = views.account.signup(req) self.assertIsInstance(resp, dict) self.assertEqual(req.response.status_code, 400)
def test_expired(self): u_exp = User(username='******', password='******', email='.', paid_until=datetime.now()-timedelta(days=5)) u_expl = User(username='******', password='******', email='.', paid_until=datetime.now()-timedelta(days=5), last_expiry_notice=datetime.now()-timedelta(days=12)) u_expll = User(username='******', password='******', email='.', paid_until=datetime.now()-timedelta(days=5), last_expiry_notice=datetime.now()-timedelta(days=1)) u_expf = User(username='******', password='******', email='.', paid_until=datetime.now()+timedelta(days=5)) self.session.add_all([u_exp, u_expl, u_expll, u_expf]) u_exp = self.session.query(User).filter_by(username='******').one() u_expl = self.session.query(User).filter_by(username='******').one() u_expll = self.session.query(User).filter_by(username='******').one() u_expf = self.session.query(User).filter_by(username='******').one() users = expire_mail.get_expired() self.assertIn(u_exp, users) self.assertIn(u_expl, users) self.assertNotIn(u_expll, users) self.assertNotIn(u_expf, users)
def setUp(self): settings = { 'mail.default_sender': 'root@lo', 'mako.directories': 'ccvpn:templates/' } self.config = testing.setUp(settings=settings) setup_routes(self.config) self.config.include('pyramid_mailer.testing') self.session = setup_database() testuser = User(username='******', password='******', email='user@host') self.session.add(testuser) self.session.flush() self.token = PasswordResetToken(uid=testuser.id) self.session.add(self.token) self.session.flush()
def signup(request): ## TODO: seriously needs refactoring _ = request.translate if request.method != 'POST': return {} errors = [] try: username = request.POST.get('username') password = request.POST.get('password') password2 = request.POST.get('password2') email = request.POST.get('email') if not User.validate_username(username): errors.append(_('Invalid username.')) if not User.validate_password(password): errors.append(_('Invalid password.')) if email and not User.validate_email(email): errors.append(_('Invalid email address.')) if password != password2: errors.append(_('Both passwords do not match.')) assert not errors used = User.is_used(username, email) if used[0] > 0: errors.append(_('Username already registered.')) if used[1] > 0 and email: errors.append(_('E-mail address already registered.')) assert not errors with transaction.manager: u = User(username=username, email=email, password=password) if request.referrer: u.referrer_id = request.referrer.id DBSession.add(u) DBSession.flush() dp = Profile(uid=u.id, name='') DBSession.add(dp) request.session['uid'] = u.id return HTTPSeeOther(location=request.route_url('account')) except AssertionError: for error in errors: request.messages.error(error) fields = ('username', 'password', 'password2', 'email') request.response.status_code = HTTPBadRequest.code return {k: request.POST[k] for k in fields}
def test_view_not_owned(self): otheruser = User(username='******', password='******') self.session.add(otheruser) self.session.flush() testorder = Order(user=otheruser.id, amount=1, method=Order.METHOD.PAYPAL, time=datetime.timedelta(days=30)) self.session.add(testorder) self.session.flush() req = DummyRequest() req.session['uid'] = self.testuser.id req.matchdict['hexid'] = '%x' % testorder.id resp = views.order.order_view(req) self.assertIsInstance(resp, httpexceptions.HTTPUnauthorized)
def reset(request): _ = request.translate token = DBSession.query(PasswordResetToken) \ .filter_by(token=request.matchdict['token']) \ .first() if not token or not token.user: request.messages.error(_('Unknown password reset token.')) url = request.route_url('account_forgot') return HTTPMovedPermanently(location=url) password = request.POST.get('password') password2 = request.POST.get('password2') if request.method != 'POST' or not password or not password2: return {'token': token} if not User.validate_password(password) or password != password2: request.messages.error(_('Invalid password.')) request.response.status_code = HTTPBadRequest.code return {'token': token} token.user.set_password(password) mailer = get_mailer(request) body = render('mail/password_reset_done.mako', { 'user': token.user, 'changed_by': request.remote_addr, }, request=request) message = Message(subject=_('CCVPN: Password changed'), recipients=[token.user.email], body=body) mailer.send(message) msg = _('You have changed the password for ${user}.', mapping={'user': token.user.username}) msg += ' ' + _('You can now log in.') request.messages.info(msg) DBSession.delete(token) url = request.route_url('account_login') return HTTPMovedPermanently(location=url)
def test_valid_referral(self): with transaction.manager: _referrer = User(username='******', password='******') self.session.add(_referrer) referrer = self.session.query(User).filter_by(username='******').first() self.assertFalse(referrer.is_paid) req = DummyRequest(post={ 'username': '******', 'password': '******', 'password2': 'newpw', 'email': 'email@host' }, params={ 'ref': str(referrer.id), }) resp = views.account.signup(req) newuser = self.session.query(User).filter_by(username='******') \ .first() self.assertIsInstance(resp, httpexceptions.HTTPSeeOther) self.assertTrue(resp.location.endswith('/account/')) self.assertEqual(newuser.referrer_id, referrer.id) self.assertFalse(referrer.is_paid) testorder = Order(user=newuser, amount=1, method=Order.METHOD.BITCOIN, time=datetime.timedelta(days=30)) self.session.add(testorder) self.session.add(referrer) self.session.flush() testorder.close(force=True) self.session.flush() self.session.refresh(referrer) self.assertTrue(referrer.is_paid)
def test_construct(self): user = User(username='******', password='******') self.assertEqual(user.username, 'test') self.assertTrue(user.check_password('pw')) self.assertFalse(user.check_password('!pw'))
def test_future(self): days = 7 u_exp5 = User(username='******', password='******', email='.') u_exp5.add_paid_time(timedelta(days=5)) self.session.add(u_exp5) u_exp10 = User(username='******', password='******', email='.') u_exp10.add_paid_time(timedelta(days=10)) self.session.add(u_exp10) # Same, with last_expiry_notice u_exp5l = User(username='******', password='******', email='.') u_exp5l.last_expiry_notice = datetime.now() - timedelta(days=1) u_exp5l.add_paid_time(timedelta(days=5)) self.session.add(u_exp5l) u_exp5ll = User(username='******', password='******', email='.') u_exp5ll.last_expiry_notice = datetime.now() - timedelta(days=30) u_exp5ll.add_paid_time(timedelta(days=5)) self.session.add(u_exp5ll) u_exp5 = self.session.query(User).filter_by(username='******').one() u_exp10 = self.session.query(User).filter_by(username='******').one() u_exp5l = self.session.query(User).filter_by(username='******').one() u_exp5ll = self.session.query(User).filter_by(username='******').one() users = expire_mail.get_future_expire(days) self.assertIn(u_exp5, users) self.assertNotIn(u_exp10, users) self.assertNotIn(u_exp5l, users) self.assertIn(u_exp5ll, users)
def test_is_used(self): r = User.is_used('test', 'test@host') self.assertGreater(r[0], 0) self.assertGreater(r[1], 0)
def test_validation(self): self.assertTrue(User.validate_username('username')) self.assertFalse(User.validate_username('username/')) self.assertFalse(User.validate_username('')) self.assertFalse(User.validate_username(None)) self.assertTrue(User.validate_email('user@host')) self.assertFalse(User.validate_email('user host')) self.assertFalse(User.validate_email('')) self.assertFalse(User.validate_email(None)) self.assertTrue(User.validate_password('password')) self.assertFalse(User.validate_password('')) self.assertFalse(User.validate_password(None))
def test_password(self): user = User() self.assertFalse(user.check_password('')) user.set_password('pw') self.assertTrue(user.check_password('pw')) self.assertFalse(user.check_password('!pw'))
def setUp(self): super().setUp() self.testuser = User(username='******', password='******') self.session.add(self.testuser) self.session.flush()
def setUp(self): super().setUp() u = User(username='******', email='test@host', password='******') DBSession.add(u) self.session.flush()
class TestAPIViews(BaseTest): def setUp(self): super().setUp() self.paiduser = User(username='******', password='******') self.paiduser.add_paid_time(datetime.timedelta(days=30)) self.session.add(self.paiduser) self.session.flush() self.profile = Profile(uid=self.paiduser.id, name='testprofile') self.session.add(self.profile) self.freeuser = User(username='******', password='******') self.session.add(self.freeuser) duser = User(username='******', password='******') duser.is_active = False duser.add_paid_time(datetime.timedelta(days=30)) self.session.add(duser) self.gw0 = Gateway(name='gw0', token='simple_gateway', isp_name='', isp_url='', country='') self.session.add(self.gw0) self.gw1 = Gateway(name='gw1', token='disabled_gateway', isp_name='', isp_url='', country='') self.gw1.enabled = False self.session.add(self.gw1) self.gw2 = Gateway(name='gw2', token='ipv4_gateway', isp_name='', isp_url='', country='', ipv4='1.2.3.4') self.session.add(self.gw2) self.gw3 = Gateway(name='gw3', token='ipv6_gateway', isp_name='', isp_url='', country='', ipv6='1:2:3:4:5:6:7:8') self.session.add(self.gw3) self.session.flush() self.testheaders = { 'X-Gateway-Token': 'simple_gateway', 'X-Gateway-Version': 'alpha', } def assertSessionExists(self, **kwargs): sess = self.session.query(VPNSession) sess = sess.filter_by(**kwargs) sess = sess.all() self.assertGreaterEqual(len(sess), 1, msg='No session found for ' + str(kwargs)) def assertNSessionExists(self, n, **kwargs): sess = self.session.query(VPNSession) sess = sess.filter_by(**kwargs) sess = sess.all() msg = '%d != %d sessions found for %s' % (len(sess), n, str(kwargs)) self.assertEqual(len(sess), n, msg=msg) def test_api_auth(self): fn = views.api.require_api_token(None)(lambda req: True) req = DummyRequest(headers={ 'X-Gateway-Token': 'simple_gateway', 'X-Gateway-Version': 'alpha', }) self.assertEqual(fn(req), True) # Invalid or missing headers req = DummyRequest(headers={ 'X-Gateway-Token': 'simple_gateway', 'X-Gateway-Version': 'something_else', }) self.assertIsInstance(fn(req), httpexceptions.HTTPBadRequest) req = DummyRequest(headers={ 'X-Gateway-Version': 'alpha', }) self.assertIsInstance(fn(req), httpexceptions.HTTPBadRequest) req = DummyRequest(headers={ 'X-Gateway-Token': 'simple_gateway', }) self.assertIsInstance(fn(req), httpexceptions.HTTPBadRequest) # Invalid header content req = DummyRequest(headers={ 'X-Gateway-Token': 'unknown_gateway', 'X-Gateway-Version': 'alpha', }) self.assertIsInstance(fn(req), httpexceptions.HTTPForbidden) req = DummyRequest(headers={ 'X-Gateway-Token': 'disabled_gateway', 'X-Gateway-Version': 'alpha', }) self.assertIsInstance(fn(req), httpexceptions.HTTPForbidden) # Invalid source address req = DummyRequest(headers={ 'X-Gateway-Token': 'ipv4_gateway', 'X-Gateway-Version': 'alpha', }, remote_addr='1.2.3.4') self.assertEqual(fn(req), True) req = DummyRequest(headers={ 'X-Gateway-Token': 'ipv4_gateway', 'X-Gateway-Version': 'alpha', }, remote_addr='4.3.2.1') self.assertIsInstance(fn(req), httpexceptions.HTTPForbidden) req = DummyRequest(headers={ 'X-Gateway-Token': 'ipv6_gateway', 'X-Gateway-Version': 'alpha', }, remote_addr='1:2:3:4:5:6:7:8') self.assertEqual(fn(req), True) req = DummyRequest(headers={ 'X-Gateway-Token': 'ipv6_gateway', 'X-Gateway-Version': 'alpha', }, remote_addr='8:7:6:5:4:3:2:1') self.assertIsInstance(fn(req), httpexceptions.HTTPForbidden) def test_auth(self): req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'password': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPBadRequest) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'password': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'password': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'password': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'password': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) self.assertEqual(resp.body, b'') def test_connect(self): req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '1.2.3.4', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertSessionExists(user_id=self.paiduser.id, disconnect_date=None) req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '1.2.3.4', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '1.2.3.4', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) req = DummyRequest(headers=self.testheaders, post={ 'username': '******', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPBadRequest) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'remote_addr': '', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPBadRequest) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) self.assertEqual(resp.body, b'') def test_disconnect_one(self): req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '1.2.3.4', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertNSessionExists(1, user_id=self.paiduser.id, disconnect_date=None) # Missing POST data req = DummyRequest(headers=self.testheaders, post={ 'username': '******', }) resp = views.api.api_gateway_disconnect(req) self.assertIsInstance(resp, httpexceptions.HTTPBadRequest) self.assertNSessionExists(1, user_id=self.paiduser.id, disconnect_date=None) req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'bytes_up': 1337, 'bytes_down': 42, }) resp = views.api.api_gateway_disconnect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertNSessionExists(0, user_id=self.paiduser.id, disconnect_date=None) def test_disconnect_multiple(self): req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '1.2.3.4', }) resp = views.api.api_gateway_connect(req) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertNSessionExists(2, user_id=self.paiduser.id, disconnect_date=None) req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'bytes_up': 0, 'bytes_down': 0, }) resp = views.api.api_gateway_disconnect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertNSessionExists(0, user_id=self.paiduser.id, disconnect_date=None)
class TestAPIViews(BaseTest): def setUp(self): super().setUp() self.paiduser = User(username='******', password='******') self.paiduser.add_paid_time(datetime.timedelta(days=30)) self.session.add(self.paiduser) self.session.flush() self.profile = Profile(uid=self.paiduser.id, name='testprofile') self.session.add(self.profile) self.freeuser = User(username='******', password='******') self.session.add(self.freeuser) duser = User(username='******', password='******') duser.is_active = False duser.add_paid_time(datetime.timedelta(days=30)) self.session.add(duser) self.gw0 = Gateway(name='gw0', token='simple_gateway', isp_name='', isp_url='', country='') self.session.add(self.gw0) self.gw1 = Gateway(name='gw1', token='disabled_gateway', isp_name='', isp_url='', country='') self.gw1.enabled = False self.session.add(self.gw1) self.gw2 = Gateway(name='gw2', token='ipv4_gateway', isp_name='', isp_url='', country='', ipv4='1.2.3.4') self.session.add(self.gw2) self.gw3 = Gateway(name='gw3', token='ipv6_gateway', isp_name='', isp_url='', country='', ipv6='1:2:3:4:5:6:7:8') self.session.add(self.gw3) self.session.flush() self.testheaders = { 'X-Gateway-Token': 'simple_gateway', 'X-Gateway-Version': 'alpha', } def assertSessionExists(self, **kwargs): sess = self.session.query(VPNSession) sess = sess.filter_by(**kwargs) sess = sess.all() self.assertGreaterEqual(len(sess), 1, msg='No session found for ' + str(kwargs)) def assertNSessionExists(self, n, **kwargs): sess = self.session.query(VPNSession) sess = sess.filter_by(**kwargs) sess = sess.all() msg = '%d != %d sessions found for %s' % (len(sess), n, str(kwargs)) self.assertEqual(len(sess), n, msg=msg) def test_api_auth(self): fn = views.api.require_api_token(None)(lambda req: True) req = DummyRequest(headers={ 'X-Gateway-Token': 'simple_gateway', 'X-Gateway-Version': 'alpha', }) self.assertEqual(fn(req), True) # Invalid or missing headers req = DummyRequest( headers={ 'X-Gateway-Token': 'simple_gateway', 'X-Gateway-Version': 'something_else', }) self.assertIsInstance(fn(req), httpexceptions.HTTPBadRequest) req = DummyRequest(headers={ 'X-Gateway-Version': 'alpha', }) self.assertIsInstance(fn(req), httpexceptions.HTTPBadRequest) req = DummyRequest(headers={ 'X-Gateway-Token': 'simple_gateway', }) self.assertIsInstance(fn(req), httpexceptions.HTTPBadRequest) # Invalid header content req = DummyRequest(headers={ 'X-Gateway-Token': 'unknown_gateway', 'X-Gateway-Version': 'alpha', }) self.assertIsInstance(fn(req), httpexceptions.HTTPForbidden) req = DummyRequest(headers={ 'X-Gateway-Token': 'disabled_gateway', 'X-Gateway-Version': 'alpha', }) self.assertIsInstance(fn(req), httpexceptions.HTTPForbidden) # Invalid source address req = DummyRequest(headers={ 'X-Gateway-Token': 'ipv4_gateway', 'X-Gateway-Version': 'alpha', }, remote_addr='1.2.3.4') self.assertEqual(fn(req), True) req = DummyRequest(headers={ 'X-Gateway-Token': 'ipv4_gateway', 'X-Gateway-Version': 'alpha', }, remote_addr='4.3.2.1') self.assertIsInstance(fn(req), httpexceptions.HTTPForbidden) req = DummyRequest(headers={ 'X-Gateway-Token': 'ipv6_gateway', 'X-Gateway-Version': 'alpha', }, remote_addr='1:2:3:4:5:6:7:8') self.assertEqual(fn(req), True) req = DummyRequest(headers={ 'X-Gateway-Token': 'ipv6_gateway', 'X-Gateway-Version': 'alpha', }, remote_addr='8:7:6:5:4:3:2:1') self.assertIsInstance(fn(req), httpexceptions.HTTPForbidden) def test_auth(self): req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'password': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPBadRequest) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'password': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'password': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'password': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'password': '******', }) resp = views.api.api_gateway_auth(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) self.assertEqual(resp.body, b'') def test_connect(self): req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '1.2.3.4', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertSessionExists(user_id=self.paiduser.id, disconnect_date=None) req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '1.2.3.4', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '1.2.3.4', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) req = DummyRequest(headers=self.testheaders, post={ 'username': '******', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPBadRequest) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'remote_addr': '', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPBadRequest) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) self.assertEqual(resp.body, b'') req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPForbidden) self.assertEqual(resp.body, b'') def test_disconnect_one(self): req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '1.2.3.4', }) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertNSessionExists(1, user_id=self.paiduser.id, disconnect_date=None) # Missing POST data req = DummyRequest(headers=self.testheaders, post={ 'username': '******', }) resp = views.api.api_gateway_disconnect(req) self.assertIsInstance(resp, httpexceptions.HTTPBadRequest) self.assertNSessionExists(1, user_id=self.paiduser.id, disconnect_date=None) req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'bytes_up': 1337, 'bytes_down': 42, }) resp = views.api.api_gateway_disconnect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertNSessionExists(0, user_id=self.paiduser.id, disconnect_date=None) def test_disconnect_multiple(self): req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'remote_addr': '1.2.3.4', }) resp = views.api.api_gateway_connect(req) resp = views.api.api_gateway_connect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertNSessionExists(2, user_id=self.paiduser.id, disconnect_date=None) req = DummyRequest(headers=self.testheaders, post={ 'username': '******', 'bytes_up': 0, 'bytes_down': 0, }) resp = views.api.api_gateway_disconnect(req) self.assertIsInstance(resp, httpexceptions.HTTPOk) self.assertNSessionExists(0, user_id=self.paiduser.id, disconnect_date=None)