Verified Commit a1e9b499 authored by Štěpán Henek's avatar Štěpán Henek 🌩

small cleanup

config.py -> config/__init__.py
wizard.py -> wizard/__init__.py
contract_valid moved to nuci/client
require_contract_valid moved to config/request_decorator
parent 2f7a431e
......@@ -23,15 +23,17 @@ from urlparse import urlunsplit
from bottle import Bottle, request, template
import bottle
from .core import lazy_cache, gettext_dummy as gettext, make_notification_title, ugettext as _
from .config_handlers import *
from .nuci import client
from .nuci.client import filters
from .nuci.exceptions import ConfigRestoreError
from .nuci.preprocessors import preproc_disabled_to_agreed
from .utils import login_required, messages, require_contract_valid, contract_valid
from .utils.bottle_csrf import CSRFPlugin
from .utils.routing import reverse
from foris.core import lazy_cache, gettext_dummy as gettext, make_notification_title, ugettext as _
from foris.config_handlers import *
from foris.nuci import client
from foris.nuci.client import filters, contract_valid
from foris.nuci.exceptions import ConfigRestoreError
from foris.nuci.preprocessors import preproc_disabled_to_agreed
from foris.utils import login_required, messages
from foris.utils.bottle_csrf import CSRFPlugin
from foris.utils.routing import reverse
from .request_decorator import require_contract_valid
logger = logging.getLogger(__name__)
......
# coding=utf-8
# Foris - web administration interface for OpenWrt based on NETCONF
# Copyright (C) 2017 CZ.NIC, z.s.p.o. <http://www.nic.cz>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import bottle
from foris.nuci.client import contract_valid
from functools import wraps
def require_contract_valid(valid=True):
"""
Decorator for methods that require valid contract.
Raises bottle HTTPError if validity differs.
:param valid: should be contrat valid
:type valid: bool
:return: decorated function
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not (contract_valid() == valid):
raise bottle.HTTPError(403, "Contract validity mismatched.")
return func(*args, **kwargs)
return wrapper
return decorator
......@@ -20,6 +20,7 @@ import bottle
from foris import fapi
from foris import validators
from foris.config.request_decorator import require_contract_valid
from foris.core import gettext_dummy as gettext, ugettext as _
from foris.form import (
File, Password, Textbox, Dropdown, Checkbox, Hidden, Radio, Number, Email, Time,
......@@ -31,7 +32,7 @@ from foris.nuci.filters import create_config_filter
from foris.nuci.modules.uci_raw import Uci, Config, Section, Option, List, Value, parse_uci_bool,\
build_option_uci_tree
from foris.utils import (
contract_valid, DEVICE_CUSTOMIZATION, tzinfo, localized_sorted, require_contract_valid
DEVICE_CUSTOMIZATION, tzinfo, localized_sorted
)
logger = logging.getLogger(__name__)
......
......@@ -22,7 +22,6 @@ from foris.form import Checkbox, Radio, RadioSingle, Number
from foris.nuci import client, filters
from foris.nuci.modules.uci_raw import Uci, Config, Section, Option, List, Value, parse_uci_bool
from foris.nuci.preprocessors import preproc_disabled_to_agreed
from foris.utils import contract_valid
from .base import BaseConfigHandler, logger
......@@ -198,7 +197,7 @@ class UpdaterHandler(BaseConfigHandler):
return list_name in enabled_names
return preproc
if not contract_valid():
if not client.contract_valid():
agreed_collect_opt = updater_form.nuci_config \
.find_child("uci.foris.eula.agreed_collect")
agreed_collect = agreed_collect_opt and bool(int(agreed_collect_opt.value))
......@@ -206,7 +205,7 @@ class UpdaterHandler(BaseConfigHandler):
agreed_collect = True
for pkg_list_item in pkg_list:
if not contract_valid():
if not client.contract_valid():
if pkg_list_item.name == "i_agree_datacollect":
# This has special meaning - it's affected by foris.eula.agreed_collect
continue
......
......@@ -41,7 +41,7 @@ from .utils import (
redirect_unauthenticated, is_safe_redirect, is_user_authenticated, template_helpers, LazyCache
)
from .utils.bottle_csrf import get_csrf_token, update_csrf_token, CSRFValidationError, CSRFPlugin
from .utils import DEVICE_CUSTOMIZATION, messages, contract_valid
from .utils import DEVICE_CUSTOMIZATION, messages
from .utils.reporting_middleware import ReportingMiddleware
from .utils.routing import reverse, static
......@@ -73,7 +73,7 @@ bottle.SimpleTemplate.defaults['translations'] = [e for e in translations]
bottle.SimpleTemplate.defaults['iso2to3'] = iso2to3
bottle.SimpleTemplate.defaults['ungettext'] = lambda singular, plural, n: ungettext(singular, plural, n)
bottle.SimpleTemplate.defaults['DEVICE_CUSTOMIZATION'] = DEVICE_CUSTOMIZATION
bottle.SimpleTemplate.defaults['contract_valid'] = contract_valid
bottle.SimpleTemplate.defaults['contract_valid'] = client.contract_valid
bottle.SimpleTemplate.defaults['foris_version'] = foris_version
gettext_dummy = lambda x: x
_ = ugettext
......
......@@ -25,6 +25,8 @@ from ncclient.operations import RPCError
from ncclient.operations.errors import TimeoutExpiredError
from ncclient.transport import TransportError
from foris import DEVICE_CUSTOMIZATION
from . import filters
from .exceptions import ConfigRestoreError
from .modules import (
......@@ -32,6 +34,7 @@ from .modules import (
stats, time as time_module, uci_raw, updater, user_notify
)
from .modules.base import Data, YinElement
from .modules.uci_raw import parse_uci_bool
from .utils import LocalizableTextValue
logger = logging.getLogger("nuci.client")
......@@ -430,5 +433,24 @@ def edit_config_multiple(configs):
netconf.edit_config("running", config=config_root)
def contract_valid():
"""Read whether the contract related with the current router is valid from uci
:return: whether the contract is still valid
"""
if DEVICE_CUSTOMIZATION == "omnia":
return False
from foris.core import nuci_cache
data = nuci_cache.get("foris.contract", 60 * 60) # once per hour should be enought
valid = data.find_child("foris.contract.valid")
if not valid: # valid record
# valid record not found, assuming that the contract is still valid
return True
return parse_uci_bool(valid)
def dispatch(*args, **kwargs):
return netconf.dispatch(*args, **kwargs)
......@@ -17,16 +17,12 @@
import json
import urlparse
from datetime import datetime, timedelta
import bottle
from functools import wraps
import logging
from xml.etree import cElementTree as ET
from .routing import reverse
from .. import DEVICE_CUSTOMIZATION
from ..nuci.modules.uci_raw import parse_uci_bool
logger = logging.getLogger("foris.utils")
......@@ -56,25 +52,6 @@ def redirect_unauthenticated(redirect_url=None):
bottle.redirect(login_url)
def contract_valid():
"""Read whether the contract related with the current router is valid from uci
:return: whether the contract is still valid
"""
if DEVICE_CUSTOMIZATION == "omnia":
return False
from foris.core import nuci_cache
data = nuci_cache.get("foris.contract", 60 * 60) # once per hour should be enought
valid = data.find_child("foris.contract.valid")
if not valid: # valid record
# valid record not found, assuming that the contract is still valid
return True
return parse_uci_bool(valid)
def login_required(func=None, redirect_url=None):
"""Decorator for views that require login.
......@@ -125,25 +102,6 @@ def require_customization(required_customization=None):
return decorator
def require_contract_valid(valid=True):
"""
Decorator for methods that require valid contract.
Raises bottle HTTPError if validity differs.
:param valid: should be contrat valid
:type valid: bool
:return: decorated function
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not (contract_valid() == valid):
raise bottle.HTTPError(403, "Contract validity mismatched.")
return func(*args, **kwargs)
return wrapper
return decorator
class Lazy(object):
def __init__(self, func):
self.func = func
......
......@@ -3,10 +3,10 @@ import pickle
# Load directory of countries country_code: country_name
countries = pickle.load(file(os.path.join(os.path.dirname(__file__), "countries.pickle2"), "rb"))
countries = pickle.load(open(os.path.join(os.path.dirname(__file__), "countries.pickle2"), "rb"))
# Load TZ data tuple of tuples: (luci_tz, country, city, zoneinfo)
tz_data = pickle.load(file(os.path.join(os.path.dirname(__file__), "tzdata.pickle2"), "rb"))
tz_data = pickle.load(open(os.path.join(os.path.dirname(__file__), "tzdata.pickle2"), "rb"))
# Set of existing regions
......
......@@ -22,11 +22,12 @@ from .core import gettext_dummy as gettext, make_notification_title, ugettext as
import logging
from .config_handlers import BaseConfigHandler, PasswordHandler, RegionHandler, \
WanHandler, TimeHandler, LanHandler, UpdaterAutoUpdatesHandler, WifiHandler
from .config.request_decorator import require_contract_valid
from .nuci import client, filters
from .nuci.configurator import add_config_update, commit
from .nuci.modules.uci_raw import build_option_uci_tree
from .nuci.preprocessors import preproc_disabled_to_agreed
from .utils import contract_valid, login_required, messages, require_contract_valid
from .utils import login_required, messages
from .utils.bottle_csrf import CSRFPlugin
from .utils.routing import reverse
......@@ -378,7 +379,7 @@ class WizardStep10(WizardStepMixin, BaseConfigHandler):
def render(self, **kwargs):
kwargs['notifications'] = client.get_messages().restarts
kwargs['make_notification_title'] = make_notification_title
if not contract_valid():
if not client.contract_valid():
updater_conf = client.get(filter=filters.create_config_filter("foris"))
agreed_updater = preproc_disabled_to_agreed(updater_conf)
return template("wizard/finished.tpl",
......
This diff is collapsed.
......@@ -55,6 +55,7 @@ setup(
packages=[
"foris",
"foris.config_handlers",
"foris.config",
"foris.langs",
"foris.nuci",
"foris.nuci.modules",
......@@ -62,6 +63,7 @@ setup(
"foris.utils",
"foris.ubus",
"foris.middleware",
"foris.wizard",
],
package_data={
'': [
......
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