Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

498 linhas
15 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 Mir Calculate. http://www.calculate-linux.org
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import sys
  16. from calculate.lib.datavars import (ReadonlyVariable, Variable,
  17. VariableError, VariableInterface)
  18. from calculate.ldap.variables.helpers import (LdapSearchHelper, LdapMaxHelper)
  19. from calculate.unix.variables.helpers import (UnixUserHelper, UnixGroupHelper,
  20. UnixActionHelper)
  21. from .action import Actions
  22. import re
  23. _ = lambda x: x
  24. from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate)
  25. setLocalTranslate('cl_unix3', sys.modules[__name__])
  26. __ = getLazyLocalTranslate(_)
  27. class GroupNameHelper(VariableInterface):
  28. """
  29. Вспомогательный объект для проверки имени группы
  30. """
  31. def check_group_name(self, gname):
  32. if len(gname) > 32:
  33. raise VariableError(_("Wrong group name length"))
  34. if ":" in gname:
  35. raise VariableError(_("Wrong group name"))
  36. class VariableUrUnixGroupName(GroupNameHelper,
  37. LdapSearchHelper, UnixActionHelper, Variable):
  38. """
  39. Название группы
  40. """
  41. base_dn = "{ld_unix_groups_dn}"
  42. search_filter = '(cn={value})'
  43. untrusted = True
  44. opt = ("ur_unix_group_name",)
  45. metavalue = "GROUP"
  46. def init(self):
  47. self.label = _("Group")
  48. self.help = _("set the group name")
  49. def get_new(self):
  50. return ""
  51. def get_exists(self):
  52. return self.Get('ur_unix_group_name_exists')
  53. def check(self, value):
  54. if not value:
  55. raise VariableError(_("Please specify the group name"))
  56. self.check_group_name(value)
  57. if value == "list":
  58. raise VariableError(_("List is used as keyword"))
  59. if self.check_name(value):
  60. raise VariableError(_("Group name already exists"))
  61. class VariableUrUnixGroupLabel(ReadonlyVariable):
  62. """
  63. Информационное поле для закладки
  64. """
  65. type = "label"
  66. def init(self):
  67. self.label = _("Group")
  68. def get(self):
  69. return self.Get('ur_unix_group_name')
  70. def uncompatible(self):
  71. return self.label
  72. class VariableUrUnixGroupNameExists(UnixUserHelper, UnixGroupHelper, Variable):
  73. """
  74. Название редактируемой/просматриваемой группы
  75. """
  76. type = "choice"
  77. base_dn = "{ld_unix_groups_dn}"
  78. search_filter = '(cn={value})'
  79. guitype = "hidden"
  80. untrusted = True
  81. opt = ("ur_unix_group_name_exists",)
  82. metavalue = "GROUP"
  83. def init(self):
  84. self.label = _("Group")
  85. self.help = _("set the group name")
  86. def choice(self):
  87. if self.Get('cl_unix_action') == Actions.GroupDel:
  88. primary_groups = map(int, self.get_primary_gids())
  89. return [(group.group_name,
  90. "%s (%s)" % (group.group_name, group.comment))
  91. for group in self.iterate_ldap_group("cn=*")
  92. if group.gid not in primary_groups]
  93. else:
  94. return [(group.group_name,
  95. "%s (%s)" % (group.group_name, group.comment))
  96. for group in self.iterate_ldap_group("cn=*")]
  97. def raiseWrongChoice(self, name, choiceVal, value, error):
  98. if self.Get('cl_unix_action') == Actions.GroupDel:
  99. group = self.search_ldap_group_name(value)
  100. if group:
  101. users = ", ".join(user.username for user in
  102. self.iterate_ldap_user(
  103. "gidNumber=%d" % group.gid))
  104. if users:
  105. raise VariableError(
  106. _("Group {group} is the primary group for users {users}"
  107. ).format(group=value, users=users))
  108. if not value:
  109. raise VariableError(_("Select group"))
  110. raise VariableError(_("Group %s not found") % value)
  111. class VariableClUnixGroupCommentDefault(Variable):
  112. """
  113. Комментарий для новой группы по умолчанию
  114. """
  115. value_format = "{ldap.ld_base_root.capitalize()} group"
  116. class VariableUrUnixGroupComment(UnixGroupHelper, UnixActionHelper, Variable):
  117. """
  118. Комментарий к группе
  119. """
  120. opt = ('-c', '--comment')
  121. metavalue = "COMMENT"
  122. def init(self):
  123. self.label = _("Comment")
  124. self.help = _("set comment of the group")
  125. def get_new(self):
  126. return self.Get('unix.cl_unix_group_comment_default')
  127. def get_exists(self):
  128. return self.Get('ur_unix_group_comment_exists')
  129. class VariableUrUnixGroupCount(UnixGroupHelper, UnixActionHelper,
  130. ReadonlyVariable):
  131. """
  132. Количество групп
  133. """
  134. type = "int"
  135. def get_exists(self):
  136. return len(self.ldap_group_list())
  137. class VariableUrUnixGroupCommentExists(UnixGroupHelper, UnixActionHelper,
  138. Variable):
  139. """
  140. Комментарий к группе
  141. """
  142. def get_exists(self):
  143. group_name = self.Get('ur_unix_group_name')
  144. if group_name:
  145. group = self.search_ldap_group_name(group_name)
  146. if group:
  147. return group.comment
  148. return ""
  149. class VariableUrUnixGroupId(LdapSearchHelper, UnixActionHelper, Variable):
  150. """
  151. ID группы
  152. """
  153. base_dn = "{ld_unix_groups_dn}"
  154. search_filter = '(gidNumber={value})'
  155. type = "int"
  156. opt = ('-g', '--gid')
  157. metavalue = "GID"
  158. def init(self):
  159. self.label = _("Group ID")
  160. self.help = _("set the group ID")
  161. def get_new(self):
  162. return self.Get('ur_unix_next_gid')
  163. def get_exists(self):
  164. return self.Get('ur_unix_group_id_exists')
  165. def check_new(self, value):
  166. if not value:
  167. raise VariableError(_("Please specify the group ID"))
  168. if self.check_name(value):
  169. raise VariableError(_("Group ID already exists"))
  170. def check_exists(self, value):
  171. old_value = self.Get('ur_unix_group_id_exists')
  172. if not value:
  173. raise VariableError(_("Please specify the group ID"))
  174. if value != old_value and self.check_name(value):
  175. raise VariableError(_("Group ID already exists"))
  176. class VariableUrUnixGroupIdExists(UnixGroupHelper, LdapSearchHelper,
  177. UnixActionHelper, Variable):
  178. """
  179. ID группы
  180. """
  181. type = "int"
  182. def get_exists(self):
  183. group_name = self.Get('ur_unix_group_name')
  184. if group_name:
  185. group = self.search_ldap_group_name(group_name)
  186. if group:
  187. return str(group.gid)
  188. return ""
  189. class VariableUrUnixNextGid(LdapMaxHelper, ReadonlyVariable):
  190. """
  191. Следующий свободный Uid
  192. """
  193. base_dn = "{ld_unix_groups_dn}"
  194. search_filter = "cn=*"
  195. attr = "gidNumber"
  196. def get(self):
  197. value = self.get_max()
  198. if value is None:
  199. return self.Get('ur_unix_min_gid')
  200. else:
  201. return str(value + 1)
  202. class VariableUrUnixMinGid(Variable):
  203. """
  204. Минимальный uid
  205. """
  206. type = "int"
  207. value = "10000"
  208. class VariableUrUnixGroupUsers(UnixGroupHelper, ReadonlyVariable):
  209. """
  210. Текущий список пользователей в группе
  211. """
  212. type = "list"
  213. def init(self):
  214. self.label = _("Users")
  215. def get(self):
  216. group_name = self.Get('ur_unix_group_name')
  217. if group_name:
  218. group = self.search_ldap_group_name(group_name)
  219. if group:
  220. return group.user_list
  221. return []
  222. class VariableUrUnixGroupUsersAdd(UnixUserHelper, Variable):
  223. """
  224. Пользователи добавляемые в группу
  225. """
  226. type = "choiceedit-list"
  227. opt = ("-a", "--add")
  228. guitype = "hidden"
  229. value = []
  230. metavalue = "USERS"
  231. def init(self):
  232. self.label = _("Include in group")
  233. self.help = _("add members")
  234. def choice(self):
  235. if self.Get('ur_unix_group_name'):
  236. exists_users = self.Get('ur_unix_group_users')
  237. return (x for x in self.ldap_user_list() if
  238. x[0] not in exists_users)
  239. return []
  240. def get(self):
  241. exists_users = set(self.Get('ur_unix_group_users'))
  242. replace_users = set(self.Get('ur_unix_group_users_replace'))
  243. return sorted(list(replace_users - exists_users))
  244. def check(self, value):
  245. exists_users = self.Get('ur_unix_group_users')
  246. replace_users = self.Get('ur_unix_group_users_replace')
  247. if set(exists_users) != set(replace_users):
  248. raise VariableError(_(
  249. "You cannot add users to group and replace the list "
  250. "of its members"))
  251. group = self.Get('ur_unix_group_name')
  252. users = self.ldap_user_names()
  253. failed = [x for x in value if x not in users]
  254. if failed:
  255. raise VariableError(
  256. _("Wrong users {users}").format(
  257. users=", ".join(failed)))
  258. already_exists = [x for x in value if x in exists_users]
  259. if already_exists:
  260. raise VariableError(
  261. _("Users {users} already exist in group {group}").format(
  262. users=", ".join(already_exists), group=group))
  263. class VariableUrUnixGroupUsersReplace(UnixUserHelper, UnixActionHelper,
  264. Variable):
  265. """
  266. Замена всех пользователей в группе
  267. """
  268. type = "choiceedit-list"
  269. opt = ("-U ", "--users")
  270. value = []
  271. metavalue = "USERS"
  272. def init(self):
  273. self.label = _("Users")
  274. self.help = _("new group's members list")
  275. def get_exists(self):
  276. return list(sorted(self.Get('ur_unix_group_users')))
  277. def choice_exists(self):
  278. return self.ldap_user_list()
  279. def check_exists(self, value):
  280. users = self.ldap_user_names()
  281. failed = [x for x in value if x not in users]
  282. if failed:
  283. raise VariableError(
  284. _("Wrong users {users}").format(
  285. users=", ".join(failed)))
  286. class VariableUrUnixGroupUsersDel(UnixUserHelper, Variable):
  287. """
  288. Пользователи добавляемые в группу
  289. """
  290. type = "choiceedit-list"
  291. opt = ("-r", "--remove")
  292. guitype = "hidden"
  293. value = []
  294. metavalue = "USERS"
  295. def init(self):
  296. self.label = _("Exclude from groups")
  297. self.help = _("remove members")
  298. def choice(self):
  299. exists_users = self.Get('ur_unix_group_users')
  300. return (x for x in self.ldap_user_list() if
  301. x[0] in exists_users)
  302. def get(self):
  303. exists_users = set(self.Get('ur_unix_group_users'))
  304. replace_users = set(self.Get('ur_unix_group_users_replace'))
  305. return sorted(list(exists_users - replace_users))
  306. def check(self, value):
  307. exists_users = self.Get('ur_unix_group_users')
  308. replace_users = self.Get('ur_unix_group_users_replace')
  309. if set(exists_users) != set(replace_users):
  310. raise VariableError(_(
  311. "You cannot remove users from a group and replace the "
  312. "list of its members"))
  313. if not exists_users and value:
  314. raise VariableError(_("No members in this group"))
  315. group = self.Get('ur_unix_group_name')
  316. users = self.ldap_user_names()
  317. failed = [x for x in value if x not in users]
  318. if failed:
  319. raise VariableError(
  320. _("Wrong users {users}").format(
  321. users=", ".join(failed)))
  322. not_exists = [x for x in value if x not in exists_users]
  323. if not_exists:
  324. raise VariableError(
  325. _("Users {users} are not in group {group}").format(
  326. users=", ".join(not_exists), group=group))
  327. def humanReadable(self):
  328. if not self.Get():
  329. return _("Do not change")
  330. class VariableUrUnixGroupNewname(GroupNameHelper, UnixGroupHelper, Variable):
  331. opt = ("-n", "--new-name")
  332. value = ""
  333. metavalue = "NEW_GROUP"
  334. def init(self):
  335. self.label = _("Group name")
  336. self.help = _("use NEW_GROUP for GROUP name")
  337. def get(self):
  338. return self.Get('ur_unix_group_name')
  339. def check(self, value):
  340. if value == self.Get('ur_unix_group_name'):
  341. return
  342. self.check_group_name(value)
  343. if self.search_ldap_group_name(value):
  344. raise VariableError(
  345. _("Group {name} already exists").format(name=value))
  346. def humanReadable(self):
  347. value = self.Get()
  348. if not value:
  349. return _("Do not change")
  350. return value
  351. class VariableClUnixGroupAliases(ReadonlyVariable):
  352. """
  353. Алиасы для переменных
  354. """
  355. type = "table"
  356. value = [ # ('name', 'ur_unix_group_name'),
  357. ('id', 'ur_unix_group_id'),
  358. ('comment', 'ur_unix_group_comment'),
  359. ('users', 'ur_unix_group_users')]
  360. class VariableClUnixGroupFields(Variable):
  361. """
  362. Список полей для вывода данных группы
  363. """
  364. type = "choice-list"
  365. element = "selecttable"
  366. opt = ["--fields"]
  367. metavalue = "FIELDS"
  368. def init(self):
  369. self.label = _("Fields")
  370. self.help = _("fields for display")
  371. def choice(self):
  372. data = self.Get('cl_unix_group_aliases')
  373. return [(x, self.parent.getInfo(y).label) for x, y in data]
  374. def get(self):
  375. return [x for x, y in self.Get('cl_unix_group_aliases')]
  376. class VariableClUnixGroupShowFields(ReadonlyVariable):
  377. """
  378. Список переменных полей при отображении списка групп
  379. """
  380. type = "list"
  381. def get(self):
  382. mapping = dict(self.Get('cl_unix_group_aliases'))
  383. return [mapping[x] for x in self.Get('cl_unix_group_fields')]
  384. class VariableUrUnixGroupShow(UnixGroupHelper,
  385. UnixActionHelper, Variable):
  386. """
  387. Фильтр на group name
  388. """
  389. type = "choiceedit"
  390. opt = ["ur_unix_group_show"]
  391. metavalue = "GROUP"
  392. value = ""
  393. def init(self):
  394. self.label = _("Group name")
  395. self.help = _("show group")
  396. def choice_exists(self):
  397. return [("", "")] + self.ldap_group_list()
  398. def check_exists(self, value):
  399. if value:
  400. if not self.search_ldap_group_name(value):
  401. raise VariableError(_("%s group not found") % value)
  402. def raiseWrongChoice(self, name, choiceVal, value, error):
  403. raise VariableError(_("Wrong group name"))