Commit f173cf09 authored by Gael Pasgrimaud's avatar Gael Pasgrimaud
Browse files

improvments & testing

parent 2880758b
......@@ -4,11 +4,12 @@
{% block twothird %}
<h2>{% trans "Manage hotspot configuration" %}</h2>
<form action="." method="POST">
{% if form %}
<form id="wpa_config" action="." method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="update_wpa_config" value="{% trans 'Update hotspot configuration' %}">
</form>
{% endif %}
{% endblock twothird %}
import pytest
from ..wifi import WPAConfig
from ..backup import Backup
DATA_ROOT = 'ideascube/serveradmin/tests/data'
......@@ -10,3 +11,24 @@ def backup(monkeypatch):
monkeypatch.setattr('ideascube.serveradmin.backup.Backup.ROOT', DATA_ROOT)
# ZIP file should be shipped by git in serveradmin/tests/data
return Backup('musasa-0.1.0-201501241620.zip')
@pytest.fixture
def wpa_config(request):
path = WPAConfig.configfile
WPAConfig.configfile = '/tmp/hostapd.conf'
with open(WPAConfig.configfile, 'w') as fd:
fd.write('''
# some comment
wpa = 2
wpa_passphrase = pwa
wpa_key_mgmt = WPA-PSK
rsn_pairwise = CCMP
''')
def fin():
WPAConfig.configfile = path
request.addfinalizer(fin)
return WPAConfig()
......@@ -4,6 +4,7 @@ import zipfile
import pytest
from webtest.forms import Checkbox, Upload
from mock import MagicMock
from mock import patch
from django.core.urlresolvers import reverse
from django.core.files.base import ContentFile
......@@ -456,3 +457,52 @@ def test_staff_forgets_non_existing_connection(mocker, staffapp):
assert u'No known Wi-Fi networks' not in res.unicode_body
assert u'my home network' in res.unicode_body
assert u'random open network' in res.unicode_body
def test_wpa_config(staffapp, wpa_config):
resp = staffapp.get(reverse('server:wpa_config'))
form = resp.forms['wpa_config']
assert form['enable'].checked is True
assert form['passphrase'].value == 'pwa'
form['passphrase'] = 'newsecret'
resp = form.submit()
resp = resp.follow()
resp.mustcontain('Hotspot is now enabled with passphrase newsecret.')
form = resp.forms['wpa_config']
assert form['enable'].checked is True
assert form['passphrase'].value == 'newsecret'
form['enable'] = False
resp = form.submit()
resp = resp.follow()
resp.mustcontain('Hotspot is now disabled.')
form = resp.forms['wpa_config']
assert form['enable'].checked is False
assert form['passphrase'].value == 'newsecret'
def test_wpa_config_file_missing(staffapp, wpa_config):
wpa_config.__class__.configfile = '/xyz/missing'
resp = staffapp.get(reverse('server:wpa_config'))
resp.mustcontain('Hotspot configuration not found.')
def test_wpa_config_password_required(staffapp, wpa_config):
resp = staffapp.get(reverse('server:wpa_config'))
form = resp.forms['wpa_config']
form['passphrase'] = ''
resp = form.submit()
resp.mustcontain('This field is required.')
def test_wpa_config_file_not_writeable(staffapp, wpa_config):
resp = staffapp.get(reverse('server:wpa_config'))
form = resp.forms['wpa_config']
patcher = patch('ideascube.serveradmin.views.WPAConfig.save',
side_effect=IOError('Permission denied'))
patcher.start()
resp = form.submit().follow()
resp.mustcontain('We are not able to change hotspot configuration.')
patcher.stop()
......@@ -446,3 +446,27 @@ def test_get_multiple_wifi_devices(mocker):
with pytest.raises(WifiError):
get_wifi_device()
def test_wpa_config(wpa_config):
print(wpa_config.configfile)
assert wpa_config.is_enabled is True
assert wpa_config.get_passphrase() == 'pwa'
wpa_config.change_passphrase('newsecret')
wpa_config.enable()
wpa_config.load()
assert wpa_config.is_enabled is True
assert wpa_config.get_passphrase() == 'newsecret'
wpa_config.disable()
wpa_config.load()
assert wpa_config.is_enabled is False
assert wpa_config.get_passphrase() == 'newsecret'
def test_wpa_config_file_missing(wpa_config):
wpa_config.configfile = '/xyz/missing'
pytest.raises(IOError, wpa_config.load)
......@@ -3,6 +3,8 @@ from subprocess import call
import batinfo
from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from django.http import StreamingHttpResponse
from django.shortcuts import render
from django.utils.translation import ugettext as _
......@@ -172,22 +174,39 @@ def wifi_history(request):
@staff_member_required
def wpa_config(request):
config = WPAConfig()
initial={'passphrase': config.get_passphrase(),
'enable': config.is_enable}
try:
config = WPAConfig()
except IOError as e:
# Handle file not found / permission denied
messages.error(request, 'Hotspot configuration not found.')
messages.error(request, e)
return render(
request, 'serveradmin/wpa_config.html',
{'form': None})
initial = {'passphrase': config.get_passphrase(),
'enable': config.is_enabled}
form = WPAConfigForm(request.POST or initial)
if request.POST and form.is_valid():
passphrase = form.cleaned_data['passphrase']
enable = form.cleaned_data['enable']
if passphrase:
config.change_passphrase(passphrase)
if enable:
config.enable()
message = _('Hotspot is now enabled with passphrase {0}').format(passphrase)
else:
config.disable()
message = _('Hotspot is now disabled')
messages.success(request, message)
try:
if enable:
config.enable()
messages.success(request, _(
'Hotspot is now enabled with passphrase {0}.'
).format(passphrase))
else:
config.disable()
messages.success(request, _('Hotspot is now disabled.'))
except IOError as e:
# file is not writeable
messages.error(request, _(
'We are not able to change hotspot configuration.'))
messages.error(request, e)
return HttpResponseRedirect(reverse_lazy('server:wpa_config'))
return render(
request, 'serveradmin/wpa_config.html',
{'form': form})
......@@ -222,6 +222,7 @@ def get_wifi_device():
class WPAConfig(object):
configfile = '/etc/hostapd/hostapd.conf'
options = {
'wpa': '2',
'wpa_passphrase': '',
......@@ -230,40 +231,38 @@ class WPAConfig(object):
'rsn_pairwise': 'CCMP',
}
def __init__(self, configfile='/etc/hostapd/hostapd.conf'):
self.is_enable = False
def __init__(self):
self.load()
def load(self):
self.is_enabled = False
# read data from config
with open(configfile) as fd:
with open(self.configfile) as fd:
self.data = fd.readlines()
# update option with current passphrase and check if WPA is enable
# update options with current passphrase and check if WPA is enable
for line in self.data:
if '=' in line and 'wpa_passphrase' in line:
self.is_enable = not line.startswith('#')
line = line.strip('# ')
passphrase = line.split('=', 1)[1].strip()
self.options['wpa_passphrase'] = passphrase
self.new_data = self.data[:]
self.configfile = configfile
self.is_enabled = not line.startswith('#')
line = line.strip('# ')
passphrase = line.split('=', 1)[1].strip()
self.options['wpa_passphrase'] = passphrase
def save(self):
"""save data to configfile"""
with open(self.configfile, 'w') as fd:
fd.write('\n'.join(self.new_data))
fd.write('\n'.join(self.data))
# FIXME: we need to restart hostapd
def update(self, comment=False):
"""update data with current options"""
comment = comment is True and '# ' or ''
for i, line in enumerate(self.new_data):
for i, line in enumerate(self.data):
new_line = line.strip()
if '=' in line:
option = line.strip('# ').split('=')[0]
option = line.strip('# ').split('=')[0].strip()
if option in self.options:
new_line = comment + option + '=' + self.options[option]
self.new_data[i] = new_line
def is_enable(self):
return self.enable
self.data[i] = new_line
def get_passphrase(self):
"""get current passphrase"""
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment