Example #1
0
 def handle_api_devices(self, http_context):
     path = '/etc/linuxmuster/sophomorix/default-school/devices.csv'
     fieldnames = [
         'room',
         'hostname',
         'group',
         'mac',
         'ip',
         'officeKey',
         'windowsKey',
         'dhcpOptions',
         'sophomorixRole',
         'lmnReserved10',
         'pxeFlag',
         'lmnReserved12',
         'lmnReserved13',
         'lmnReserved14',
         'sophomorixComment',
         'options',
     ]
     if http_context.method == 'GET':
         return list(
             csv.DictReader(CSVSpaceStripper(open(path)),
                            delimiter=';',
                            fieldnames=fieldnames))
     if http_context.method == 'POST':
         data = http_context.json_body()
         for item in data:
             item.pop('_isNew', None)
             item.pop('null', None)
         lmn_backup_file(path)
         with open(path, 'w') as f:
             csv.DictWriter(f, delimiter=';',
                            fieldnames=fieldnames).writerows(data)
Example #2
0
    def handle_api_subnet(self, http_context):
        school = 'default-school'
        path = '/etc/linuxmuster/subnets.csv'
        fieldnames = [
            'network',
            'routerIp',
            'beginRange',
            'endRange',
            'setupFlag',
        ]
        if http_context.method == 'GET':
            return list(
                csv.DictReader(CSVSpaceStripper(open(path)),
                               delimiter=';',
                               fieldnames=fieldnames))
        if http_context.method == 'POST':
            data = http_context.json_body()
            header = """
# modified by Webui at %s
# /etc/linuxmuster/subnets.csv
#
# [email protected]
#
# Network/Prefix ; Router-IP (last available IP in network) ; 1. Range-IP ; Last-Range-IP ; SETUP-Flag
#
# server subnet definition
""" % (datetime.now().strftime("%Y%m%d%H%M%S"))
            separator = """
# add your subnets below
#
"""
            tmp = path + '_tmp'
            with open(tmp, 'w') as f:
                f.write(header)
                # Write setup subnet : Sure that data[0] contains the setup subnet ?
                csv.DictWriter(
                    f,
                    delimiter=';',
                    fieldnames=fieldnames,
                    #encoding='utf-8'
                ).writerows([data[0]])
                # Write custom subnets
                f.write(separator)
                csv.DictWriter(
                    f,
                    delimiter=';',
                    fieldnames=fieldnames,
                    #encoding='utf-8'
                ).writerows(data[1:])
            if not filecmp.cmp(tmp, path):
                lmn_backup_file(path)
                os.rename(tmp, path)
            else:
                os.unlink(tmp)
            try:
                subprocess.check_call(
                    'linuxmuster-import-subnets > /tmp/import_devices.log',
                    shell=True)
            except Exception as e:
                raise EndpointError(None, message=str(e))
Example #3
0
 def handle_api_extra_courses(self, http_context):
     school = 'default-school'
     path = '/etc/linuxmuster/sophomorix/' + school + '/extraclasses.csv'
     if os.path.isfile(path) is False:
         os.mknod(path)
     fieldnames = [
         'course',
         'base_name',
         'count',
         'birthday',
         'gecos',
         'password',
         'removal_date',
     ]
     if http_context.method == 'GET':
         with authorize('lm:users:extra-courses:read'):
             return list(
                 csv.DictReader(CSVSpaceStripper(
                     open(path),
                     encoding=http_context.query.get('encoding', 'utf-8')),
                                delimiter=';',
                                fieldnames=fieldnames))
     if http_context.method == 'POST':
         with authorize('lm:users:extra-courses:write'):
             data = http_context.json_body()
             for item in data:
                 item.pop('_isNew', None)
             lmn_backup_file(path)
             with open(path, 'w') as f:
                 csv.DictWriter(f,
                                delimiter=';',
                                fieldnames=fieldnames,
                                encoding=http_context.query.get(
                                    'encoding', 'utf-8')).writerows(data)
Example #4
0
    def handle_api_printers(self, http_context):
        access_path = '/etc/cups/access.conf'
        printers_path = '/etc/cups/printers.conf'
        if http_context.method == 'GET':
            result = []
            found_names = []
            for line in open(access_path):
                if line.startswith('<Location'):
                    printer = {
                        'name': line.split()[-1].rstrip(' >').split('/')[-1],
                        'items': []
                    }
                    found_names.append(printer['name'])
                    result.append(printer)
                if line.strip().startswith('Allow From'):
                    printer['items'].append(line.strip().split()[-1])
            for line in open(printers_path):
                if line.startswith('<Printer'):
                    printer = {
                        'name': line.split()[-1].rstrip(' >').split('/')[-1],
                        'items': []
                    }
                    if printer['name'] not in found_names:
                        result.append(printer)
            return result
        if http_context.method == 'POST':
            content = ''
            for printer in http_context.json_body():
                if len(printer['items']) == 0:
                    continue
                content += '<Location /printers/%s>\n' % printer['name']
                content += '\tOrder Deny,Allow\n'
                content += '\tDeny From All\n'
                for item in printer['items']:
                    content += '\tAllow From %s\n' % item

                for v in psutil.net_if_addrs().values():
                    for x in v:
                        if not ':' in x.address:
                            content += '\tAllow From %s\n' % x.address

                content += '</Location>\n'

            lmn_backup_file(access_path)
            with open(access_path, 'w') as f:
                f.write(content)
Example #5
0
    def handle_api_quotas(self, http_context):
        path = '/etc/linuxmuster/sophomorix/quota.txt'  ## TODO DELETE
        mpath = '/etc/linuxmuster/sophomorix/mailquota.txt'
        if http_context.method == 'GET':
            r = {}

            for line in open(path):
                if ':' in line and not line.startswith('#'):
                    k, v = line.split(':', 1)
                    r[k.strip()] = {
                        'home': int(v.split('+')[0].strip()),
                        'var': int(v.split('+')[1].strip()),
                    }

            for line in open(mpath):
                if ':' in line and not line.startswith('#'):
                    k, v = line.split(':', 1)
                    k = k.strip()
                    if k in r:
                        r[k]['mail'] = int(v.strip())

            return r
        if http_context.method == 'POST':
            lmn_backup_file(path)
            with open(path, 'w') as f:
                f.write('\n'.join('%s: %s+%s' % (
                    k,
                    v['home'],
                    v['var'],
                ) for k, v in http_context.json_body().items()))
            lmn_backup_file(mpath)
            with open(mpath, 'w') as f:
                f.write('\n'.join('%s: %s' % (
                    k,
                    v['mail'],
                ) for k, v in http_context.json_body().items()
                                  if v.get('mail', None)))
Example #6
0
 def handle_api_teachers(self, http_context):
     school = 'default-school'
     path = '/etc/linuxmuster/sophomorix/' + school + '/teachers.csv'
     if os.path.isfile(path) is False:
         os.mknod(path)
     fieldnames = [
         'class',
         'last_name',
         'first_name',
         'birthday',
         'login',
         'password',
         'usertoken',
         'quota',
         'mailquota',
         'reserved',
     ]
     if http_context.method == 'GET':
         with authorize('lm:users:teachers:read'):
             return list(
                 csv.DictReader(CSVSpaceStripper(
                     open(path),
                     encoding=http_context.query.get('encoding', 'utf-8')),
                                delimiter=';',
                                fieldnames=fieldnames))
     if http_context.method == 'POST':
         with authorize('lm:users:teachers:write'):
             data = http_context.json_body()
             for item in data:
                 item.pop('_isNew', None)
             lmn_backup_file(path)
             with open(path, 'w') as f:
                 csv.DictWriter(f,
                                delimiter=';',
                                fieldnames=fieldnames,
                                encoding=http_context.query.get(
                                    'encoding', 'utf-8')).writerows(data)
Example #7
0
    def handle_api_settings(self, http_context):
        school = 'default-school'
        path = '/etc/linuxmuster/sophomorix/' + school + '/school.conf'
        if http_context.method == 'GET':
            # Parse csv config file
            config = ConfigParser()
            config.read(path)
            settings = {}
            for section in config.sections():
                settings[section] = {}
                for (key, val) in config.items(section):
                    if val.isdigit():
                        val = int(val)
                        #settings[section][key] = val
                    if val == 'no':
                        val = False
                    if val == 'yes':
                        val = True
                    settings[section][key] = val
            return settings

        if http_context.method == 'POST':
            content = ''
            data = http_context.json_body()
            if 'admins_print' in data:
                for k, v in self.EMAIL_MAPPING.items():
                    data['admins_print'] = data['admins_print'].replace(k, v)

            def convert_value(v):
                if type(v) is int:
                    return str(v)
                elif type(v) is bool:
                    return 'yes' if v else 'no'
                else:
                    return '%s' % v

            section_name = ''
            set_control = 0
            for line in open(path):
                originalLine = line
                # remove everything before comment
                if '#' in line:
                    line = line.split('#', 1)[1]
                    line = '#' + line
                if line.startswith('#'):
                    content += originalLine
                    continue
                # if new section found
                if line.startswith('['):
                    # check if last section contained all keys
                    if set_control is 1:
                        for k in data[section_name]:
                            if k not in keys_found:
                                k = k.strip()
                                v = v.strip()
                                content += "\t%s = %s\n" % (
                                    k.upper(),
                                    convert_value(data[section_name][k]))
                    # start of with new section
                    set_control = 1
                    keys_found = []
                    section_name = line.strip('[]\n')
                else:
                    k, v = line.split('=', 1)
                    k = k.strip().lower()
                    v = v.strip()
                    if k in data[section_name]:
                        newValue = convert_value(data[section_name][k])
                        keys_found.append(k)

                        originalLine = originalLine.replace(v, newValue)
                        if newValue not in v:
                            originalLine = originalLine.lstrip('#')
                content += originalLine

            lmn_backup_file(path)
            with open(path, 'w') as f:
                f.write(content)
Example #8
0
    def handle_api_config(self, http_context, name=None):
        path = os.path.join(self.LINBO_PATH, name)

        if http_context.method == 'GET':
            config = {
                'config': {},
                'partitions': [],
                'os': [],
            }
            for line in open(path, 'rb'):
                line = line.decode('utf-8', errors='ignore')
                line = line.split('#')[0].strip()

                if line.startswith('['):
                    section = {}
                    section_name = line.strip('[]')
                    if section_name == 'Partition':
                        config['partitions'].append(section)
                    elif section_name == 'OS':
                        config['os'].append(section)
                    else:
                        config['config'][section_name] = section
                elif '=' in line:
                    k, v = line.split('=', 1)
                    v = v.strip()
                    if v in ['yes', 'no']:
                        v = v == 'yes'
                    section[k.strip()] = v
            return config

        if http_context.method == 'DELETE':
            lmn_backup_file(path)
            os.unlink(path)

        if http_context.method == 'POST':
            content = ''
            data = http_context.json_body()

            def convert(v):
                if type(v) is bool:
                    return 'yes' if v else 'no'
                return v

            for section_name, section in data['config'].items():
                content += '[%s]\n' % section_name
                for k, v in section.items():
                    content += '%s = %s\n' % (k, convert(v))
                content += '\n'
            for partition in data['partitions']:
                content += '[Partition]\n'
                for k, v in partition.items():
                    if k[0] == '_':
                        continue
                    content += '%s = %s\n' % (k, convert(v))
                content += '\n'
            for partition in data['os']:
                content += '[OS]\n'
                for k, v in partition.items():
                    content += '%s = %s\n' % (k, convert(v))
                content += '\n'

            lmn_write_configfile(path, content)
            os.chmod(path, 0o755)