diff --git a/pym/unix/unix.py b/pym/unix/unix.py index d7fc36c..75b4a2e 100644 --- a/pym/unix/unix.py +++ b/pym/unix/unix.py @@ -25,7 +25,7 @@ import shutil _ = lambda x: x from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate) -from calculate.lib.cl_ldap import ldap, LDAPConnectError +from calculate.lib.cl_ldap import ldap, LDAPConnectError, LDAPBadSearchFilter setLocalTranslate('cl_unix3', sys.modules[__name__]) __ = getLazyLocalTranslate(_) @@ -123,9 +123,15 @@ class UnixGroups(object): return group.group_name return value + def _groupname(self, name, comment): + if comment != name: + return "{0} ({1})".format(name, comment) + else: + return name + def ldap_group_list(self): groups = list(x for x in self.iterate_ldap_group("cn=*")) - return [(x.group_name, "%s (%s)" % (x.group_name, x.comment)) + return [(x.group_name, self._groupname(x.group_name, x.comment)) for x in sorted(groups, key=lambda k: k.gid)] def ldap_group_names(self): @@ -197,7 +203,7 @@ class UnixGroups(object): UnixUser = namedtuple( "UnixUser", ['username', 'uid', 'gid', 'comment', 'homedir', 'shell', - 'visible', 'lock']) + 'visible', 'lock', 'pass_set']) class PasswdFile(object): @@ -211,7 +217,7 @@ class PasswdFile(object): if len(data) >= 7 and data[2].isdigit() and data[3].isdigit(): yield UnixUser(data[0], int(data[2]), int(data[3]), data[4], data[5], data[6], True, - False) + False, False) class UnixUsers(object): @@ -272,6 +278,7 @@ class UnixUsers(object): user['loginShell'][0], self.flag_to_visible(user['shadowFlag'][0]), self.flag_to_lock(user['shadowExpire'][0]), + self.has_password(user['userPassword'][0]), ) def search_ldap_user(self, search_filter): @@ -279,6 +286,11 @@ class UnixUsers(object): return user return None + def has_password(self, password): + if password and password != self.DeletedPassword: + return True + return False + def search_ldap_user_name(self, value): return self.search_ldap_user("uid=%s" % value) @@ -311,9 +323,15 @@ class UnixUsers(object): return user.username return value + def _username(self, name, comment): + if comment != name: + return "{0} ({1})".format(name, comment) + else: + return name + def ldap_user_list(self): users = list(x for x in self.iterate_ldap_user("uid=*")) - return [(x.username, "%s (%s)" % (x.username, x.comment)) + return [(x.username, self._username(x.username, x.comment)) for x in sorted(users, key=lambda y: y.uid)] def ldap_user_names(self): @@ -470,7 +488,7 @@ class Unix(Ldap): uu.remove_user(username) return True - def add_users_in_group(self, users, groupname): + def _add_users_in_group(self, users, groupname): """ Добавить пользователей в группу """ @@ -486,6 +504,20 @@ class Unix(Ldap): return False def remove_users_from_group(self, users, groupname): + self._remove_users_from_group(users, groupname) + self.printSUCCESS(_("Users {logins} was removed " + "from group {group}").format( + logins=", ".join(users), group=groupname)) + return True + + def add_users_in_group(self, users, groupname): + self._add_users_in_group(users, groupname) + self.printSUCCESS(_("Users {logins} was added " + "to group {group}").format( + logins=", ".join(users), group=groupname)) + return True + + def _remove_users_from_group(self, users, groupname): """ Удалить пользователей из групп """ @@ -505,7 +537,10 @@ class Unix(Ldap): Добавить пользователя в группы """ for group in groups: - self.add_users_in_group([user], group) + self._add_users_in_group([user], group) + self.printSUCCESS(_("User {login} added " + "to groups {groups}").format( + login=user, groups=", ".join(groups))) return True def remove_user_from_groups(self, user, groups): @@ -513,7 +548,10 @@ class Unix(Ldap): Удалить пользователя из группы """ for group in groups: - self.remove_users_from_group([user], group) + self._remove_users_from_group([user], group) + self.printSUCCESS(_("User {login} removed " + "from groups {groups}").format( + login=user, groups=", ".join(groups))) return True def modify_user(self, login, pw, gid, shell, visible, lock, comment): @@ -599,12 +637,7 @@ class Unix(Ldap): return True def show_groups(self, fields, count, offset): - dv = self.clVars - # list_group_name = sorted(dv.Choice('cl_core_group')) - - # if not list_group_name: - # self.printSUCCESS(_("No groups")) head = [dv.getInfo(x).label for x in fields] body = [] @@ -612,32 +645,49 @@ class Unix(Ldap): groups_dn = self.clVars.Get('ld_unix_groups_dn') ug = UnixGroups(ldap_connect, groups_dn) + users_dn = self.clVars.Get('ld_unix_users_dn') + uu = UnixUsers(ldap_connect, users_dn) + + filters = (self.clVars.getInfo(x) + for x in ('cl_unix_group_filter_name', + 'cl_unix_group_filter_id', + 'cl_unix_group_filter_comment', + 'cl_unix_group_filter_users', + 'cl_unix_group_filter_primary')) + filters = [x.test for x in filters if x.enabled()] + + def all_users(group): + for user in uu.iterate_ldap_user("gidNumber=%d" % group.gid): + yield "<%s>" % user.username + for user in group.user_list: + yield user + variables_mapping = { 'ur_unix_group_name': lambda group: group.group_name, 'ur_unix_group_id': lambda group: str(group.gid), 'ur_unix_group_comment': lambda group: group.comment, - 'ur_unix_group_users': lambda group: ", ".join(group.user_list) + 'ur_unix_group_users': lambda group: ", ".join(all_users(group)) } for group in ug.iterate_ldap_group("cn=*", offset, count): - body.append([variables_mapping.get(x)(group) for x in fields]) - # body.append((group.group_name, str(group.gid), - # group.comment, ",".join(group.user_list))) + if all(x(group) for x in filters): + body.append([variables_mapping.get(x)(group) for x in fields]) mapping = {'ur_unix_group_name': 'ur_unix_group_name_exists'} table_fields = [mapping.get(x, '') for x in fields] - if body: - self.printTable( - _("Groups"), head, body, + if not body: + body = [[]] + dv.Invalidate('ur_unix_group_count') + self.printTable( + _("Groups") if any(body) else _("No groups"), head, body, fields=table_fields, onClick='unix_groupmod' if any(table_fields) else None, addAction='unix_groupadd', records=self.clVars.Get('core.cl_page_max')) + if any(body): num_page, count_page = getPagesInterval( count, offset, int(self.clVars.Get('core.cl_page_max'))) self.printSUCCESS(_('page %d from ') % num_page + str(count_page)) - else: - self.printSUCCESS(_("No groups")) return True def show_group(self, groupname): @@ -671,12 +721,8 @@ class Unix(Ldap): self.printTable(_("Group info"), head, body) return True - def show_users(self, fields, count, offset): + def show_users(self, login, fields, count, offset): dv = self.clVars - # list_group_name = sorted(dv.Choice('cl_core_group')) - - # if not list_group_name: - # self.printSUCCESS(_("No groups")) head = [dv.getInfo(x).label for x in fields] body = [] @@ -688,6 +734,20 @@ class Unix(Ldap): yesno = lambda x: _("Yes") if x else _("No") + filters = (self.clVars.getInfo(x) + for x in ('cl_unix_user_filter_login', + 'cl_unix_user_filter_pw_set', + 'cl_unix_user_filter_comment', + 'cl_unix_user_filter_uid', + 'cl_unix_user_filter_gid', + 'cl_unix_user_filter_home_path', + 'cl_unix_user_filter_shell', + 'cl_unix_user_filter_groups', + 'cl_unix_user_filter_visible_set', + 'cl_unix_user_filter_lock_set', + )) + filters = [x.test for x in filters if x.enabled()] + variables_mapping = { 'ur_unix_uid': lambda user: user.uid, 'ur_unix_login': lambda user: user.username, @@ -701,13 +761,17 @@ class Unix(Ldap): ), 'ur_unix_home_path': lambda user: user.homedir, 'ur_unix_shell': lambda user: user.shell, - 'ur_unix_pw_set': lambda user: 'HZ', + 'ur_unix_pw_set': lambda user: yesno(user.pass_set), } mapping = {'ur_unix_login': 'ur_unix_login_exists'} - for user in uu.iterate_ldap_user("uid=*", offset, count): - print user - body.append([variables_mapping.get(x)(user) for x in fields]) + try: + for user in uu.iterate_ldap_user("uid=%s" % login, offset, count): + if all(x(user) for x in filters): + body.append( + [variables_mapping.get(x)(user) for x in fields]) + except LDAPBadSearchFilter: + raise UnixError(_("Wrong user pattern")) table_fields = [mapping.get(x, '') for x in fields] if not body: @@ -719,9 +783,9 @@ class Unix(Ldap): onClick='unix_usermod' if any(table_fields) else None, addAction='unix_useradd', records=str(self.clVars.Get('unix.ur_unix_user_count'))) - num_page, count_page = getPagesInterval( - count, offset, int(self.clVars.Get('unix.ur_unix_user_count'))) if any(body): + num_page, count_page = getPagesInterval( + count, offset, int(self.clVars.Get('unix.ur_unix_user_count'))) self.printSUCCESS(_('page %d from ') % num_page + str(count_page)) return True diff --git a/pym/unix/utils/cl_unix_groupmod.py b/pym/unix/utils/cl_unix_groupmod.py index 5d1a002..a9ff519 100644 --- a/pym/unix/utils/cl_unix_groupmod.py +++ b/pym/unix/utils/cl_unix_groupmod.py @@ -56,15 +56,11 @@ class ClUnixGroupmodAction(Action): # список задач для действия tasks = [ {'name': 'remove_users', - 'message': _("Users {unix.ur_unix_group_users_del} removed " - "from group {unix.ur_unix_group_name}"), 'method': 'Unix.remove_users_from_group(unix.ur_unix_group_users_del,' 'unix.ur_unix_group_name_exists)', 'condition': lambda Get: Get('unix.ur_unix_group_users_del') }, {'name': 'append_users', - 'message': _("Users {unix.ur_unix_group_users_add} added " - "to group {unix.ur_unix_group_name}"), 'method': 'Unix.add_users_in_group(unix.ur_unix_group_users_add,' 'unix.ur_unix_group_name_exists)', 'condition': lambda Get: Get('unix.ur_unix_group_users_add') @@ -74,7 +70,8 @@ class ClUnixGroupmodAction(Action): "{unix.ur_unix_group_newname}"), 'method': 'Unix.rename_group(unix.ur_unix_group_name,' 'unix.ur_unix_group_newname)', - 'condition': lambda Get: Get('unix.ur_unix_group_newname') + 'condition': lambda Get: (Get('unix.ur_unix_group_newname') != + Get('unix.ur_unix_group_name')) }, {'name': 'change_comment', 'message': _("Changed comment for group {unix.ur_unix_group_name} to " diff --git a/pym/unix/utils/cl_unix_useradd.py b/pym/unix/utils/cl_unix_useradd.py index f3ffcad..af617ca 100644 --- a/pym/unix/utils/cl_unix_useradd.py +++ b/pym/unix/utils/cl_unix_useradd.py @@ -61,6 +61,10 @@ class ClUnixUseraddAction(Action): 'tasks': meta_tasks.ldif_task("unix.ld_unix_dn,unix.ld_unix_pw", Actions.Setup) }, + {'name': "info", + 'message': __("Created primary group {ur_unix_primary_group}"), + 'condition': lambda Get: Get('cl_unix_create_group_set') == "on" + }, {'name': 'user_groups', 'method': 'Unix.add_user_in_groups(ur_unix_login,ur_unix_groups)', 'condition': lambda Get: Get('ur_unix_groups') diff --git a/pym/unix/utils/cl_unix_usermod.py b/pym/unix/utils/cl_unix_usermod.py index 45a54c7..c058ec3 100644 --- a/pym/unix/utils/cl_unix_usermod.py +++ b/pym/unix/utils/cl_unix_usermod.py @@ -61,15 +61,11 @@ class ClUnixUsermodAction(Action): 'ur_unix_comment)', }, {'name': 'remove_groups', - 'message': _("User {unix.ur_unix_login} removed from " - "groups {unix.ur_unix_groups_del}"), 'method': 'Unix.remove_user_from_groups(unix.ur_unix_login,' 'unix.ur_unix_groups_del)', 'condition': lambda Get: Get('unix.ur_unix_groups_del') }, {'name': 'append_groups', - 'message': _("User {unix.ur_unix_login} added " - "to groups {unix.ur_unix_groups_add}"), 'method': 'Unix.add_user_in_groups(unix.ur_unix_login,' 'unix.ur_unix_groups_add)', 'condition': lambda Get: Get('unix.ur_unix_groups_add') diff --git a/pym/unix/utils/cl_unix_usershow.py b/pym/unix/utils/cl_unix_usershow.py index 54bc5b6..2c249da 100644 --- a/pym/unix/utils/cl_unix_usershow.py +++ b/pym/unix/utils/cl_unix_usershow.py @@ -53,12 +53,13 @@ class ClUnixUsershowAction(Action): # список задач для действия tasks = [ {'name': 'view_users', - 'method': 'Unix.show_users(unix.cl_unix_user_show_fields,' + 'method': 'Unix.show_users(unix.ur_unix_user_show,' + 'unix.cl_unix_user_show_fields,' 'core.cl_page_count,core.cl_page_offset)', - 'condition': lambda Get: Get('ur_unix_user_show') == "all" + 'condition': lambda Get: "*" in Get('ur_unix_user_show') }, {'name': 'view_user', 'method': 'Unix.show_user(ur_unix_user_show)', - 'condition': lambda Get: Get('ur_unix_user_show') != "all" + 'condition': lambda Get: "*" not in Get('ur_unix_user_show') } ] diff --git a/pym/unix/variables/__init__.py b/pym/unix/variables/__init__.py index cac3c44..d0ef3a7 100644 --- a/pym/unix/variables/__init__.py +++ b/pym/unix/variables/__init__.py @@ -16,5 +16,8 @@ import action import unix +import filters +import groups +import users section = "unix" diff --git a/pym/unix/variables/filters.py b/pym/unix/variables/filters.py new file mode 100644 index 0000000..2ea9e52 --- /dev/null +++ b/pym/unix/variables/filters.py @@ -0,0 +1,392 @@ +# -*- coding: utf-8 -*- + +# Copyright 2016 Mir Calculate. http://www.calculate-linux.org +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +import re +from fnmatch import fnmatch +from calculate.lib.datavars import (Variable, VariableInterface, VariableError) +from calculate.unix.variables.helpers import (UnixUserHelper, UnixGroupHelper) +import operator + +_ = lambda x: x +from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate) + +setLocalTranslate('cl_unix3', sys.modules[__name__]) +__ = getLazyLocalTranslate(_) + +""" +String +--filter-comment fasdfad faksjdflk* ---fasdfas|fasdfasd + +Integer +--filter-uid 321 >12000 <11000 + +--filter-uid 321, >=, <, >, >= 325-400 + +Boolean +--filter-password on/off/auto +""" + + +class FilterHelper(VariableInterface): + def test(self, value): + """ + Проверка попадания значения под фильтр + :param value: + :return: + """ + return True + + def enabled(self): + filter_values = self.Get() + if not filter_values: + return False + return True + + +class FilterStringHelper(FilterHelper): + """ + Для фильтрации строковых данных + + user10, user*, !user*, !user20 + """ + value = "" + metavalue = "FILTER" + + def test_value(self, value): + filter_values = self.Get() + if not filter_values: + return True + + for filter_value in filter_values.split('|'): + revert = lambda x: x + if filter_value[:1] == "!" or filter_value[:2] == r"\!": + revert = lambda x: not x + if filter_value[:2] == r"\!": + filter_value = filter_value[2:] + else: + filter_value = filter_value[1:] + if revert(fnmatch(value, filter_value)): + return True + else: + return False + + +class FilterListHelper(FilterHelper): + """ + Для фильтрации данных со списками + + user10, user*, !user*, !user20 + """ + value = "" + metavalue = "FILTER" + + def test_value(self, value): + value = list(value) + filter_values = self.Get() + if not filter_values: + return True + + for filter_value in filter_values.split('|'): + revert = lambda x: x + if filter_value[:1] == "!" or filter_value[:2] == r"\!": + revert = lambda x: not x + if filter_value[:2] == r"\!": + filter_value = filter_value[2:] + else: + filter_value = filter_value[1:] + results = [fnmatch(x, filter_value) for x in value] + if revert(any(results)): + return True + else: + return False + + +class FilterIntegerHelper(FilterHelper): + """ + Для фильтрации числовых данных + + >5, <5, >=5, <=5, 5, 5-10 + """ + value = "" + filter_format = re.compile("^(\d+)-(\d+)|(<=|>=|<|>)?(\d+)$") + metavalue = "FILTER" + + def test_value(self, value): + filter_value = self.Get() + if not filter_value: + return True + start, end, op, number = self.filter_format.search( + filter_value).groups() + + if start and end: + return int(start) <= value <= int(end) + number = int(number) + if op: + return {"<=": operator.le, + ">=": operator.ge, + "<": operator.lt, + ">": operator.gt}.get(op)(value, number) + else: + return value == number + + def check(self, value): + if not self.filter_format.match(value): + raise VariableError(_("Wrong filter")) + + +class FilterBooleanHelper(FilterHelper): + """ + Для фильтрации булевых данных + """ + type = "boolauto" + value = "auto" + metavalue = "ON/OFF/AUTO" + + def enabled(self): + filter_value = self.Get() + if filter_value == "auto": + return False + return True + + def test_value(self, value): + filter_value = self.Get() + if filter_value == "auto": + return True + return Variable.isTrue(filter_value) == value + + +class VariableClUnixUserFilterLogin(FilterStringHelper, Variable): + """ + Фильтр на login + """ + opt = ["--filter-login"] + + def init(self): + self.label = _("Login filter") + self.help = _("set login filter") + + def test(self, user): + return self.test_value(user.username) + + +class VariableClUnixUserFilterComment(FilterStringHelper, Variable): + """ + Фильтр на полное имя пользователя + """ + opt = ["--filter-fullname"] + + def init(self): + self.label = _("Full name filter") + self.help = _("set full name filter") + + def test(self, user): + return self.test_value(user.comment) + + +class VariableClUnixUserFilterHomePath(FilterStringHelper, Variable): + """ + Фильтр на домашнюю директорию + """ + opt = ["--filter-homedir"] + + def init(self): + self.label = _("Home directory filter") + self.help = _("set home directory filter") + + def test(self, user): + return self.test_value(user.homedir) + + +class VariableClUnixUserFilterShell(FilterStringHelper, Variable): + """ + Фильтр на shell + """ + opt = ["--filter-shell"] + + def init(self): + self.label = _("Shell filter") + self.help = _("set shell filter") + + def test(self, user): + return self.test_value(user.shell) + + +class VariableClUnixUserFilterGid(FilterStringHelper, UnixGroupHelper, + Variable): + """ + Фильтр на primary group + """ + opt = ["--filter-gid"] + + def init(self): + self.label = _("Primary group filter") + self.help = _("set primary group filter") + + def test(self, user): + primary_group = str(self.gid_to_name(str(user.gid))) + return self.test_value(primary_group) + + def set(self, value): + if value.isdigit(): + value = self.gid_to_name(str(value)) + return str(value) + + +class VariableClUnixUserFilterGroups(FilterListHelper, UnixGroupHelper, + Variable): + """ + Фильтр на вхождение пользователя в группу + """ + opt = ["--filter-groups"] + + def init(self): + self.label = _("Supplimentary group filter") + self.help = _("set supplimentary group filter") + + def test(self, user): + return self.test_value(x.group_name for x in self.iterate_ldap_group( + "memberUid=%s" % user.username)) + + +class VariableClUnixUserFilterUid(FilterIntegerHelper, Variable): + """ + Фильтр на id пользователя + """ + opt = ["--filter-uid"] + + def init(self): + self.label = _("Uid filter") + self.help = _("set uid filter") + + def test(self, user): + return self.test_value(user.uid) + + +class VariableClUnixUserFilterPwSet(FilterBooleanHelper, Variable): + """ + Фильтр на наличие пароля + """ + opt = ["--filter-password"] + + def init(self): + self.label = _("Password availability filter") + self.help = _("set password availability filter") + + def test(self, user): + return self.test_value(user.pass_set) + + +class VariableClUnixUserFilterVisibleSet(FilterBooleanHelper, Variable): + """ + Фильтр на видимость + """ + opt = ["--filter-visible"] + + def init(self): + self.label = _("Visibility filter") + self.help = _("set visibility filter") + + def test(self, user): + return self.test_value(user.visible) + + +class VariableClUnixUserFilterLockSet(FilterBooleanHelper, Variable): + """ + Фильтр на login + """ + opt = ["--filter-lock"] + + def init(self): + self.label = _("Lock filter") + self.help = _("set lock filter") + + def test(self, user): + return self.test_value(user.lock) + + +class VariableClUnixGroupFilterName(FilterStringHelper, Variable): + """ + Фильтр на group name + """ + opt = ["--filter-name"] + + def init(self): + self.label = _("Name filter") + self.help = _("set name filter") + + def test(self, group): + return self.test_value(group.group_name) + + +class VariableClUnixGroupFilterId(FilterIntegerHelper, Variable): + """ + Фильтр на group id + """ + opt = ["--filter-gid"] + + def init(self): + self.label = _("Group id filter") + self.help = _("set group id filter") + + def test(self, group): + return self.test_value(group.gid) + + +class VariableClUnixGroupFilterComment(FilterStringHelper, Variable): + """ + Фильтр на group comment + """ + opt = ["--filter-comment"] + + def init(self): + self.label = _("Comment filter") + self.help = _("set comment filter") + + def test(self, group): + return self.test_value(group.comment) + + +class VariableClUnixGroupFilterUsers(FilterListHelper, Variable): + """ + Фильтр на наличие пользователей в группе + """ + opt = ["--filter-users"] + + def init(self): + self.label = _("Users filter") + self.help = _("set users filter") + + def test(self, group): + return self.test_value(group.user_list) + + +class VariableClUnixGroupFilterPrimary(FilterListHelper, UnixUserHelper, + Variable): + """ + Фильтр на наличие пользователей в primary-group + """ + opt = ["--filter-primary"] + + def init(self): + self.label = _("Users filter") + self.help = _("set users filter") + + def test(self, group): + return self.test_value( + user.username for user in self.iterate_ldap_user( + "gidNumber=%d" % group.gid) + ) diff --git a/pym/unix/variables/groups.py b/pym/unix/variables/groups.py new file mode 100644 index 0000000..96177ee --- /dev/null +++ b/pym/unix/variables/groups.py @@ -0,0 +1,471 @@ +# -*- coding: utf-8 -*- + +# Copyright 2016 Mir Calculate. http://www.calculate-linux.org +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +from calculate.lib.datavars import (ReadonlyVariable, Variable, + VariableError) +from calculate.ldap.variables.helpers import (LdapSearchHelper, LdapMaxHelper) +from calculate.unix.variables.helpers import (UnixUserHelper, UnixGroupHelper, + UnixActionHelper) +from .action import Actions + +_ = lambda x: x +from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate) + +setLocalTranslate('cl_unix3', sys.modules[__name__]) +__ = getLazyLocalTranslate(_) + + +class VariableUrUnixGroupName(LdapSearchHelper, UnixActionHelper, Variable): + """ + Название группы + """ + base_dn = "{ld_unix_groups_dn}" + search_filter = '(cn={value})' + + untrusted = True + opt = ("ur_unix_group_name",) + metavalue = "GROUP" + + def init(self): + self.label = _("Group") + self.help = _("set the group name") + + def get_new(self): + return "" + + def get_exists(self): + return self.Get('ur_unix_group_name_exists') + + def check(self, value): + if not value: + raise VariableError(_("You should specify group name")) + if self.check_name(value): + raise VariableError(_("Group name already exists")) + + +class VariableUrUnixGroupLabel(ReadonlyVariable): + """ + Информационное поле для закладки + """ + type = "label" + + def init(self): + self.label = _("Group") + + def get(self): + return self.Get('ur_unix_group_name') + + def uncompatible(self): + return self.label + + +class VariableUrUnixGroupNameExists(UnixUserHelper, UnixGroupHelper, Variable): + """ + Название редактируемой/просматриваемой группы + """ + type = "choice" + base_dn = "{ld_unix_groups_dn}" + search_filter = '(cn={value})' + guitype = "hidden" + + untrusted = True + opt = ("ur_unix_group_name_exists",) + metavalue = "GROUP" + + def init(self): + self.label = _("Group") + self.help = _("set the group name") + + def choice(self): + if self.Get('cl_unix_action') == Actions.GroupDel: + primary_groups = map(int, self.get_primary_gids()) + return [(group.group_name, + "%s (%s)" % (group.group_name, group.comment)) + for group in self.iterate_ldap_group("cn=*") + if group.gid not in primary_groups] + else: + return [(group.group_name, + "%s (%s)" % (group.group_name, group.comment)) + for group in self.iterate_ldap_group("cn=*")] + + def raiseWrongChoice(self, name, choiceVal, value, error): + if self.Get('cl_unix_action') == Actions.GroupDel: + group = self.search_ldap_group_name(value) + if group: + users = ", ".join(user.username for user in + self.iterate_ldap_user( + "gidNumber=%d" % group.gid)) + if users: + raise VariableError( + _("Group {group} is primary group for users {users}" + ).format(group=value, users=users)) + if not value: + raise VariableError(_("Choice group")) + raise VariableError(_("Group %s not found") % value) + + +class VariableUrUnixGroupComment(UnixGroupHelper, UnixActionHelper, Variable): + """ + Комментарий к группе + """ + value_format = "{ldap.ld_base_root.capitalize()} group" + opt = ('-c', '--comment') + metavalue = "COMMENT" + + def init(self): + self.label = _("Comment") + self.help = _("set comment of the group") + + def get_new(self): + return self._value_formatter.format(self.value_format, self.Get) + + def get_exists(self): + return self.Get('ur_unix_group_comment_exists') + + +class VariableUrUnixGroupCount(UnixGroupHelper, UnixActionHelper, + ReadonlyVariable): + """ + Количество групп + """ + type = "int" + + def get_exists(self): + return len(self.ldap_group_list()) + + +class VariableUrUnixGroupCommentExists(UnixGroupHelper, UnixActionHelper, + Variable): + """ + Комментарий к группе + """ + + def get_exists(self): + group_name = self.Get('ur_unix_group_name') + if group_name: + group = self.search_ldap_group_name(group_name) + if group: + return group.comment + return "" + + +class VariableUrUnixGroupId(LdapSearchHelper, UnixActionHelper, Variable): + """ + ID группы + """ + base_dn = "{ld_unix_groups_dn}" + search_filter = '(gidNumber={value})' + type = "int" + opt = ('-g', '--gid') + metavalue = "GID" + + def init(self): + self.label = _("Group ID") + self.help = _("set the group ID") + + def get_new(self): + return self.Get('ur_unix_next_gid') + + def get_exists(self): + return self.Get('ur_unix_group_id_exists') + + def check_new(self, value): + if not value: + raise VariableError(_("You should specify group ID")) + if self.check_name(value): + raise VariableError(_("Group ID already exists")) + + def check_exists(self, value): + old_value = self.Get('ur_unix_group_id_exists') + if not value: + raise VariableError(_("You should specify group ID")) + if value != old_value and self.check_name(value): + raise VariableError(_("Group ID already exists")) + + +class VariableUrUnixGroupIdExists(UnixGroupHelper, LdapSearchHelper, + UnixActionHelper, Variable): + """ + ID группы + """ + type = "int" + + def get_exists(self): + group_name = self.Get('ur_unix_group_name') + if group_name: + group = self.search_ldap_group_name(group_name) + if group: + return str(group.gid) + return "" + + +class VariableUrUnixNextGid(LdapMaxHelper, ReadonlyVariable): + """ + Следующий свободный Uid + """ + base_dn = "{ld_unix_groups_dn}" + search_filter = "cn=*" + attr = "gidNumber" + + def get(self): + value = self.get_max() + if value is None: + return self.Get('ur_unix_min_gid') + else: + return str(value + 1) + + +class VariableUrUnixMinGid(Variable): + """ + Минимальный uid + """ + type = "int" + value = "10000" + + +class VariableUrUnixGroupUsers(UnixGroupHelper, ReadonlyVariable): + """ + Текущий список пользователей в группе + """ + type = "list" + + def init(self): + self.label = _("Users") + + def get(self): + group_name = self.Get('ur_unix_group_name') + if group_name: + group = self.search_ldap_group_name(group_name) + if group: + return group.user_list + return [] + + +class VariableUrUnixGroupUsersAdd(UnixUserHelper, Variable): + """ + Пользователи добавляемые в группу + """ + type = "choiceedit-list" + opt = ("-a", "--add") + value = [] + metavalue = "USERS" + + def init(self): + self.label = _("Include in group") + self.help = _("add members") + + def choice(self): + if self.Get('ur_unix_group_name'): + exists_users = self.Get('ur_unix_group_users') + return (x for x in self.ldap_user_list() if + x[0] not in exists_users) + return [] + + def get(self): + exists_users = set(self.Get('ur_unix_group_users')) + replace_users = set(self.Get('ur_unix_group_users_replace')) + return sorted(list(replace_users - exists_users)) + + def check(self, value): + exists_users = self.Get('ur_unix_group_users') + replace_users = self.Get('ur_unix_group_users_replace') + if set(exists_users) != set(replace_users): + raise VariableError(_( + "Appending users to group unavailable " + "with the replace user using")) + group = self.Get('ur_unix_group_name') + users = self.ldap_user_names() + failed = [x for x in value if x not in users] + if failed: + raise VariableError( + _("Wrong users {users}").format( + users=", ".join(failed))) + already_exists = [x for x in value if x in exists_users] + if already_exists: + raise VariableError( + _("Users {users} already exist in group {group}").format( + users=", ".join(already_exists), group=group)) + + +class VariableUrUnixGroupUsersReplace(UnixUserHelper, UnixActionHelper, + Variable): + """ + Замена всех пользователей в группе + """ + type = "choiceedit-list" + opt = ("-U ", "--users") + value = [] + metavalue = "USERS" + + def init(self): + self.label = _("Users") + self.help = _("new user list of group") + + def get_exists(self): + return list(sorted(self.Get('ur_unix_group_users'))) + + def choice_exists(self): + return self.ldap_user_list() + + def check_exists(self, value): + users = self.ldap_user_names() + failed = [x for x in value if x not in users] + if failed: + raise VariableError( + _("Wrong users {users}").format( + users=", ".join(failed))) + + +class VariableUrUnixGroupUsersDel(UnixUserHelper, Variable): + """ + Пользователи добавляемые в группу + """ + type = "choiceedit-list" + opt = ("-r", "--remove") + value = [] + metavalue = "USERS" + + def init(self): + self.label = _("Exclude from groups") + self.help = _("remove members") + + def choice(self): + exists_users = self.Get('ur_unix_group_users') + return (x for x in self.ldap_user_list() if + x[0] in exists_users) + + def get(self): + exists_users = set(self.Get('ur_unix_group_users')) + replace_users = set(self.Get('ur_unix_group_users_replace')) + return sorted(list(exists_users - replace_users)) + + def check(self, value): + exists_users = self.Get('ur_unix_group_users') + replace_users = self.Get('ur_unix_group_users_replace') + if set(exists_users) != set(replace_users): + raise VariableError(_( + "Removing users from group unavailable " + "with the replace user using")) + if not exists_users and value: + raise VariableError(_("Group has not members")) + + group = self.Get('ur_unix_group_name') + users = self.ldap_user_names() + failed = [x for x in value if x not in users] + if failed: + raise VariableError( + _("Wrong users {users}").format( + users=", ".join(failed))) + not_exists = [x for x in value if x not in exists_users] + if not_exists: + raise VariableError( + _("Users {users} are not exist in group {group}").format( + users=", ".join(not_exists), group=group)) + + def humanReadable(self): + if not self.Get(): + return _("Not change") + + +class VariableUrUnixGroupNewname(UnixGroupHelper, Variable): + opt = ("-n", "--new-name") + value = "" + metavalue = "NEW_GROUP" + + def init(self): + self.label = _("Group name") + self.help = _("use NEW_GROUP name by GROUP") + + def get(self): + return self.Get('ur_unix_group_name') + + def check(self, value): + if value == self.Get('ur_unix_group_name'): + return + # raise VariableError(_("The new group name is the same as the old")) + if self.search_ldap_group_name(value): + raise VariableError( + _("Group {name} already exists").format(name=value)) + + def humanReadable(self): + value = self.Get() + if not value: + return _("Not change") + return value + + +class VariableUrUnixGroupShow(UnixGroupHelper, UnixActionHelper, Variable): + """ + Группа + """ + type = "choice" + opt = ["-G", "--group"] + metavalue = "GROUP" + + def init(self): + self.label = _("Group name") + self.help = _("show group") + + def get(self): + return "all" + + def choice_exists(self): + return ([("all", _("All"))] + + self.ldap_group_list()) + + +class VariableClUnixGroupAliases(ReadonlyVariable): + """ + Алиасы для переменных + """ + type = "table" + value = [('name', 'ur_unix_group_name'), + ('id', 'ur_unix_group_id'), + ('comment', 'ur_unix_group_comment'), + ('users', 'ur_unix_group_users')] + + +class VariableClUnixGroupFields(Variable): + """ + Список полей для вывода данных группы + """ + type = "choice-list" + element = "selecttable" + opt = ["--fields"] + metavalue = "FIELDS" + + def init(self): + self.label = _("Fields") + self.help = _("fields for display") + + def choice(self): + data = self.Get('cl_unix_group_aliases') + return [(x, self.parent.getInfo(y).label) for x, y in data] + + def get(self): + return [x for x, y in self.Get('cl_unix_group_aliases')] + + +class VariableClUnixGroupShowFields(ReadonlyVariable): + """ + Список переменных полей при отображении списка групп + """ + type = "list" + + def get(self): + mapping = dict(self.Get('cl_unix_group_aliases')) + return [mapping[x] for x in self.Get('cl_unix_group_fields')] diff --git a/pym/unix/variables/unix.py b/pym/unix/variables/unix.py index 0e8abf1..4df2232 100644 --- a/pym/unix/variables/unix.py +++ b/pym/unix/variables/unix.py @@ -15,18 +15,9 @@ # limitations under the License. import sys -from os import path -from calculate.lib.cl_ldap import LDAPConnectError -from calculate.lib.datavars import (ReadonlyVariable, Variable, - VariableError, PasswordError) +from calculate.lib.datavars import (ReadonlyVariable, Variable) from calculate.ldap.variables.helpers import (HashHelper, RandomPasswordHelper, - ServerEnvHelper, LdapSearchHelper, - LdapMaxHelper) -from calculate.unix.variables.helpers import (UnixUserHelper, UnixGroupHelper, - ExistsUserHelper, - ShowFieldsHelper, - FieldsHelper, UnixActionHelper) -from .action import Actions + ServerEnvHelper) _ = lambda x: x from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate) @@ -92,1108 +83,3 @@ class VariableLdUnixPw(ServerEnvHelper, RandomPasswordHelper, Variable): return "test22" return RandomPasswordHelper.get(self) - -class VariableUrUnixLogin(UnixUserHelper, UnixActionHelper, Variable): - """ - Логин настраиваемого пользователя - """ - untrusted = True - opt = ("ur_unix_login",) - metavalue = "USER" - - def init(self): - self.label = _("Login") - self.help = _("set user login") - - def get_new(self): - return "" - - def get_exists(self): - return self.Get('ur_unix_login_exists') - - def check_new(self, value): - if not value: - raise VariableError(_("You should specify login")) - if self.search_ldap_user_name(value): - raise VariableError(_("User %s already exists" % value)) - if self.search_system_user_name(value): - raise VariableError( - _("User %s already exists in /etc/passwd") % value) - - -class VariableUrUnixLoginExists(UnixUserHelper, UnixActionHelper, Variable): - """ - Логин настраиваемого пользователя - """ - type = "choice" - opt = ("ur_unix_login_exists",) - metavalue = "USER" - untrusted = True - guitype = "readonly" - - def init(self): - self.label = _("Login") - self.help = _("set user login") - - def get_new(self): - return "" - - def get_exists(self): - return "" - - def choice_exists(self): - return ((user.username, - "%s (%s)" % (user.username, user.comment)) - for user in self.iterate_ldap_user("uid=*")) - - def raiseWrongChoice(self, name, choiceVal, value, error): - if not value: - raise VariableError(_("Please specify user login")) - else: - raise VariableError(_("%s user not found") % value) - - -class VariableUrUnixGroupName(LdapSearchHelper, UnixActionHelper, Variable): - """ - Логин настраиваемого пользователя - """ - base_dn = "{ld_unix_groups_dn}" - search_filter = '(cn={value})' - - untrusted = True - opt = ("ur_unix_group_name",) - metavalue = "GROUP" - - def init(self): - self.label = _("Group") - self.help = _("set the group name") - - def get_new(self): - return "" - - def get_exists(self): - return self.Get('ur_unix_group_name_exists') - - def check(self, value): - if not value: - raise VariableError(_("You should specify group name")) - if self.check_name(value): - raise VariableError(_("Group name already exists")) - - -class VariableUrUnixGroupLabel(ReadonlyVariable): - """ - Информационное поле для закладки - """ - type = "label" - - def init(self): - self.label = _("Group") - - def get(self): - return self.Get('ur_unix_group_name') - - def uncompatible(self): - return self.label - - -class VariableUrUnixGroupNameExists(UnixUserHelper, UnixGroupHelper, Variable): - """ - Логин настраиваемого пользователя - """ - type = "choice" - base_dn = "{ld_unix_groups_dn}" - search_filter = '(cn={value})' - guitype = "hidden" - - untrusted = True - opt = ("ur_unix_group_name_exists",) - metavalue = "GROUP" - - def init(self): - self.label = _("Group") - self.help = _("set the group name") - - def choice(self): - if self.Get('cl_unix_action') == Actions.GroupDel: - primary_groups = map(int, self.get_primary_gids()) - return [(group.group_name, - "%s (%s)" % (group.group_name, group.comment)) - for group in self.iterate_ldap_group("cn=*") - if group.gid not in primary_groups] - else: - return [(group.group_name, - "%s (%s)" % (group.group_name, group.comment)) - for group in self.iterate_ldap_group("cn=*")] - - def raiseWrongChoice(self, name, choiceVal, value, error): - if self.Get('cl_unix_action') == Actions.GroupDel: - group = self.search_ldap_group_name(value) - if group: - users = ", ".join(user.username for user in - self.iterate_ldap_user( - "gidNumber=%d" % group.gid)) - if users: - raise VariableError( - _("Group {group} is primary group for users {users}" - ).format(group=value, users=users)) - if not value: - raise VariableError(_("Choice group")) - raise VariableError(_("Group %s not found") % value) - - -class VariableUrUnixBaseDir(Variable): - """ - Базовая директория для нового пользователя - """ - value = "/home" - opt = ('-b', '--base-dir') - metavalue = "BASE_DIR" - - def init(self): - self.label = _("Base directory") - self.help = _("base directory for the home directory of new account") - - -class VariableUrUnixComment(ExistsUserHelper, UnixActionHelper, Variable): - """ - Описание учётной записи - """ - attribute = "comment" - value_format = "{ldap.ld_base_root.capitalize()} user" - opt = ('-c', '--comment') - metavalue = "COMMENT" - - def init(self): - self.label = _("Comment") - self.help = _("set comment of the account") - - def get_new(self): - return self._value_formatter.format(self.value_format, self.Get) - - -class VariableUrUnixGroupComment(UnixGroupHelper, UnixActionHelper, Variable): - """ - Комментарий к группе - """ - value_format = "{ldap.ld_base_root.capitalize()} group" - opt = ('-c', '--comment') - metavalue = "COMMENT" - - def init(self): - self.label = _("Comment") - self.help = _("set comment of the group") - - def get_new(self): - return self._value_formatter.format(self.value_format, self.Get) - - def get_exists(self): - return self.Get('ur_unix_group_comment_exists') - - -class VariableUrUnixGroupCount(UnixGroupHelper, UnixActionHelper, - ReadonlyVariable): - """ - Количество групп - """ - type = "int" - - def get_exists(self): - return len(self.ldap_group_list()) - - -class VariableUrUnixGroupCommentExists(UnixGroupHelper, UnixActionHelper, - Variable): - """ - Комментарий к группе - """ - - def get_exists(self): - group_name = self.Get('ur_unix_group_name') - if group_name: - group = self.search_ldap_group_name(group_name) - if group: - return group.comment - return "" - - -class VariableUrUnixHomePath(ExistsUserHelper, UnixActionHelper, Variable): - """ - Путь до домашней директории - """ - value_format = "{unix.ur_unix_base_dir}/{unix.ur_unix_login}" - opt = ('-d', '--home-dir') - metavalue = "HOME_DIR" - check_after = ["ur_unix_login"] - - def init(self): - self.label = _("Home directory") - self.help = _("set home directory of the account") - - def get_exists(self): - return self.Get('ur_unix_home_path_exists') - - def get_new(self): - return self._value_formatter.format(self.value_format, self.Get) - - def check_exists(self, value): - if "," in value: - raise VariableError(_("Wrong home directory")) - if not value.startswith('/'): - raise VariableError(_("Home directory path must be absolutly")) - - -class VariableUrUnixHomePathExists(ExistsUserHelper, UnixActionHelper, - ReadonlyVariable): - """ - Путь до домашней директории - """ - attribute = "homedir" - - -class VariableUrUnixHomePathMove(Variable): - """ - Перемещать домашнуюю пользовательскую директорию - """ - type = "bool" - opt = ('-m', '--move-home') - value = "off" - - def init(self): - self.label = _("Move home directory") - self.help = _("move contents of the home directory to the new location") - - def check_on(self): - new_path = self.Get('ur_unix_home_path') - old_path = self.Get('ur_unix_home_path_exists') - if new_path == old_path: - raise VariableError(_("You should change home directory")) - if path.exists(new_path): - raise VariableError( - _("New home directory %s exists") % new_path) - if not path.exists(old_path): - raise VariableError( - _("Previous home directory %s not found") % old_path) - - -class VariableUrUnixPrimaryGroup(ExistsUserHelper, UnixGroupHelper, - UnixActionHelper, Variable): - """ - ID основной группы - """ - attribute = "gid" - type = "choiceedit" - opt = ('-g', '--gid') - metavalue = "GROUP" - - default_value = "default" - - def init(self): - self.label = _("Primary group") - self.help = _("set name or ID of primary group of the account " - "('default' value for create default group)") - - def get_new(self): - return self.default_value - - def get_exists(self): - value = str(ExistsUserHelper.get_exists(self)) - if value: - return str(self.gid_to_name(value)) - - def set(self, value): - if self._new(self.Get('cl_unix_action')): - if value == self.Get('ur_unix_login'): - return self.default_value - return str(self.gid_to_name(value)) - - def choice_new(self): - return ([(self.default_value, _("Default"))] - + self.ldap_group_list()) - - def choice_exists(self): - return self.ldap_group_list() - - def check_new(self, value): - if not value: - raise VariableError(_("You should specify primary group ID")) - # if value != "auto": - if value != self.default_value: - self.check_group(value) - - def check_exists(self, value): - if not value: - raise VariableError(_("You should specify primary group ID")) - # if value != "auto": - if value: - self.check_group(value) - - def raiseWrongChoice(self, name, choiceVal, value, error): - raise VariableError(_("Group %s not found") % value) - - -class VariableUrUnixGid(UnixGroupHelper, ReadonlyVariable): - """ - ID основной группы пользователя - """ - type = "int" - - def get(self): - group_name = self.Get('ur_unix_primary_group') - print group_name - if (group_name and - group_name != VariableUrUnixPrimaryGroup.default_value): - ldap_group = self.search_ldap_group_name(group_name) - return str(ldap_group.gid) - else: - return self.Get('ur_unix_next_gid') - - -class VariableUrUnixGroupId(LdapSearchHelper, UnixActionHelper, Variable): - """ - ID группы - """ - base_dn = "{ld_unix_groups_dn}" - search_filter = '(gidNumber={value})' - type = "int" - opt = ('-g', '--gid') - metavalue = "GID" - - def init(self): - self.label = _("Group ID") - self.help = _("set the group ID") - - def get_new(self): - return self.Get('ur_unix_next_gid') - - def get_exists(self): - return self.Get('ur_unix_group_id_exists') - - def check_new(self, value): - if not value: - raise VariableError(_("You should specify group ID")) - if self.check_name(value): - raise VariableError(_("Group ID already exists")) - - def check_exists(self, value): - old_value = self.Get('ur_unix_group_id_exists') - if not value: - raise VariableError(_("You should specify group ID")) - if value != old_value and self.check_name(value): - raise VariableError(_("Group ID already exists")) - - -class VariableUrUnixGroupIdExists(UnixGroupHelper, LdapSearchHelper, - UnixActionHelper, Variable): - """ - ID группы - """ - type = "int" - - def get_exists(self): - group_name = self.Get('ur_unix_group_name') - if group_name: - group = self.search_ldap_group_name(group_name) - if group: - return str(group.gid) - return "" - - -class VariableUrUnixUid(UnixUserHelper, UnixActionHelper, Variable): - """ - UID пользователя - """ - type = "int" - opt = ('-u', '--uid') - metavalue = "UID" - value = "" - - def init(self): - self.label = _("User ID") - self.help = _("set user ID of the account") - - def get_new(self): - return self.Get('ur_unix_next_uid') - - def get_exists(self): - login = self.Get('ur_unix_login') - if login: - return str(self.search_ldap_user_name(login).uid) - - def check_new(self, value): - user = self.search_ldap_user_id(value) - if user: - raise VariableError(_("Uid %s is used by user %s") - % (user.uid, user.username)) - user = self.search_system_user_id(value) - if user: - raise VariableError(_("Uid %s is used by system user %s") - % (user.uid, user.username)) - - -class VariableUrUnixGroups(UnixGroupHelper, UnixActionHelper, Variable): - """ - Список груп - """ - type = "choiceedit-list" - opt = ("-G", "--groups") - metavalue = "GROUPS" - value = [] - - def init(self): - self.label = _("Supplimentary groups") - self.help = _("set list of supplementary groups of the account") - - def set(self, value): - return map(self.gid_to_name, value) - - def get_exists(self): - return self.Get('ur_unix_groups_exists') - - def choice(self): - return self.ldap_group_list() - - def check(self, value): - for group in value: - self.check_group(group) - - -class VariableUrUnixGroupsExists(UnixGroupHelper, UnixActionHelper, Variable): - """ - Список груп - """ - type = "list" - value = [] - - #def get_bylogin(self, login, obj): - # return [x.group_name for x in - # self.iterate_ldap_group("memberUid=%s" % login)] - - def get_exists(self): - login = self.Get('ur_unix_login') - if login: - return [x.group_name for x in - self.iterate_ldap_group("memberUid=%s" % login)] - return [] - - -class VariableUrUnixGroupsAdd(UnixGroupHelper, UnixActionHelper, Variable): - """ - Список групп в которые необходимо добавить пользователя - """ - type = "choiceedit-list" - opt = ("-a", "--append") - metavalue = "GROUPS" - value = [] - - def init(self): - self.label = _("Include to groups") - self.help = _("include user into groups") - - def set(self, value): - return map(self.gid_to_name, value) - - def get_exists(self): - exists_groups = set(self.Get('ur_unix_groups_exists')) - replace_group = set(self.Get('ur_unix_groups')) - return sorted(list(replace_group - exists_groups)) - - def choice_exists(self): - login = self.Get('ur_unix_login') - if login: - exists_groups = self.Get('ur_unix_groups_exists') - return (x for x in self.ldap_group_list() - if x[0] not in exists_groups) - return [] - - def check_exists(self, value): - exists_groups = self.Get('ur_unix_groups_exists') - replace_groups = self.Get('ur_unix_groups') - if set(exists_groups) != set(replace_groups): - raise VariableError(_( - "Appending user to groups unavailable " - "with the replace groups using")) - login = self.Get('ur_unix_login') - groups = self.ldap_group_names() - failed = [x for x in value if x not in groups] - if failed: - raise VariableError( - _("Wrong groups {groups}").format( - groups=", ".join(failed))) - self.check_special(value, exists_groups, login) - - def check_special(self, value, exists_groups, login): - already_exists = [x for x in value if x in exists_groups] - if already_exists: - raise VariableError( - _("User {user} already exist in groups {groups}").format( - groups=", ".join(already_exists), user=login)) - - def humanReadable(self): - if not self.Get(): - return _("Not change") - - -class VariableUrUnixGroupsDel(VariableUrUnixGroupsAdd): - """ - Список групп из которых необходимо исключить пользователя - """ - type = "choiceedit-list" - opt = ("-r", "--remove") - metavalue = "GROUPS" - value = [] - - def init(self): - self.label = _("Exclude from groups") - self.help = _("exclude user from groups") - - def get_exists(self): - exists_groups = set(self.Get('ur_unix_groups_exists')) - replace_groups = set(self.Get('ur_unix_groups')) - return sorted(list(exists_groups - replace_groups)) - - def choice_exists(self): - login = self.Get('ur_unix_login') - if login: - exists_groups = self.Get('ur_unix_groups_exists') - return (x for x in self.ldap_group_list() - if x[0] in exists_groups) - return [] - - def check_special(self, value, exists_groups, login): - not_exists = [x for x in value if x not in exists_groups] - if not_exists: - raise VariableError( - _("User {user} is not exist in groups {groups}").format( - groups=", ".join(not_exists), user=login)) - - -class VariableUrUnixSkel(Variable): - """ - Skel директория - """ - opt = ("-k", "--skel") - metavalue = "SKEL_DIR" - value = "/etc/skel" - - def init(self): - self.label = _("Skeleton directory") - self.help = _("set skeletion directory for new account") - - -class VariableUrUnixCreateHomeSet(Variable): - """ - Создавать домашнюю директорию пользователю - """ - type = "bool" - opt = ("-m", "--create-home") - value = "off" - check_after = ["ur_unix_home_path"] - - def init(self): - self.label = _("Create home directory") - self.help = _("create the user's home directory") - - def check_on(self): - home_path = self.Get('ur_unix_home_path') - if path.exists(home_path): - raise VariableError( - _("Home directory %s already exists") % home_path) - - -class VariableUrUnixPw(Variable): - """ - Пароль пользователя - """ - type = "password" - opt = ("-p", "--password") - value = "" - untrusted = True - metavalue = "PASSWORD" - - def init(self): - self.label = _("Password") - self.help = _("set user password") - - def check(self, value): - delete_pw = self.GetBool('ur_unix_pw_delete_set') - change_lock = (self.GetBool('ur_unix_lock_set') != - self.GetBool('ur_unix_lock_exists_set')) - if (self.Get('cl_unix_action') == Actions.Passwd and - not delete_pw and not change_lock and not value): - raise PasswordError(_("Specify user password")) - - -class VariableUrUnixPwSet(UnixActionHelper, UnixUserHelper, ReadonlyVariable): - """ - Указан ли пароль у пользователя - """ - type = "bool" - - def init(self): - self.label = _("Password") - - def get_exists(self): - username = self.Get('ur_unix_login') - pw = self.get_password_hash(username) - if pw and pw != self.DeletedPassword: - return "on" - else: - return "off" - - -class VariableUrUnixPwDeleteSet(Variable): - """ - Удалить пароль пользователя - """ - type = "bool" - value = "off" - - opt = ("-d", "--delete") - - def init(self): - self.label = _("Remove user password") - self.help = _("delete the password for the named account") - - -class VariableUrUnixHash(HashHelper, ReadonlyVariable): - """ - Хэш пароля - """ - source = "unix.ur_unix_pw" - - -class VariableUrUnixUserObject(UnixUserHelper, UnixActionHelper, - ReadonlyVariable): - """ - Объект данных пользователя - """ - - def get_exists(self): - login = self.Get('ur_unix_login') - if login: - return self.search_ldap_user_name(login) or "" - return "" - - -class VariableUrUnixShell(ExistsUserHelper, UnixActionHelper, Variable): - """ - Командная оболочка по умолчанию для пользователя - """ - attribute = "shell" - opt = ("-s", "--shell") - metavalue = "SHELL" - - def init(self): - self.label = _("Shell") - self.help = _("login shell of the account") - - def get_new(self): - return "/bin/bash" - - -class VariableUrUnixVisibleSet(ExistsUserHelper, UnixActionHelper, Variable): - """ - Виден ли пользователь - """ - attribute = "visible" - type = "bool" - opt = ("-v", "--visible") - - def init(self): - self.label = _("Visible") - self.help = _("set visible of the account") - - def get_new(self): - return "on" - - -class VariableUrUnixLockSet(ExistsUserHelper, UnixActionHelper, Variable): - """ - Виден ли пользователь - """ - attribute = "lock" - type = "bool" - opt = ("-l", "--lock") - value = "off" - - def init(self): - self.label = _("Locked") - self.help = _("lock the account") - - -class VariableUrUnixLockExistsSet(ExistsUserHelper, UnixActionHelper, Variable): - """ - Виден ли пользователь - """ - type = "bool" - attribute = "lock" - value = "off" - - -class VariableUrUnixVisibleFlag(UnixUserHelper, ReadonlyVariable): - """ - Значение используемое для шаблона - """ - - def get(self): - return self.visible_to_flag(self.GetBool('ur_unix_visible_set')) - - -class VariableUrUnixLockFlag(UnixUserHelper, ReadonlyVariable): - """ - Значение используемое для шаблона - """ - - def get(self): - return self.lock_to_flag(self.GetBool('ur_unix_lock_set')) - - -class VariableUrUnixNextUid(LdapMaxHelper, ReadonlyVariable): - """ - Следующий свободный Uid - """ - base_dn = "{ld_unix_users_dn}" - search_filter = "uid=*" - attr = "uidNumber" - - def get(self): - value = self.get_max() - if value is None: - return self.Get('ur_unix_min_uid') - else: - return str(value + 1) - - -class VariableUrUnixNextGid(LdapMaxHelper, ReadonlyVariable): - """ - Следующий свободный Uid - """ - base_dn = "{ld_unix_groups_dn}" - search_filter = "cn=*" - attr = "gidNumber" - - def get(self): - value = self.get_max() - if value is None: - return self.Get('ur_unix_min_gid') - else: - return str(value + 1) - - -class VariableUrUnixMinUid(Variable): - """ - Минимальный uid - """ - type = "int" - value = "10000" - - -class VariableUrUnixMinGid(Variable): - """ - Минимальный uid - """ - type = "int" - value = "10000" - - -class VariableUrUnixGroupUsers(UnixGroupHelper, ReadonlyVariable): - """ - Текущий список пользователей в группе - """ - type = "list" - - def init(self): - self.label = _("Users") - - def get(self): - group_name = self.Get('ur_unix_group_name') - if group_name: - group = self.search_ldap_group_name(group_name) - if group: - return group.user_list - return [] - - -class VariableUrUnixGroupUsersAdd(UnixUserHelper, Variable): - """ - Пользователи добавляемые в группу - """ - type = "choiceedit-list" - opt = ("-a", "--add") - value = [] - metavalue = "USERS" - - def init(self): - self.label = _("Include in group") - self.help = _("add members") - - def choice(self): - if self.Get('ur_unix_group_name'): - exists_users = self.Get('ur_unix_group_users') - return (x for x in self.ldap_user_list() if - x[0] not in exists_users) - return [] - - def get(self): - exists_users = set(self.Get('ur_unix_group_users')) - replace_users = set(self.Get('ur_unix_group_users_replace')) - return sorted(list(replace_users - exists_users)) - - def check(self, value): - exists_users = self.Get('ur_unix_group_users') - replace_users = self.Get('ur_unix_group_users_replace') - if set(exists_users) != set(replace_users): - raise VariableError(_( - "Appending users to group unavailable " - "with the replace user using")) - group = self.Get('ur_unix_group_name') - users = self.ldap_user_names() - failed = [x for x in value if x not in users] - if failed: - raise VariableError( - _("Wrong users {users}").format( - users=", ".join(failed))) - already_exists = [x for x in value if x in exists_users] - if already_exists: - raise VariableError( - _("Users {users} already exist in group {group}").format( - users=", ".join(already_exists), group=group)) - - -class VariableUrUnixGroupUsersReplace(UnixUserHelper, UnixActionHelper, - Variable): - """ - Замена всех пользователей в группе - """ - type = "choiceedit-list" - opt = ("-U ", "--users") - value = [] - metavalue = "USERS" - - def init(self): - self.label = _("Users") - self.help = _("new user list of group") - - def get_exists(self): - return list(sorted(self.Get('ur_unix_group_users'))) - - def choice_exists(self): - return self.ldap_user_list() - - def check_exists(self, value): - users = self.ldap_user_names() - failed = [x for x in value if x not in users] - if failed: - raise VariableError( - _("Wrong users {users}").format( - users=", ".join(failed))) - - -class VariableUrUnixGroupUsersDel(UnixUserHelper, Variable): - """ - Пользователи добавляемые в группу - """ - type = "choiceedit-list" - opt = ("-r", "--remove") - value = [] - metavalue = "USERS" - - def init(self): - self.label = _("Exclude from groups") - self.help = _("remove members") - - def choice(self): - exists_users = self.Get('ur_unix_group_users') - return (x for x in self.ldap_user_list() if - x[0] in exists_users) - - def get(self): - exists_users = set(self.Get('ur_unix_group_users')) - replace_users = set(self.Get('ur_unix_group_users_replace')) - return sorted(list(exists_users - replace_users)) - - def check(self, value): - exists_users = self.Get('ur_unix_group_users') - replace_users = self.Get('ur_unix_group_users_replace') - if set(exists_users) != set(replace_users): - raise VariableError(_( - "Removing users from group unavailable " - "with the replace user using")) - if not exists_users and value: - raise VariableError(_("Group has not members")) - - group = self.Get('ur_unix_group_name') - users = self.ldap_user_names() - failed = [x for x in value if x not in users] - if failed: - raise VariableError( - _("Wrong users {users}").format( - users=", ".join(failed))) - not_exists = [x for x in value if x not in exists_users] - if not_exists: - raise VariableError( - _("Users {users} are not exist in group {group}").format( - users=", ".join(not_exists), group=group)) - - def humanReadable(self): - if not self.Get(): - return _("Not change") - - -class VariableUrUnixGroupNewname(UnixGroupHelper, Variable): - opt = ("-n", "--new-name") - value = "" - metavalue = "NEW_GROUP" - - def init(self): - self.label = _("Group name") - self.help = _("use NEW_GROUP name by GROUP") - - def get(self): - return self.Get('ur_unix_group_name') - - def check(self, value): - if value == self.Get('ur_unix_group_name'): - return - #raise VariableError(_("The new group name is the same as the old")) - if self.search_ldap_group_name(value): - raise VariableError( - _("Group {name} already exists").format(name=value)) - - def humanReadable(self): - value = self.Get() - if not value: - return _("Not change") - return value - - -class VariableUrUnixGroupShow(UnixGroupHelper, UnixActionHelper, Variable): - """ - Группа - """ - type = "choice" - opt = ["-G", "--group"] - metavalue = "GROUP" - - def init(self): - self.label = _("Group name") - self.help = _("show group") - - def get(self): - return "all" - - def choice_exists(self): - return ([("all", _("All"))] - + self.ldap_group_list()) - - -class VariableUrUnixUserShow(UnixUserHelper, UnixActionHelper, Variable): - """ - Группа - """ - type = "choice" - opt = ["-U", "--user"] - metavalue = "USER" - - def init(self): - self.label = _("login") - self.help = _("show user") - - def get(self): - return "all" - - def choice_exists(self): - try: - return ([("all", _("All"))] - + self.ldap_user_list()) - except LDAPConnectError as s: - raise VariableError(str(s)) - - -class VariableUrUnixUserCount(UnixUserHelper, UnixActionHelper, - ReadonlyVariable): - """ - Количество пользователей - """ - type = "int" - - def get_exists(self): - return len(self.ldap_user_list()) - - -class VariableClUnixGroupAliases(ReadonlyVariable): - """ - Алиасы для переменных - """ - type = "table" - value = [('name', 'ur_unix_group_name'), - ('id', 'ur_unix_group_id'), - ('comment', 'ur_unix_group_comment'), - ('users', 'ur_unix_group_users')] - - -class VariableClUnixGroupFields(Variable): - """ - Список полей для вывода данных группы - """ - type = "choice-list" - element = "selecttable" - opt = ["--fields"] - metavalue = "FIELDS" - - def init(self): - self.label = _("Fields") - self.help = _("fields for display") - - def choice(self): - data = self.Get('cl_unix_group_aliases') - return [(x, self.parent.getInfo(y).label) for x, y in data] - - def get(self): - return [x for x, y in self.Get('cl_unix_group_aliases')] - - -class VariableClUnixGroupShowFields(ReadonlyVariable): - """ - Список переменных полей при отображении списка групп - """ - type = "list" - - def get(self): - mapping = dict(self.Get('cl_unix_group_aliases')) - return [mapping[x] for x in self.Get('cl_unix_group_fields')] - - -class VariableClUnixUserAliases(ReadonlyVariable): - """ - Алиасы для переменных - """ - type = "table" - value = [ - ('login', 'ur_unix_login'), - ('uid', 'ur_unix_uid'), - ('gid', 'ur_unix_primary_group'), - ('comment', 'ur_unix_comment'), - ('lock', 'ur_unix_lock_set'), - ('visible', 'ur_unix_visible_set'), - ('groups', 'ur_unix_groups'), - ('home', 'ur_unix_home_path'), - ('shell', 'ur_unix_shell'), - ('password', 'ur_unix_pw_set'), - ] - - -class VariableClUnixUserFields(FieldsHelper, Variable): - """ - Список полей для вывода данных группы - """ - alias_variable = "cl_unix_user_aliases" - - -class VariableClUnixUserShowFields(ShowFieldsHelper, ReadonlyVariable): - """ - Список переменных полей при отображении списка групп - """ - alias_variable = "cl_unix_user_aliases" - source_variable = "cl_unix_user_fields" diff --git a/pym/unix/variables/users.py b/pym/unix/variables/users.py new file mode 100644 index 0000000..d0b7654 --- /dev/null +++ b/pym/unix/variables/users.py @@ -0,0 +1,709 @@ +# -*- coding: utf-8 -*- + +# Copyright 2016 Mir Calculate. http://www.calculate-linux.org +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +from os import path +from calculate.lib.cl_ldap import LDAPConnectError +from calculate.lib.datavars import (ReadonlyVariable, Variable, + VariableError, PasswordError) +from calculate.ldap.variables.helpers import (HashHelper, + LdapMaxHelper) +from calculate.unix.variables.helpers import (UnixUserHelper, UnixGroupHelper, + ExistsUserHelper, + ShowFieldsHelper, + FieldsHelper, UnixActionHelper) +from .action import Actions + +_ = lambda x: x +from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate) + +setLocalTranslate('cl_unix3', sys.modules[__name__]) +__ = getLazyLocalTranslate(_) + + +class VariableUrUnixLogin(UnixUserHelper, UnixActionHelper, Variable): + """ + Логин настраиваемого пользователя + """ + untrusted = True + opt = ("ur_unix_login",) + metavalue = "USER" + + def init(self): + self.label = _("Login") + self.help = _("set user login") + + def get_new(self): + return "" + + def get_exists(self): + return self.Get('ur_unix_login_exists') + + def check_new(self, value): + if not value: + raise VariableError(_("You should specify login")) + if self.search_ldap_user_name(value): + raise VariableError(_("User %s already exists" % value)) + if self.search_system_user_name(value): + raise VariableError( + _("User %s already exists in /etc/passwd") % value) + + +class VariableUrUnixLoginExists(UnixUserHelper, UnixActionHelper, Variable): + """ + Логин настраиваемого пользователя + """ + type = "choice" + opt = ("ur_unix_login_exists",) + metavalue = "USER" + untrusted = True + guitype = "readonly" + + def init(self): + self.label = _("Login") + self.help = _("set user login") + + def get_new(self): + return "" + + def get_exists(self): + return "" + + def choice_exists(self): + return ((user.username, + "%s (%s)" % (user.username, user.comment)) + for user in self.iterate_ldap_user("uid=*")) + + def raiseWrongChoice(self, name, choiceVal, value, error): + if not value: + raise VariableError(_("Please specify user login")) + else: + raise VariableError(_("%s user not found") % value) + + +class VariableUrUnixBaseDir(Variable): + """ + Базовая директория для нового пользователя + """ + value = "/home" + opt = ('-b', '--base-dir') + metavalue = "BASE_DIR" + + def init(self): + self.label = _("Base directory") + self.help = _("base directory for the home directory of new account") + + +class VariableUrUnixComment(ExistsUserHelper, UnixActionHelper, Variable): + """ + Описание учётной записи + """ + attribute = "comment" + value_format = "{ldap.ld_base_root.capitalize()} user" + opt = ('-c', '--comment') + metavalue = "COMMENT" + + def init(self): + self.label = _("Full name") + self.help = _("set fullname of the account") + + def get_new(self): + return "" + # self._value_formatter.format(self.value_format, self.Get) + +class VariableUrUnixHomePath(ExistsUserHelper, UnixActionHelper, Variable): + """ + Путь до домашней директории + """ + value_format = "{unix.ur_unix_base_dir}/{unix.ur_unix_login}" + opt = ('-d', '--home-dir') + metavalue = "HOME_DIR" + check_after = ["ur_unix_login"] + + def init(self): + self.label = _("Home directory") + self.help = _("set home directory of the account") + + def get_exists(self): + return self.Get('ur_unix_home_path_exists') + + def get_new(self): + return self._value_formatter.format(self.value_format, self.Get) + + def check_exists(self, value): + if "," in value: + raise VariableError(_("Wrong home directory")) + if not value.startswith('/'): + raise VariableError(_("Home directory path must be absolutly")) + + +class VariableUrUnixHomePathExists(ExistsUserHelper, UnixActionHelper, + ReadonlyVariable): + """ + Путь до домашней директории + """ + attribute = "homedir" + + +class VariableUrUnixHomePathMove(Variable): + """ + Перемещать домашнуюю пользовательскую директорию + """ + type = "bool" + opt = ('-m', '--move-home') + value = "off" + + def init(self): + self.label = _("Move home directory") + self.help = _("move contents of the home directory to the new location") + + def check_on(self): + new_path = self.Get('ur_unix_home_path') + old_path = self.Get('ur_unix_home_path_exists') + if new_path == old_path: + raise VariableError(_("You should change home directory")) + if path.exists(new_path): + raise VariableError( + _("New home directory %s exists") % new_path) + if not path.exists(old_path): + raise VariableError( + _("Previous home directory %s not found") % old_path) + + +class VariableUrUnixPrimaryGroup(ExistsUserHelper, UnixGroupHelper, + UnixActionHelper, Variable): + """ + ID основной группы + """ + attribute = "gid" + type = "choiceedit" + opt = ('-g', '--gid') + metavalue = "GROUP" + + domain_group = "domain" + + def init(self): + self.label = _("Primary group") + self.help = _("set name or ID of primary group of the account " + "('default' value for create default group)") + + def get_new(self): + return "domain" + + def get_exists(self): + value = str(ExistsUserHelper.get_exists(self)) + if value: + return str(self.gid_to_name(value)) + + def set(self, value): + return str(self.gid_to_name(value)) + + def choice_new(self): + return ([(self.domain_group, self.domain_group)] + + self.ldap_group_list()) + + def choice_exists(self): + return self.ldap_group_list() + + def check_new(self, value): + if not value: + raise VariableError(_("You should specify primary group ID")) + + def check_exists(self, value): + if not value: + raise VariableError(_("You should specify primary group ID")) + if value: + self.check_group(value) + + def raiseWrongChoice(self, name, choiceVal, value, error): + raise VariableError(_("Group %s not found") % value) + + +class VariableUrUnixGid(UnixGroupHelper, ReadonlyVariable): + """ + ID основной группы пользователя + """ + type = "int" + + def get(self): + group_name = self.Get('ur_unix_primary_group') + group = self.search_ldap_group_name(group_name) + if group: + return str(group.gid) + else: + return self.Get('ur_unix_next_gid') + + + +class VariableUrUnixUid(UnixUserHelper, UnixActionHelper, Variable): + """ + UID пользователя + """ + type = "int" + opt = ('-u', '--uid') + metavalue = "UID" + value = "" + + def init(self): + self.label = _("User ID") + self.help = _("set user ID of the account") + + def get_new(self): + return self.Get('ur_unix_next_uid') + + def get_exists(self): + login = self.Get('ur_unix_login') + if login: + return str(self.search_ldap_user_name(login).uid) + + def check_new(self, value): + user = self.search_ldap_user_id(value) + if user: + raise VariableError(_("Uid %s is used by user %s") + % (user.uid, user.username)) + user = self.search_system_user_id(value) + if user: + raise VariableError(_("Uid %s is used by system user %s") + % (user.uid, user.username)) + + +class VariableUrUnixGroups(UnixGroupHelper, UnixActionHelper, Variable): + """ + Список груп + """ + type = "choiceedit-list" + opt = ("-G", "--groups") + metavalue = "GROUPS" + value = [] + + def init(self): + self.label = _("Supplimentary groups") + self.help = _("set list of supplementary groups of the account") + + def set(self, value): + return map(self.gid_to_name, value) + + def get_exists(self): + return self.Get('ur_unix_groups_exists') + + def choice(self): + return self.ldap_group_list() + + def check(self, value): + for group in value: + self.check_group(group) + + +class VariableUrUnixGroupsExists(UnixGroupHelper, UnixActionHelper, Variable): + """ + Список груп + """ + type = "list" + value = [] + + # def get_bylogin(self, login, obj): + # return [x.group_name for x in + # self.iterate_ldap_group("memberUid=%s" % login)] + + def get_exists(self): + login = self.Get('ur_unix_login') + if login: + return [x.group_name for x in + self.iterate_ldap_group("memberUid=%s" % login)] + return [] + + +class VariableUrUnixGroupsAdd(UnixGroupHelper, UnixActionHelper, Variable): + """ + Список групп в которые необходимо добавить пользователя + """ + type = "choiceedit-list" + opt = ("-a", "--append") + metavalue = "GROUPS" + value = [] + + def init(self): + self.label = _("Include to groups") + self.help = _("include user into groups") + + def set(self, value): + return map(self.gid_to_name, value) + + def get_exists(self): + exists_groups = set(self.Get('ur_unix_groups_exists')) + replace_group = set(self.Get('ur_unix_groups')) + return sorted(list(replace_group - exists_groups)) + + def choice_exists(self): + login = self.Get('ur_unix_login') + if login: + exists_groups = self.Get('ur_unix_groups_exists') + return (x for x in self.ldap_group_list() + if x[0] not in exists_groups) + return [] + + def check_exists(self, value): + exists_groups = self.Get('ur_unix_groups_exists') + replace_groups = self.Get('ur_unix_groups') + if set(exists_groups) != set(replace_groups): + raise VariableError(_( + "Appending user to groups unavailable " + "with the replace groups using")) + login = self.Get('ur_unix_login') + groups = self.ldap_group_names() + failed = [x for x in value if x not in groups] + if failed: + raise VariableError( + _("Wrong groups {groups}").format( + groups=", ".join(failed))) + self.check_special(value, exists_groups, login) + + def check_special(self, value, exists_groups, login): + already_exists = [x for x in value if x in exists_groups] + if already_exists: + raise VariableError( + _("User {user} already exist in groups {groups}").format( + groups=", ".join(already_exists), user=login)) + + def humanReadable(self): + if not self.Get(): + return _("Not change") + + +class VariableUrUnixGroupsDel(VariableUrUnixGroupsAdd): + """ + Список групп из которых необходимо исключить пользователя + """ + type = "choiceedit-list" + opt = ("-r", "--remove") + metavalue = "GROUPS" + value = [] + + def init(self): + self.label = _("Exclude from groups") + self.help = _("exclude user from groups") + + def get_exists(self): + exists_groups = set(self.Get('ur_unix_groups_exists')) + replace_groups = set(self.Get('ur_unix_groups')) + return sorted(list(exists_groups - replace_groups)) + + def choice_exists(self): + login = self.Get('ur_unix_login') + if login: + exists_groups = self.Get('ur_unix_groups_exists') + return (x for x in self.ldap_group_list() + if x[0] in exists_groups) + return [] + + def check_special(self, value, exists_groups, login): + not_exists = [x for x in value if x not in exists_groups] + if not_exists: + raise VariableError( + _("User {user} is not exist in groups {groups}").format( + groups=", ".join(not_exists), user=login)) + + +class VariableUrUnixSkel(Variable): + """ + Skel директория + """ + opt = ("-k", "--skel") + metavalue = "SKEL_DIR" + value = "/etc/skel" + + def init(self): + self.label = _("Skeleton directory") + self.help = _("set skeletion directory for new account") + + +class VariableUrUnixCreateHomeSet(Variable): + """ + Создавать домашнюю директорию пользователю + """ + type = "bool" + opt = ("-m", "--create-home") + value = "off" + check_after = ["ur_unix_home_path"] + + def init(self): + self.label = _("Create home directory") + self.help = _("create the user's home directory") + + def check_on(self): + home_path = self.Get('ur_unix_home_path') + if path.exists(home_path): + raise VariableError( + _("Home directory %s already exists") % home_path) + + +class VariableUrUnixPw(Variable): + """ + Пароль пользователя + """ + type = "password" + opt = ("-p", "--password") + value = "" + untrusted = True + metavalue = "PASSWORD" + + def init(self): + self.label = _("Password") + self.help = _("set user password") + + def check(self, value): + delete_pw = self.GetBool('ur_unix_pw_delete_set') + change_lock = (self.GetBool('ur_unix_lock_set') != + self.GetBool('ur_unix_lock_exists_set')) + if (self.Get('cl_unix_action') == Actions.Passwd and + not delete_pw and not change_lock and not value): + raise PasswordError(_("Specify user password")) + + +class VariableUrUnixPwSet(UnixActionHelper, UnixUserHelper, ReadonlyVariable): + """ + Указан ли пароль у пользователя + """ + type = "bool" + + def init(self): + self.label = _("Password") + + def get_exists(self): + username = self.Get('ur_unix_login') + pw = self.get_password_hash(username) + if pw and pw != self.DeletedPassword: + return "on" + else: + return "off" + + +class VariableUrUnixPwDeleteSet(Variable): + """ + Удалить пароль пользователя + """ + type = "bool" + value = "off" + + opt = ("-d", "--delete") + + def init(self): + self.label = _("Remove user password") + self.help = _("delete the password for the named account") + + +class VariableUrUnixHash(HashHelper, ReadonlyVariable): + """ + Хэш пароля + """ + source = "unix.ur_unix_pw" + + +class VariableUrUnixUserObject(UnixUserHelper, UnixActionHelper, + ReadonlyVariable): + """ + Объект данных пользователя + """ + + def get_exists(self): + login = self.Get('ur_unix_login') + if login: + return self.search_ldap_user_name(login) or "" + return "" + + +class VariableUrUnixShell(ExistsUserHelper, UnixActionHelper, Variable): + """ + Командная оболочка по умолчанию для пользователя + """ + attribute = "shell" + opt = ("-s", "--shell") + metavalue = "SHELL" + + def init(self): + self.label = _("Shell") + self.help = _("login shell of the account") + + def get_new(self): + return "/bin/bash" + + +class VariableUrUnixVisibleSet(ExistsUserHelper, UnixActionHelper, Variable): + """ + Виден ли пользователь + """ + attribute = "visible" + type = "bool" + opt = ("-v", "--visible") + + def init(self): + self.label = _("Visible") + self.help = _("set visible of the account") + + def get_new(self): + return "on" + + +class VariableUrUnixLockSet(ExistsUserHelper, UnixActionHelper, Variable): + """ + Виден ли пользователь + """ + attribute = "lock" + type = "bool" + opt = ("-l", "--lock") + value = "off" + + def init(self): + self.label = _("Locked") + self.help = _("lock the account") + + +class VariableUrUnixLockExistsSet(ExistsUserHelper, UnixActionHelper, Variable): + """ + Виден ли пользователь + """ + type = "bool" + attribute = "lock" + value = "off" + + +class VariableUrUnixVisibleFlag(UnixUserHelper, ReadonlyVariable): + """ + Значение используемое для шаблона + """ + + def get(self): + return self.visible_to_flag(self.GetBool('ur_unix_visible_set')) + + +class VariableUrUnixLockFlag(UnixUserHelper, ReadonlyVariable): + """ + Значение используемое для шаблона + """ + + def get(self): + return self.lock_to_flag(self.GetBool('ur_unix_lock_set')) + + +class VariableUrUnixNextUid(LdapMaxHelper, ReadonlyVariable): + """ + Следующий свободный Uid + """ + base_dn = "{ld_unix_users_dn}" + search_filter = "uid=*" + attr = "uidNumber" + + def get(self): + value = self.get_max() + if value is None: + return self.Get('ur_unix_min_uid') + else: + return str(value + 1) + + +class VariableUrUnixMinUid(Variable): + """ + Минимальный uid + """ + type = "int" + value = "10000" + + +class VariableUrUnixUserShow(UnixUserHelper, UnixActionHelper, Variable): + """ + Группа + """ + type = "choiceedit" + opt = ["-U", "--user"] + metavalue = "USER" + + def init(self): + self.label = _("login") + self.help = _("show user (support regular expressions)") + + def get(self): + return "*" + + def choice_exists(self): + try: + return ([("*", _("*"))] + + self.ldap_user_list()) + except LDAPConnectError as s: + raise VariableError(str(s)) + + def check_new(self, value): + if not value: + raise VariableError(_("Please specify user")) + if "*" not in value: + if not self.search_ldap_user_name(value): + raise VariableError(_("%s user not found") % value) + + +class VariableUrUnixUserCount(UnixUserHelper, UnixActionHelper, + ReadonlyVariable): + """ + Количество пользователей + """ + type = "int" + + def get_exists(self): + return len(self.ldap_user_list()) + + +class VariableClUnixUserAliases(ReadonlyVariable): + """ + Алиасы для переменных + """ + type = "table" + value = [ + ('login', 'ur_unix_login'), + ('uid', 'ur_unix_uid'), + ('gid', 'ur_unix_primary_group'), + ('comment', 'ur_unix_comment'), + ('lock', 'ur_unix_lock_set'), + ('visible', 'ur_unix_visible_set'), + ('groups', 'ur_unix_groups'), + ('home', 'ur_unix_home_path'), + ('shell', 'ur_unix_shell'), + ('password', 'ur_unix_pw_set'), + ] + + +class VariableClUnixUserFields(FieldsHelper, Variable): + """ + Список полей для вывода данных группы + """ + alias_variable = "cl_unix_user_aliases" + + +class VariableClUnixUserShowFields(ShowFieldsHelper, ReadonlyVariable): + """ + Список переменных полей при отображении списка групп + """ + alias_variable = "cl_unix_user_aliases" + source_variable = "cl_unix_user_fields" + + +class VariableClUnixCreateGroupSet(UnixGroupHelper, ReadonlyVariable): + """ + Нужно ли создавать primary группу или она уже существует + """ + + def get(self): + group_name = self.Get('ur_unix_primary_group') + if self.search_ldap_group("cn={0}".format(group_name)): + return "off" + return "on" diff --git a/pym/unix/wsdl_unix.py b/pym/unix/wsdl_unix.py index a5a58b1..7622ed6 100644 --- a/pym/unix/wsdl_unix.py +++ b/pym/unix/wsdl_unix.py @@ -102,14 +102,12 @@ class Wsdl(WsdlBase): { # идентификатор метода 'method_name': Unix.Method.UserAdd, - # категория метода - 'category': __('Old Unix'), # заголовок метода 'title': __("Add the User"), # иконка для графической консоли 'image': 'setup', # метод присутствует в графической консоли - 'gui': False, + 'gui': True, # консольная команда 'command': 'cl-unix-useradd', # права для запуска метода @@ -155,6 +153,7 @@ class Wsdl(WsdlBase): next_label=_("Perform") ), ], + 'depends': [Unix.Method.Setup], }, # # Добавить группу @@ -162,14 +161,12 @@ class Wsdl(WsdlBase): { # идентификатор метода 'method_name': Unix.Method.GroupAdd, - # категория метода - 'category': __('Old Unix'), # заголовок метода 'title': __("Add the Group"), # иконка для графической консоли 'image': 'setup', # метод присутствует в графической консоли - 'gui': False, + 'gui': True, # консольная команда 'command': 'cl-unix-groupadd', # права для запуска метода @@ -207,6 +204,7 @@ class Wsdl(WsdlBase): next_label=_("Perform") ), ], + 'depends': [Unix.Method.Setup], }, # # Изменить параметры группы @@ -214,14 +212,12 @@ class Wsdl(WsdlBase): { # идентификатор метода 'method_name': Unix.Method.GroupMod, - # категория метода - 'category': __('Old Unix'), # заголовок метода 'title': __("Modify the Group"), # иконка для графической консоли 'image': 'setup', # метод присутствует в графической консоли - 'gui': False, + 'gui': True, # консольная команда 'command': 'cl-unix-groupmod', # права для запуска метода @@ -282,6 +278,7 @@ class Wsdl(WsdlBase): 'ur_unix_group_users_add', 'ur_unix_group_users_del',) }, + 'depends': [Unix.Method.Setup], 'brief': {'next': __("Perform"), 'name': __("Modify the Unix Group"), } }, @@ -291,14 +288,12 @@ class Wsdl(WsdlBase): { # идентификатор метода 'method_name': Unix.Method.GroupDel, - # категория метода - 'category': __('Old Unix'), # заголовок метода 'title': __("Delete the Group"), # иконка для графической консоли 'image': 'setup', # метод присутствует в графической консоли - 'gui': False, + 'gui': True, # консольная команда 'command': 'cl-unix-groupdel', # права для запуска метода @@ -332,6 +327,7 @@ class Wsdl(WsdlBase): next_label=_("Perform") ), ], + 'depends': [Unix.Method.Setup] }, # # Изменить параметры пользователя @@ -339,14 +335,12 @@ class Wsdl(WsdlBase): { # идентификатор метода 'method_name': Unix.Method.UserMod, - # категория метода - 'category': __('Old Unix'), # заголовок метода 'title': __("Modify the User"), # иконка для графической консоли 'image': 'setup', # метод присутствует в графической консоли - 'gui': False, + 'gui': True, # консольная команда 'command': 'cl-unix-usermod', # права для запуска метода @@ -418,6 +412,7 @@ class Wsdl(WsdlBase): 'ur_unix_pw_delete_set', ) }, + 'depends': [Unix.Method.Setup] }, # # Удалить пользователя @@ -425,14 +420,12 @@ class Wsdl(WsdlBase): { # идентификатор метода 'method_name': Unix.Method.UserDel, - # категория метода - 'category': __('Old Unix'), # заголовок метода 'title': __("Delete the User"), # иконка для графической консоли 'image': 'setup', # метод присутствует в графической консоли - 'gui': False, + 'gui': True, # консольная команда 'command': 'cl-unix-userdel', # права для запуска метода @@ -466,6 +459,7 @@ class Wsdl(WsdlBase): next_label=_("Perform") ), ], + 'depends': [Unix.Method.Setup] }, # # Сменить пароль пользователю @@ -473,8 +467,6 @@ class Wsdl(WsdlBase): { # идентификатор метода 'method_name': Unix.Method.Passwd, - # категория метода - 'category': __('Old Unix'), # заголовок метода 'title': __("Change the Password"), # иконка для графической консоли @@ -517,6 +509,7 @@ class Wsdl(WsdlBase): next_label=_("Perform") ), ], + 'depends': [Unix.Method.Setup] }, # # Просмотр групп @@ -567,6 +560,11 @@ class Wsdl(WsdlBase): ), expert=( 'cl_unix_group_fields', + 'cl_unix_group_filter_name', + 'cl_unix_group_filter_id', + 'cl_unix_group_filter_comment', + 'cl_unix_group_filter_users', + 'cl_unix_group_filter_primary', ), custom_buttons=[ ('but0', _("Add Group"), @@ -629,6 +627,16 @@ class Wsdl(WsdlBase): ), expert=( 'cl_unix_user_fields', + 'cl_unix_user_filter_login', + 'cl_unix_user_filter_pw_set', + 'cl_unix_user_filter_comment', + 'cl_unix_user_filter_uid', + 'cl_unix_user_filter_gid', + 'cl_unix_user_filter_groups', + 'cl_unix_user_filter_home_path', + 'cl_unix_user_filter_shell', + 'cl_unix_user_filter_visible_set', + 'cl_unix_user_filter_lock_set', ), custom_buttons=[ ('but0', _("Add User"),