예제 #1
0
    def run(self):
        if not os.path.exists(LICENSE_FILE):
            return None
        with open(LICENSE_FILE, 'rb') as f:
            data = f.read()
        try:
            license = License.load(data)
        except:
            return [Alert(
                Alert.CRIT,
                _('Unable to decode %s license') % get_sw_name(),
            )]

        end_date = license.contract_end
        if end_date < datetime.now().date():
            return [Alert(
                Alert.CRIT,
                _('Your %s license has expired') % get_sw_name(),
            )]
        elif end_date - timedelta(days=30) < datetime.now().date():
            return [Alert(
                Alert.WARN, _(
                    'Your %(sw_name)s license is going to expire in %(date)s'
                ) % {
                    'sw_name': get_sw_name(),
                    'date': end_date,
                }
            )]
예제 #2
0
def do_sendmail(msg, to_addrs=None, parse_recipients=False):

    if to_addrs is None:
        if not parse_recipients:
            raise ValueError('Do not know who to send the message to.')
        to_addrs = []

    # XXX: this should probably be a FeedParser because reading from sys.stdin
    # is blocking.
    em_parser = email.parser.Parser()
    em = em_parser.parsestr(msg)
    if parse_recipients:
        # Strip away the comma based delimiters and whitespace.
        to_addrs = map(str.strip, em.get('To').split(','))

    if not to_addrs or not to_addrs[0]:
        to_addrs = ['root']

    if to_addrs:
        aliases = get_aliases()
        to_addrs_repl = []
        for to_addr in to_addrs:
            for to_addr in to_addr.split(','):
                if to_addr.find('@') == -1 and to_addr in aliases:
                    to_addr = aliases[to_addr]
                to_addrs_repl.append(to_addr)

    margs = {}
    margs['extra_headers'] = dict(em)
    margs['extra_headers'].update({
        'X-Mailer': get_sw_name(),
        'X-%s-Host' % get_sw_name(): socket.gethostname(),
        'To': to_addr,
    })
    margs['subject'] = em.get('Subject')

    # abusive use of querysets
    lemail = Email.objects.all()
    for obj in lemail:
        if obj.em_fromemail != '':
            margs['extra_headers'].update({
               'From': obj.em_fromemail
            })

    if em.is_multipart():
        margs['attachments'] = filter(
            lambda part: part.get_content_maintype() != 'multipart',
            em.walk()
        )
        margs['text'] = u"%s" % _(
            'This is a MIME formatted message.  If you see '
            'this text it means that your email software '
            'does not support MIME formatted messages.')
    else:
        margs['text'] = ''.join(email.iterators.body_line_iterator(em))

    if to_addrs_repl:
        margs['to'] = to_addrs_repl

    send_mail(**margs)
예제 #3
0
def do_sendmail(msg, to_addrs=None, parse_recipients=False):

    if to_addrs is None:
        if not parse_recipients:
            raise ValueError('Do not know who to send the message to.')
        to_addrs = []

    # XXX: this should probably be a FeedParser because reading from sys.stdin
    # is blocking.
    em_parser = email.parser.Parser()
    em = em_parser.parsestr(msg)
    if parse_recipients:
        # Strip away the comma based delimiters and whitespace.
        to_addrs = map(str.strip, em.get('To').split(','))

    if not to_addrs or not to_addrs[0]:
        to_addrs = ['root']

    if to_addrs:
        aliases = get_aliases()
        to_addrs_repl = []
        for to_addr in to_addrs:
            for to_addr in to_addr.split(','):
                if to_addr.find('@') == -1 and to_addr in aliases:
                    to_addr = aliases[to_addr]
                to_addrs_repl.append(to_addr)

    margs = {}
    margs['extra_headers'] = dict(em)
    margs['extra_headers'].update({
        'X-Mailer':
        get_sw_name(),
        'X-%s-Host' % get_sw_name():
        socket.gethostname(),
        'To':
        to_addr,
    })
    margs['subject'] = em.get('Subject')

    # abusive use of querysets
    lemail = Email.objects.all()
    for obj in lemail:
        if obj.em_fromemail != '':
            margs['extra_headers'].update({'From': obj.em_fromemail})

    if em.is_multipart():
        margs['attachments'] = filter(
            lambda part: part.get_content_maintype() != 'multipart', em.walk())
        margs['text'] = u"%s" % _(
            'This is a MIME formatted message.  If you see '
            'this text it means that your email software '
            'does not support MIME formatted messages.')
    else:
        margs['text'] = ''.join(email.iterators.body_line_iterator(em))

    if to_addrs_repl:
        margs['to'] = to_addrs_repl

    send_mail(**margs)
예제 #4
0
def main():

    try:
        updateobj = mUpdate.objects.order_by('-id')[0]
    except IndexError:
        updateobj = mUpdate.objects.create()

    if updateobj.upd_autocheck is False:
        return

    location = notifier().get_update_location()

    Update.DownloadUpdate(updateobj.get_train(), location)

    update = Update.CheckForUpdates(
        train=updateobj.get_train(),
        cache_dir=location,
    )

    if not update:
        return

    conf = Configuration.Configuration()
    sys_mani = conf.SystemManifest()
    if sys_mani:
        sequence = sys_mani.Sequence()
    else:
        sequence = ''

    changelog = get_changelog(
        updateobj.get_train(),
        start=sequence,
        end=update.Sequence(),
    )

    hostname = socket.gethostname()

    send_mail(
        subject='%s: %s' % (
            hostname,
            _('Update Available'),
        ),
        extra_headers={
            'X-Mailer': get_sw_name(),
            'X-%s-Host' % get_sw_name(): socket.gethostname()
        },
        text=_('''A new update is available for the %(train)s train.

Version: %(version)s
Changelog:
%(changelog)s
''') % {
            'train': updateobj.get_train(),
            'version': update.Version(),
            'changelog': changelog,
        },
    )
예제 #5
0
def main():

    try:
        updateobj = mUpdate.objects.order_by('-id')[0]
    except IndexError:
        updateobj = mUpdate.objects.create()

    if updateobj.upd_autocheck is False:
        return

    location = notifier().get_update_location()

    Update.DownloadUpdate(updateobj.get_train(), location)

    update = Update.CheckForUpdates(
        train=updateobj.get_train(),
        cache_dir=location,
    )

    if not update:
        return

    conf = Configuration.Configuration()
    sys_mani = conf.SystemManifest()
    if sys_mani:
        sequence = sys_mani.Sequence()
    else:
        sequence = ''

    changelog = get_changelog(
        updateobj.get_train(),
        start=sequence,
        end=update.Sequence(),
    )

    hostname = socket.gethostname()

    send_mail(
        subject='%s: %s' % (
            hostname,
            _('Update Available'),
        ),
        extra_headers={'X-Mailer': get_sw_name(),
                       'X-%s-Host' % get_sw_name(): socket.gethostname()},
        text=_('''A new update is available for the %(train)s train.

Changelog:
%(changelog)s
''') % {
            'train': updateobj.get_train(),
            'changelog': changelog,
        },
    )
예제 #6
0
def ticket(request):

    debug = True if request.POST.get('debug') == 'on' else False

    data = {
        'title': request.POST.get('subject'),
        'body': request.POST.get('desc'),
        'category': request.POST.get('category'),
        'attach_debug': debug,
    }

    if get_sw_name().lower() == 'freenas':
        data.update({
            'username': request.POST.get('username'),
            'password': request.POST.get('password'),
            'type': request.POST.get('type', '').upper(),
        })
    else:
        data.update({
            'phone': request.POST.get('phone'),
            'name': request.POST.get('name'),
            'email': request.POST.get('email'),
            'criticality': request.POST.get('criticality'),
            'environment': request.POST.get('environment'),
        })

    error = False
    files = request.FILES.getlist('attachment')
    token = None
    with client as c:
        try:
            rv = c.call('support.new_ticket', data, job=True)
            data = {'error': False, 'message': rv['url']}
            if files:
                token = c.call('auth.generate_token')
        except ClientException as e:
            data = {'error': True, 'message': e.error}

    if not error:
        for f in files:
            requests.post(
                f'http://127.0.0.1:6000/_upload/?auth_token={token}',
                files={
                    'file': ('file', f.file),
                    'data': ('data', json.dumps({
                        'method': 'support.attach_ticket',
                        'params': [{
                            'ticket': rv['ticket'],
                            'filename': f.name,
                            'username': request.POST.get('username'),
                            'password': request.POST.get('password'),
                        }],
                    }).encode()),
                },
            )

    data = '<html><body><textarea>{}</textarea></boby></html>'.format(
        json.dumps(data),
    )
    return HttpResponse(data)
예제 #7
0
def login_wrapper(request,
                  template_name='registration/login.html',
                  redirect_field_name=REDIRECT_FIELD_NAME,
                  authentication_form=AuthenticationForm,
                  current_app=None,
                  extra_context={}):
    """
    Wrapper to login to do not allow login and redirect to
    shutdown, reboot or logout pages,
    instead redirect to /
    """
    extra_context.update({
        'sw_login_version': get_sw_login_version(),
        'sw_name': get_sw_name(),
    })
    response = login(request,
                     template_name='registration/login.html',
                     redirect_field_name=redirect_field_name,
                     authentication_form=authentication_form,
                     current_app=current_app,
                     extra_context=extra_context)
    if response.status_code in (301, 302) and response._headers.get(
            'location', ('', ''))[1] in (
                reverse('system_reboot'),
                reverse('system_shutdown'),
                reverse('account_logout'),
            ):
        response._headers['location'] = ('Location', '/')
    elif request.user.is_authenticated():
        return HttpResponseRedirect('/')
    return response
예제 #8
0
    def forwards(self, orm):

        # Adding model 'Email'
        db.create_table('system_email', (
            ('id',
             self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('em_fromemail', self.gf('django.db.models.fields.CharField')(
                max_length=120, blank=True)),
            ('em_outgoingserver', self.gf('django.db.models.fields.CharField')(
                max_length=120, blank=True)),
            ('em_port',
             self.gf('django.db.models.fields.IntegerField')(default=25)),
            ('em_security', self.gf('django.db.models.fields.CharField')(
                default='plain', max_length=120)),
            ('em_smtp',
             self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('em_user', self.gf('django.db.models.fields.CharField')(
                max_length=120, null=True, blank=True)),
            ('em_pass', self.gf('django.db.models.fields.CharField')(
                max_length=120, null=True, blank=True)),
        ))
        db.send_create_signal('system', ['Email'])

        em = orm.Email()
        em.em_fromemail = 'root@%s.local' % (get_sw_name().lower(), )
        em.em_port = 25
        em.em_smtp = False
        em.save()
예제 #9
0
def index(request):
    sw_name = get_sw_name().lower()

    license, reason = utils.get_license()
    allow_update = True
    if hasattr(notifier, 'failover_status'):
        status = notifier().failover_status()
        if status not in ('MASTER', 'SINGLE'):
            allow_update = False

    context = {
        'sw_name': sw_name,
        'license': license,
        'fc_enabled': utils.fc_enabled(),
        'allow_update': allow_update,
    }
    for c in appPool.hook_view_context('support.index', request):
        context.update(c)

    if not notifier().is_freenas():
        form = forms.ProductionForm()
        if request.method == 'POST':
            form = forms.ProductionForm(request.POST)
            if form.is_valid():
                form.save()
                return JsonResp(
                    request,
                    message='Production status successfully updated.'
                )

        context['production_form'] = form

    return render(request, 'support/home.html', context)
예제 #10
0
파일: views.py 프로젝트: Cbrdiv/freenas
def documentation_home(request):

    sw_name = get_sw_name().lower()
    context = {
        'sw_name': sw_name
    }
    return render(request, "documentation/index.html", context)
예제 #11
0
파일: views.py 프로젝트: WilfriedNH/freenas
def login_wrapper(
    request,
    template_name='registration/login.html',
    redirect_field_name=REDIRECT_FIELD_NAME,
    authentication_form=AuthenticationForm,
    current_app=None, extra_context={}
):
    """
    Wrapper to login to do not allow login and redirect to
    shutdown, reboot or logout pages,
    instead redirect to /
    """
    extra_context.update({
        'sw_login_version': get_sw_login_version(),
        'sw_name': get_sw_name(),
    })
    response = login(
        request,
        template_name='registration/login.html',
        redirect_field_name=redirect_field_name,
        authentication_form=authentication_form,
        current_app=current_app,
        extra_context=extra_context,
    )
    if response.status_code in (301, 302) and response._headers.get(
        'location', ('', '')
    )[1] in (
        reverse('system_reboot'),
        reverse('system_shutdown'),
        reverse('account_logout'),
    ):
        response._headers['location'] = ('Location', '/')
    elif request.user.is_authenticated():
        return HttpResponseRedirect('/')
    return response
예제 #12
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced

        view = appPool.hook_app_index('freeadmin', request)
        view = filter(None, view)
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].gc_hostname
        except:
            hostname = None
        sw_version = get_sw_version()
        return render(
            request, 'freeadmin/index.html', {
                'consolemsg': console,
                'hostname': hostname,
                'sw_name': get_sw_name(),
                'sw_version': sw_version,
                'cache_hash': hashlib.md5(sw_version).hexdigest(),
                'css_hook': appPool.get_base_css(request),
                'js_hook': appPool.get_base_js(request),
                'menu_hook': appPool.get_top_menu(request),
            })
예제 #13
0
파일: views.py 프로젝트: jceel/freenas
def testmail(request):

    try:
        kwargs = dict(instance=models.Email.objects.order_by('-id')[0])
    except IndexError:
        kwargs = {}
    form = forms.EmailForm(request.POST, **kwargs)
    if not form.is_valid():
        return JsonResp(request, form=form)

    email = bsdUsers.objects.get(bsdusr_username='******').bsdusr_email
    if not email:
        return JsonResp(
            request,
            error=True,
            message=_(
                "You must configure the root email (Accounts->Users->root)"),
        )

    sid = transaction.savepoint()
    form.save()

    error = False
    if request.is_ajax():
        sw_name = get_sw_name()
        error, errmsg = send_mail(
            subject=_('Test message from %s' % (sw_name)),
            text=_('This is a message test from %s' % (sw_name, )))
    if error:
        errmsg = _("Your test email could not be sent: %s") % errmsg
    else:
        errmsg = _('Your test email has been sent!')
    transaction.savepoint_rollback(sid)

    return JsonResp(request, error=error, message=errmsg)
예제 #14
0
    def forwards(self, orm):
        
        # Adding model 'GlobalConfiguration'
        db.create_table('network_globalconfiguration', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('gc_hostname', self.gf('django.db.models.fields.CharField')(max_length=120)),
            ('gc_domain', self.gf('django.db.models.fields.CharField')(max_length=120)),
            ('gc_ipv4gateway', self.gf('django.db.models.fields.CharField')(max_length=120, blank=True)),
            ('gc_ipv6gateway', self.gf('django.db.models.fields.CharField')(max_length=120, blank=True)),
            ('gc_nameserver1', self.gf('django.db.models.fields.CharField')(max_length=120, blank=True)),
            ('gc_nameserver2', self.gf('django.db.models.fields.CharField')(max_length=120, blank=True)),
            ('gc_nameserver3', self.gf('django.db.models.fields.CharField')(max_length=120, blank=True)),
        ))
        db.send_create_signal('network', ['GlobalConfiguration'])

        # Adding model 'Interfaces'
        db.create_table('network_interfaces', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('int_interface', self.gf('django.db.models.fields.CharField')(max_length=300)),
            ('int_name', self.gf('django.db.models.fields.CharField')(max_length='120')),
            ('int_dhcp', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('int_ipv4address', self.gf('django.db.models.fields.CharField')(max_length=18, blank=True)),
            ('int_ipv6auto', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('int_ipv6address', self.gf('django.db.models.fields.CharField')(max_length=42, blank=True)),
            ('int_options', self.gf('django.db.models.fields.CharField')(max_length=120, blank=True)),
        ))
        db.send_create_signal('network', ['Interfaces'])

        # Adding model 'VLAN'
        db.create_table('network_vlan', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('vlan_vint', self.gf('django.db.models.fields.CharField')(max_length=120)),
            ('vlan_pint', self.gf('django.db.models.fields.CharField')(max_length=300)),
            ('vlan_tag', self.gf('django.db.models.fields.CharField')(max_length=120)),
            ('vlan_description', self.gf('django.db.models.fields.CharField')(max_length=120, blank=True)),
        ))
        db.send_create_signal('network', ['VLAN'])

        # Adding model 'LAGG'
        db.create_table('network_lagg', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('lagg_vint', self.gf('django.db.models.fields.CharField')(max_length=120)),
            ('lagg_ports', self.gf('django.db.models.fields.CharField')(max_length=120)),
            ('lagg_description', self.gf('django.db.models.fields.CharField')(max_length=120, blank=True)),
        ))
        db.send_create_signal('network', ['LAGG'])

        # Adding model 'StaticRoute'
        db.create_table('network_staticroute', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('sr_destination', self.gf('django.db.models.fields.CharField')(max_length=120)),
            ('sr_gateway', self.gf('django.db.models.fields.CharField')(max_length=120)),
            ('sr_description', self.gf('django.db.models.fields.CharField')(max_length=120, blank=True)),
        ))
        db.send_create_signal('network', ['StaticRoute'])

        gc = orm.GlobalConfiguration()
        gc.gc_hostname = get_sw_name().lower()
        gc.gc_domain = 'local'
        gc.save()
예제 #15
0
def jails_enabled():
    license, reason = get_license()
    sw_name = get_sw_name().lower()
    if sw_name == 'freenas' or (license
                                and Features.jails in license.features):
        return True
    return False
예제 #16
0
파일: site.py 프로젝트: WilfriedNH/freenas
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced

        view = appPool.hook_app_index('freeadmin', request)
        view = filter(None, view)
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].gc_hostname
        except:
            hostname = None
        sw_version = get_sw_version()
        return render(request, 'freeadmin/index.html', {
            'consolemsg': console,
            'hostname': hostname,
            'sw_name': get_sw_name(),
            'sw_version': sw_version,
            'cache_hash': hashlib.md5(sw_version).hexdigest(),
            'css_hook': appPool.get_base_css(request),
            'js_hook': appPool.get_base_js(request),
            'menu_hook': appPool.get_top_menu(request),
        })
예제 #17
0
def fc_enabled():
    license, reason = get_license()
    sw_name = get_sw_name().lower()
    if sw_name == 'truenas' and (license and Features.fibrechannel
                                 in license.features):
        return True
    return False
예제 #18
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced, Settings
        from freenasUI.middleware.client import client

        view = appPool.hook_app_index('freeadmin', request)
        view = filter(None, view)
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].get_hostname()
        except:
            hostname = None

        try:
            settings = Settings.objects.all().order_by('-id')[0]
            wizard = not settings.stg_wizardshown
            if settings.stg_wizardshown is False:
                settings.stg_wizardshown = True
                settings.save()
        except:
            wizard = False
        sw_version = get_sw_version()

        try:
            with client as c:
                middleware_token = c.call('auth.generate_token', timeout=10)
        except Exception:
            middleware_token = None
            extra_data = {
                'sw_version': sw_version,
            }
            if os.path.exists('/var/log/middlewared.log'):
                with open('/var/log/middlewared.log', 'r') as f:
                    extra_data['middlewaredlog'] = f.read()[-10240:]
            rollbar.report_exc_info(
                sys.exc_info(),
                request,
                extra_data=extra_data,
            )

        return render(
            request, 'freeadmin/index.html', {
                'consolemsg': console,
                'hostname': hostname,
                'sw_name': get_sw_name(),
                'sw_version': sw_version,
                'cache_hash': hashlib.md5(sw_version).hexdigest(),
                'css_hook': appPool.get_base_css(request),
                'js_hook': appPool.get_base_js(request),
                'menu_hook': appPool.get_top_menu(request),
                'wizard': wizard,
                'middleware_token': middleware_token,
            })
예제 #19
0
파일: views.py 프로젝트: penglaixy/freenas
def testmail(request):

    try:
        kwargs = dict(instance=models.Email.objects.order_by("-id")[0])
    except IndexError:
        kwargs = {}
    form = forms.EmailForm(request.POST, **kwargs)
    if not form.is_valid():
        return JsonResp(request, form=form)

    email = bsdUsers.objects.get(bsdusr_username="******").bsdusr_email
    if not email:
        return JsonResp(request, error=True, message=_("You must configure the root email" " (Accounts->Users->root)"))

    sid = transaction.savepoint()
    form.save()

    error = False
    if request.is_ajax():
        sw_name = get_sw_name()
        error, errmsg = send_mail(
            subject=_("Test message from %s" % (sw_name)), text=_("This is a message test from %s" % (sw_name,))
        )
    if error:
        errmsg = _("Your test email could not be sent: %s") % errmsg
    else:
        errmsg = _("Your test email has been sent!")
    transaction.savepoint_rollback(sid)

    return JsonResp(request, error=error, message=errmsg)
예제 #20
0
def _system_info(request=None):
    # OS, hostname, release
    __, hostname, __ = os.uname()[0:3]
    platform = sysctl.filter('hw.model')[0].value
    physmem = '%dMB' % (sysctl.filter('hw.physmem')[0].value / 1048576, )
    # All this for a timezone, because time.asctime() doesn't add it in.
    date = time.strftime('%a %b %d %H:%M:%S %Z %Y') + '\n'
    uptime = subprocess.check_output(
        "env -u TZ uptime | awk -F', load averages:' '{ print $1 }'",
        shell=True)
    loadavg = "%.2f, %.2f, %.2f" % os.getloadavg()

    try:
        freenas_build = '%s %s' % (get_sw_name(), get_sw_login_version())
    except:
        freenas_build = "Unrecognized build"

    try:
        conf = Configuration.Configuration()
        manifest = conf.SystemManifest()
        builddate = datetime.utcfromtimestamp(int(manifest.Sequence()))
    except:
        builddate = None

    return {
        'hostname': hostname,
        'platform': platform,
        'physmem': physmem,
        'date': date,
        'uptime': uptime,
        'loadavg': loadavg,
        'freenas_build': freenas_build,
        'builddate': builddate,
    }
예제 #21
0
파일: site.py 프로젝트: jgehrcke/freenas
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced

        view = appPool.hook_app_index("freeadmin", request)
        view = filter(None, view)
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by("-id")[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by("-id")[0].gc_hostname
        except:
            hostname = None
        sw_version = get_sw_version()
        return render(
            request,
            "freeadmin/index.html",
            {
                "consolemsg": console,
                "hostname": hostname,
                "sw_name": get_sw_name(),
                "sw_version": sw_version,
                "cache_hash": hashlib.md5(sw_version).hexdigest(),
                "css_hook": appPool.get_base_css(request),
                "js_hook": appPool.get_base_js(request),
                "menu_hook": appPool.get_top_menu(request),
            },
        )
예제 #22
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced, Settings
        from freenasUI.middleware.client import client

        view = appPool.hook_app_index('freeadmin', request)
        view = filter(None, view)
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].get_hostname()
        except:
            hostname = None

        try:
            settings = Settings.objects.all().order_by('-id')[0]
            wizard = not settings.stg_wizardshown
            if settings.stg_wizardshown is False:
                settings.stg_wizardshown = True
                settings.save()
        except:
            wizard = False
        sw_version = get_sw_version()

        try:
            with client as c:
                middleware_token = c.call('auth.generate_token', timeout=10)
        except Exception:
            middleware_token = None
            extra_data = {
                'sw_version': sw_version,
            }
            if os.path.exists('/var/log/middlewared.log'):
                with open('/var/log/middlewared.log', 'r') as f:
                    extra_data['middlewaredlog'] = f.read()[-10240:]
            rollbar.report_exc_info(
                sys.exc_info(),
                request,
                extra_data=extra_data,
            )

        return render(request, 'freeadmin/index.html', {
            'consolemsg': console,
            'hostname': hostname,
            'sw_name': get_sw_name(),
            'sw_version': sw_version,
            'cache_hash': hashlib.md5(sw_version).hexdigest(),
            'css_hook': appPool.get_base_css(request),
            'js_hook': appPool.get_base_js(request),
            'menu_hook': appPool.get_top_menu(request),
            'wizard': wizard,
            'middleware_token': middleware_token,
        })
예제 #23
0
파일: utils.py 프로젝트: Cbrdiv/freenas
def jails_enabled():
    license, reason = get_license()
    sw_name = get_sw_name().lower()
    if sw_name == 'freenas' or (
        license and Features.jails in license.features
    ):
        return True
    return False
예제 #24
0
def index(request):
    sw_name = get_sw_name().lower()

    context = {}
    for c in appPool.hook_view_context('support.index', request):
        context.update(c)

    return render(request, 'support/home_%s.html' % sw_name, context)
예제 #25
0
파일: utils.py 프로젝트: Cbrdiv/freenas
def fc_enabled():
    license, reason = get_license()
    sw_name = get_sw_name().lower()
    if sw_name == 'truenas' and (
        license and Features.fibrechannel in license.features
    ):
        return True
    return False
예제 #26
0
파일: views.py 프로젝트: vanloswang/freenas
def license_status(request):

    sw_name = get_sw_name().lower()
    license, reason = utils.get_license()
    if (license is None and sw_name != "freenas") or license.expired:
        return HttpResponse("PROMPT")

    return HttpResponse("OK")
예제 #27
0
파일: views.py 프로젝트: HySoaKa/freenas
def license_status(request):

    sw_name = get_sw_name().lower()
    license, reason = utils.get_license()
    if (license is None and sw_name != 'freenas') or license.expired:
        return HttpResponse('PROMPT')

    return HttpResponse('OK')
예제 #28
0
def license_status(request):

    sw_name = get_sw_name().lower()
    license, reason = utils.get_license()
    if (license is None and sw_name != 'freenas') or license.expired:
        return HttpResponse('PROMPT')

    return HttpResponse('OK')
예제 #29
0
파일: views.py 프로젝트: freenas/freenas
def login_wrapper(
    request,
    template_name='registration/login.html',
    redirect_field_name=REDIRECT_FIELD_NAME,
    authentication_form=ExtendedAuthForm,
    current_app=None, extra_context=None,
):
    """
    Wrapper to login to do not allow login and redirect to
    shutdown, reboot or logout pages,
    instead redirect to /
    """

    auth_token = request.GET.get('auth_token')
    if auth_token:
        user = authenticate(auth_token=auth_token)
        if user:
            auth_login(request, user, 'freenasUI.middleware.auth.AuthTokenBackend')

    # Overload hook_app_index to shortcut passive node
    # Doing that in another layer will use too many reasources
    view = appPool.hook_app_index('account_login', request)
    view = [_f for _f in view if _f]
    if view:
        return view[0]

    if extra_context is None:
        extra_context = {}
    extra_context.update({
        'sw_login_version': get_sw_login_version(),
        'sw_version_footer': get_sw_version(strip_build_num=True).split('-', 1)[-1],
        'sw_name': get_sw_name(),
        'sw_year': get_sw_year(),
    })
    if not models.bsdUsers.has_root_password():
        authentication_form = forms.NewPasswordForm
        extra_context.update({
            'reset_password': True,
        })
    response = login(
        request,
        template_name='registration/login.html',
        redirect_field_name=redirect_field_name,
        authentication_form=authentication_form,
        current_app=current_app,
        extra_context=extra_context,
    )
    if response.status_code in (301, 302) and response._headers.get(
        'location', ('', '')
    )[1] in (
        reverse('system_reboot'),
        reverse('system_shutdown'),
        reverse('account_logout'),
    ):
        response._headers['location'] = ('Location', '/legacy/')
    elif request.user.is_authenticated:
        return HttpResponseRedirect('/legacy/')
    return response
예제 #30
0
def testmail(request):

    try:
        kwargs = dict(instance=models.Email.objects.order_by('-id')[0])
    except IndexError:
        kwargs = {}

    fromwizard = False
    data = request.POST.copy()
    for key, value in data.items():
        if key.startswith('system-'):
            fromwizard = True
            data[key.replace('system-', '')] = value

    form = forms.EmailForm(data, **kwargs)
    if not form.is_valid():
        return JsonResp(request, form=form)

    if fromwizard:
        allfield = 'system-__all__'
    else:
        allfield = '__all__'

    if fromwizard:
        email = request.POST.get('system-sys_email')
        errmsg = _('You must provide a Root E-mail')
    else:
        email = bsdUsers.objects.get(bsdusr_username='******').bsdusr_email
        errmsg = _('You must configure the root email (Accounts->Users->root)')
    if not email:
        form.errors[allfield] = form.error_class([errmsg])

        return JsonResp(
            request,
            form=form,
        )

    sid = transaction.savepoint()
    form.save()

    error = False
    if request.is_ajax():
        sw_name = get_sw_name()
        error, errmsg = send_mail(
            subject=_('Test message from %s') % sw_name,
            text=_('This is a message test from %s') % sw_name,
            to=[email])
    if error:
        errmsg = _("Your test email could not be sent: %s") % errmsg
    else:
        errmsg = _('Your test email has been sent!')
    transaction.savepoint_rollback(sid)

    form.errors[allfield] = form.error_class([errmsg])
    return JsonResp(
        request,
        form=form,
    )
예제 #31
0
def testmail(request):

    try:
        kwargs = dict(instance=models.Email.objects.order_by('-id')[0])
    except IndexError:
        kwargs = {}

    fromwizard = False
    data = request.POST.copy()
    for key, value in data.items():
        if key.startswith('system-'):
            fromwizard = True
            data[key.replace('system-', '')] = value

    form = forms.EmailForm(data, **kwargs)
    if not form.is_valid():
        return JsonResp(request, form=form)

    if fromwizard:
        allfield = 'system-__all__'
    else:
        allfield = '__all__'

    if fromwizard:
        email = request.POST.get('system-sys_email')
        errmsg = _('You must provide a Root E-mail')
    else:
        email = bsdUsers.objects.get(bsdusr_username='******').bsdusr_email
        errmsg = _('You must configure the root email (Accounts->Users->root)')
    if not email:
        form.errors[allfield] = form.error_class([errmsg])

        return JsonResp(
            request,
            form=form,
        )

    sid = transaction.savepoint()
    form.save()

    error = False
    if request.is_ajax():
        sw_name = get_sw_name()
        error, errmsg = send_mail(subject=_('Test message from %s') % sw_name,
                                  text=_('This is a message test from %s') %
                                  sw_name,
                                  to=[email])
    if error:
        errmsg = _("Your test email could not be sent: %s") % errmsg
    else:
        errmsg = _('Your test email has been sent!')
    transaction.savepoint_rollback(sid)

    form.errors[allfield] = form.error_class([errmsg])
    return JsonResp(
        request,
        form=form,
    )
예제 #32
0
파일: views.py 프로젝트: mike0615/freenas
def license_status(request):

    sw_name = get_sw_name().lower()
    license = utils.get_license()[0]
    if (license is None and sw_name != 'freenas') or (license is not None
                                                      and license['expired']):
        return HttpResponse('PROMPT')

    return HttpResponse('OK')
예제 #33
0
def login_wrapper(
    request,
    template_name='registration/login.html',
    redirect_field_name=REDIRECT_FIELD_NAME,
    authentication_form=ExtendedAuthForm,
    current_app=None,
    extra_context=None,
):
    """
    Wrapper to login to do not allow login and redirect to
    shutdown, reboot or logout pages,
    instead redirect to /
    """

    auth_token = request.GET.get('auth_token')
    if auth_token:
        user = authenticate(auth_token=auth_token)
        if user:
            auth_login(request, user,
                       'freenasUI.middleware.auth.AuthTokenBackend')

    # Overload hook_app_index to shortcut passive node
    # Doing that in another layer will use too many reasources
    view = appPool.hook_app_index('account_login', request)
    view = [_f for _f in view if _f]
    if view:
        return view[0]

    if extra_context is None:
        extra_context = {}
    extra_context.update({
        'sw_login_version': get_sw_login_version(),
        'sw_name': get_sw_name(),
    })
    if not models.bsdUsers.has_root_password():
        authentication_form = forms.NewPasswordForm
        extra_context.update({
            'reset_password': True,
        })
    response = login(
        request,
        template_name='registration/login.html',
        redirect_field_name=redirect_field_name,
        authentication_form=authentication_form,
        current_app=current_app,
        extra_context=extra_context,
    )
    if response.status_code in (301, 302) and response._headers.get(
            'location', ('', ''))[1] in (
                reverse('system_reboot'),
                reverse('system_shutdown'),
                reverse('account_logout'),
            ):
        response._headers['location'] = ('Location', '/')
    elif request.user.is_authenticated:
        return HttpResponseRedirect('/')
    return response
예제 #34
0
def reboot(request):
    """ reboots the system """
    if not request.session.get("allow_reboot"):
        return HttpResponseRedirect('/')
    request.session.pop("allow_reboot")
    return render(request, 'system/reboot.html', {
        'sw_name': get_sw_name(),
        'sw_version': get_sw_version(),
    })
예제 #35
0
def shutdown(request):
    """ shuts down the system and powers off the system """
    if not request.session.get("allow_shutdown"):
        return HttpResponseRedirect('/')
    request.session.pop("allow_shutdown")
    return render(request, 'system/shutdown.html', {
        'sw_name': get_sw_name(),
        'sw_version': get_sw_version(),
    })
예제 #36
0
def reboot(request):
    """ reboots the system """
    if not request.session.get("allow_reboot"):
        return HttpResponseRedirect('/')
    request.session.pop("allow_reboot")
    return render(request, 'system/reboot.html', {
        'sw_name': get_sw_name(),
        'sw_version': get_sw_version(),
    })
예제 #37
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced, Settings
        from freenasUI.middleware.client import client

        view = appPool.hook_app_index('freeadmin', request)
        view = [_f for _f in view if _f]
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].get_hostname()
        except:
            hostname = None

        try:
            settings = Settings.objects.all().order_by('-id')[0]
            wizard = not settings.stg_wizardshown
            if settings.stg_wizardshown is False:
                settings.stg_wizardshown = True
                settings.save()
        except:
            wizard = False
        sw_version = get_sw_version()
        sw_version_footer = get_sw_version(strip_build_num=True).split('-',
                                                                       1)[-1]

        try:
            with client as c:
                middleware_token = c.call('auth.generate_token', timeout=10)
        except Exception:
            middleware_token = None
            extra_log_files = (('/var/log/middlewared.log',
                                'middlewared_log'), )
            self.trace.rollbar_report(sys.exc_info(), request, sw_version,
                                      extra_log_files)

        return render(
            request, 'freeadmin/index.html', {
                'consolemsg': console,
                'hostname': hostname,
                'sw_name': get_sw_name(),
                'sw_version': sw_version,
                'sw_version_footer': sw_version_footer,
                'cache_hash': hashlib.md5(
                    sw_version.encode('utf8')).hexdigest(),
                'css_hook': appPool.get_base_css(request),
                'js_hook': appPool.get_base_js(request),
                'menu_hook': appPool.get_top_menu(request),
                'wizard': wizard,
                'middleware_token': middleware_token,
            })
예제 #38
0
def shutdown(request):
    """ shuts down the system and powers off the system """
    if not request.session.get("allow_shutdown"):
        return HttpResponseRedirect('/')
    request.session.pop("allow_shutdown")
    return render(request, 'system/shutdown.html', {
        'sw_name': get_sw_name(),
        'sw_version': get_sw_version(),
    })
예제 #39
0
def eula(request):
    eula = None
    if os.path.exists('/usr/local/share/truenas/eula.html'):
        with open('/usr/local/share/truenas/eula.html', 'r', encoding='utf8') as f:
            eula = f.read()

    return render(request, 'eula.html', {
        'sw_name': get_sw_name(),
        'sw_version': get_sw_version(),
        'eula': eula,
        'hide_buttons': True,
    })
예제 #40
0
파일: utils.py 프로젝트: william-gr/freenas
def new_ticket(data):

    sw_name = get_sw_name().lower()
    try:
        r = requests.post(
            'https://%s/%s/api/v1.0/ticket' % (ADDRESS, sw_name),
            data=json.dumps(data),
            headers={'Content-Type': 'application/json'},
            timeout=10,
        )
        data = r.json()
    except simplejson.JSONDecodeError, e:
        log.debug("Failed to decode ticket attachment response: %s", r.text)
        return False, r.text, None
예제 #41
0
파일: utils.py 프로젝트: william-gr/freenas
def ticket_attach(data, file_handler):

    sw_name = get_sw_name().lower()
    try:
        r = requests.post(
            'https://%s/%s/api/v1.0/ticket/attachment' % (ADDRESS, sw_name),
            data=data,
            timeout=10,
            files={'file': (file_handler.name, file_handler.file)},
        )
        data = r.json()
    except simplejson.JSONDecodeError, e:
        log.debug("Failed to decode ticket attachment response: %s", r.text)
        return False, r.text
예제 #42
0
def login_wrapper(
    request,
    template_name='registration/login.html',
    redirect_field_name=REDIRECT_FIELD_NAME,
    authentication_form=ExtendedAuthForm,
    current_app=None, extra_context=None,
):
    """
    Wrapper to login to do not allow login and redirect to
    shutdown, reboot or logout pages,
    instead redirect to /
    """

    # Overload hook_app_index to shortcut passive node
    # Doing that in another layer will use too many reasources
    view = appPool.hook_app_index('account_login', request)
    view = filter(None, view)
    if view:
        return view[0]

    if extra_context is None:
        extra_context = {}
    extra_context.update({
        'sw_login_version': get_sw_login_version(),
        'sw_name': get_sw_name(),
    })
    if not models.bsdUsers.has_root_password():
        authentication_form = forms.NewPasswordForm
        extra_context.update({
            'reset_password': True,
        })
    response = login(
        request,
        template_name='registration/login.html',
        redirect_field_name=redirect_field_name,
        authentication_form=authentication_form,
        current_app=current_app,
        extra_context=extra_context,
    )
    if response.status_code in (301, 302) and response._headers.get(
        'location', ('', '')
    )[1] in (
        reverse('system_reboot'),
        reverse('system_shutdown'),
        reverse('account_logout'),
    ):
        response._headers['location'] = ('Location', '/')
    elif request.user.is_authenticated():
        return HttpResponseRedirect('/')
    return response
예제 #43
0
파일: utils.py 프로젝트: Heliophobe/freenas
def fc_enabled():
    license, reason = get_license()
    if not license:
        return False
    sw_name = get_sw_name().lower()
    if sw_name == 'truenas':
        # Licenses issued before 2017-04-14 had a bug in the feature bit
        # for fibre channel, which means they were issue having
        # dedup+jails instead.
        if (Features.fibrechannel in license.features) or (
                Features.dedup in license.features
                and Features.jails in license.features
                and license.contract_start < datetime.date(2017, 4, 14)):
            return True
    return False
예제 #44
0
파일: views.py 프로젝트: vanloswang/freenas
def index(request):
    sw_name = get_sw_name().lower()

    license, reason = utils.get_license()
    allow_update = True
    if hasattr(notifier, "failover_status"):
        status = notifier().failover_status()
        if status not in ("MASTER", "SINGLE"):
            allow_update = False

    context = {"sw_name": sw_name, "license": license, "allow_update": allow_update}
    for c in appPool.hook_view_context("support.index", request):
        context.update(c)

    return render(request, "support/home.html", context)
예제 #45
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced, Settings

        view = appPool.hook_app_index('freeadmin', request)
        view = [_f for _f in view if _f]
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].get_hostname()
        except:
            hostname = None

        try:
            settings = Settings.objects.all().order_by('-id')[0]
            wizard = not settings.stg_wizardshown
            if settings.stg_wizardshown is False:
                settings.stg_wizardshown = True
                settings.save()
        except:
            wizard = False
        sw_version = get_sw_version()
        version = get_sw_version(strip_build_num=True)
        sw_version_footer = version.split('-', 1)[-1]
        sw_version_major = version.split('-')[1]

        return render(
            request, 'freeadmin/index.html', {
                'consolemsg': console,
                'hostname': hostname,
                'sw_name': get_sw_name(),
                'sw_year': get_sw_year(),
                'sw_version': sw_version,
                'sw_version_footer': sw_version_footer,
                'sw_version_major': sw_version_major,
                'cache_hash': hashlib.md5(
                    sw_version.encode('utf8')).hexdigest(),
                'css_hook': appPool.get_base_css(request),
                'js_hook': appPool.get_base_js(request),
                'menu_hook': appPool.get_top_menu(request),
                'wizard': wizard,
            })
예제 #46
0
def login_wrapper(
    request,
    template_name='registration/login.html',
    redirect_field_name=REDIRECT_FIELD_NAME,
    authentication_form=AuthenticationForm,
    current_app=None, extra_context=None,
):
    """
    Wrapper to login to do not allow login and redirect to
    shutdown, reboot or logout pages,
    instead redirect to /
    """
    if extra_context is None:
        extra_context = {}
    extra_context.update({
        'sw_login_version': get_sw_login_version(),
        'sw_name': get_sw_name(),
    })
    qs = models.bsdUsers.objects.filter(bsdusr_uid=0).exclude(
        bsdusr_unixhash='*'
    )
    if not qs.exists():
        authentication_form = forms.NewPasswordForm
        extra_context.update({
            'reset_password': True,
        })
    response = login(
        request,
        template_name='registration/login.html',
        redirect_field_name=redirect_field_name,
        authentication_form=authentication_form,
        current_app=current_app,
        extra_context=extra_context,
    )
    if response.status_code in (301, 302) and response._headers.get(
        'location', ('', '')
    )[1] in (
        reverse('system_reboot'),
        reverse('system_shutdown'),
        reverse('account_logout'),
    ):
        response._headers['location'] = ('Location', '/')
    elif request.user.is_authenticated():
        return HttpResponseRedirect('/')
    return response
예제 #47
0
파일: utils.py 프로젝트: binzyw/freenas
def fc_enabled():
    license, reason = get_license()
    if not license:
        return False
    sw_name = get_sw_name().lower()
    if sw_name == 'truenas':
        # Licenses issued before 2017-04-14 had a bug in the feature bit
        # for fibre channel, which means they were issue having
        # dedup+jails instead.
        if (
            Features.fibrechannel in license.features
        ) or (
            Features.dedup in license.features and
            Features.jails in license.features and
            license.contract_start < datetime.date(2017, 4, 14)
        ):
            return True
    return False
예제 #48
0
def login_wrapper(
    request,
    template_name='registration/login.html',
    redirect_field_name=REDIRECT_FIELD_NAME,
    authentication_form=AuthenticationForm,
    current_app=None,
    extra_context=None,
):
    """
    Wrapper to login to do not allow login and redirect to
    shutdown, reboot or logout pages,
    instead redirect to /
    """
    if extra_context is None:
        extra_context = {}
    extra_context.update({
        'sw_login_version': get_sw_login_version(),
        'sw_name': get_sw_name(),
    })
    qs = models.bsdUsers.objects.filter(bsdusr_uid=0).exclude(
        bsdusr_unixhash='*')
    if not qs.exists():
        authentication_form = forms.NewPasswordForm
        extra_context.update({
            'reset_password': True,
        })
    response = login(
        request,
        template_name='registration/login.html',
        redirect_field_name=redirect_field_name,
        authentication_form=authentication_form,
        current_app=current_app,
        extra_context=extra_context,
    )
    if response.status_code in (301, 302) and response._headers.get(
            'location', ('', ''))[1] in (
                reverse('system_reboot'),
                reverse('system_shutdown'),
                reverse('account_logout'),
            ):
        response._headers['location'] = ('Location', '/')
    elif request.user.is_authenticated():
        return HttpResponseRedirect('/')
    return response
예제 #49
0
파일: views.py 프로젝트: HySoaKa/freenas
def index(request):
    sw_name = get_sw_name().lower()

    license, reason = utils.get_license()
    allow_update = True
    if hasattr(notifier, 'failover_status'):
        status = notifier().failover_status()
        if status not in ('MASTER', 'SINGLE'):
            allow_update = False

    context = {
        'sw_name': sw_name,
        'license': license,
        'allow_update': allow_update,
    }
    for c in appPool.hook_view_context('support.index', request):
        context.update(c)

    return render(request, 'support/home.html', context)
예제 #50
0
def index(request):
    sw_name = get_sw_name().lower()

    license, reason = utils.get_license()
    allow_update = True
    if hasattr(notifier, 'failover_status'):
        status = notifier().failover_status()
        if status not in ('MASTER', 'SINGLE'):
            allow_update = False

    context = {
        'sw_name': sw_name,
        'license': license,
        'allow_update': allow_update,
    }
    for c in appPool.hook_view_context('support.index', request):
        context.update(c)

    return render(request, 'support/home.html', context)
예제 #51
0
def index(request):
    if request.method == 'POST':
        if request.POST.get('eula') == 'unaccept':
            request.session.pop('noeula', None)
            with client as c:
                c.call('truenas.unaccept_eula')
            return HttpResponseRedirect('/')

    sw_name = get_sw_name().lower()

    license = utils.get_license()[0]
    allow_update = True
    if hasattr(notifier, 'failover_status'):
        status = notifier().failover_status()
        if status not in ('MASTER', 'SINGLE'):
            allow_update = False

    context = {
        'sw_name': sw_name,
        'license': license,
        'fc_enabled': utils.fc_enabled(),
        'allow_update': allow_update,
    }
    for c in appPool.hook_view_context('support.index', request):
        context.update(c)
    if not notifier().is_freenas():
        with client as c:
            context['eula_not_accepted'] = not c.call('truenas.is_eula_accepted')

    if not notifier().is_freenas():
        form = forms.ProductionForm()
        if request.method == 'POST':
            form = forms.ProductionForm(request.POST)
            if form.is_valid():
                form.save()
                return JsonResp(
                    request,
                    message='Production status successfully updated.'
                )

        context['production_form'] = form

    return render(request, 'support/home.html', context)
예제 #52
0
파일: site.py 프로젝트: razzfazz/freenas
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced, Settings

        view = appPool.hook_app_index('freeadmin', request)
        view = [_f for _f in view if _f]
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].get_hostname()
        except:
            hostname = None

        try:
            settings = Settings.objects.all().order_by('-id')[0]
            wizard = not settings.stg_wizardshown
            if settings.stg_wizardshown is False:
                settings.stg_wizardshown = True
                settings.save()
        except:
            wizard = False
        sw_version = get_sw_version()
        sw_version_footer = get_sw_version(strip_build_num=True).split('-', 1)[-1]

        return render(request, 'freeadmin/index.html', {
            'consolemsg': console,
            'hostname': hostname,
            'sw_name': get_sw_name(),
            'sw_year': get_sw_year(),
            'sw_version': sw_version,
            'sw_version_footer': sw_version_footer,
            'cache_hash': hashlib.md5(sw_version.encode('utf8')).hexdigest(),
            'css_hook': appPool.get_base_css(request),
            'js_hook': appPool.get_base_js(request),
            'menu_hook': appPool.get_top_menu(request),
            'wizard': wizard,
        })
예제 #53
0
 def adminInterface(self, request):
     from freenasUI.network.models import GlobalConfiguration
     from freenasUI.system.models import Advanced
     try:
         console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
     except:
         console = False
     try:
         hostname = GlobalConfiguration.objects.order_by(
             '-id')[0].gc_hostname
     except:
         hostname = None
     sw_version = get_sw_version()
     return render(request, 'freeadmin/index.html', {
         'consolemsg': console,
         'hostname': hostname,
         'sw_name': get_sw_name(),
         'sw_version': sw_version,
         'cache_hash': hashlib.md5(sw_version).hexdigest(),
     })
예제 #54
0
    def forwards(self, orm):

        # Adding model 'Email'
        db.create_table(
            "system_email",
            (
                ("id", self.gf("django.db.models.fields.AutoField")(primary_key=True)),
                ("em_fromemail", self.gf("django.db.models.fields.CharField")(max_length=120, blank=True)),
                ("em_outgoingserver", self.gf("django.db.models.fields.CharField")(max_length=120, blank=True)),
                ("em_port", self.gf("django.db.models.fields.IntegerField")(default=25)),
                ("em_security", self.gf("django.db.models.fields.CharField")(default="plain", max_length=120)),
                ("em_smtp", self.gf("django.db.models.fields.BooleanField")(default=False)),
                ("em_user", self.gf("django.db.models.fields.CharField")(max_length=120, null=True, blank=True)),
                ("em_pass", self.gf("django.db.models.fields.CharField")(max_length=120, null=True, blank=True)),
            ),
        )
        db.send_create_signal("system", ["Email"])

        em = orm.Email()
        em.em_fromemail = "root@%s.local" % (get_sw_name().lower(),)
        em.em_port = 25
        em.em_smtp = False
        em.save()