You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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