permissions.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. from django.core.exceptions import PermissionDenied
  2. from django.db.models import Q
  3. from django.http import Http404
  4. from django.utils import timezone
  5. from django.utils.translation import ungettext, ugettext_lazy as _
  6. from misago.acl import add_acl, algebra
  7. from misago.acl.decorators import return_boolean
  8. from misago.core import forms
  9. from misago.forums.models import Forum, RoleForumACL, ForumRole
  10. from misago.forums.permissions import get_forums_roles
  11. from misago.threads.models import Thread, Post, Event
  12. """
  13. Admin Permissions Form
  14. """
  15. class PermissionsForm(forms.Form):
  16. legend = _("Threads")
  17. can_see_all_threads = forms.TypedChoiceField(
  18. label=_("Can see threads"),
  19. coerce=int,
  20. initial=0,
  21. choices=((0, _("Started threads")), (1, _("All threads"))))
  22. can_start_threads = forms.YesNoSwitch(label=_("Can start threads"))
  23. can_reply_threads = forms.YesNoSwitch(label=_("Can reply to threads"))
  24. can_edit_threads = forms.TypedChoiceField(
  25. label=_("Can edit threads"),
  26. coerce=int,
  27. initial=0,
  28. choices=((0, _("No")), (1, _("Own threads")), (2, _("All threads"))))
  29. can_hide_own_threads = forms.TypedChoiceField(
  30. label=_("Can hide own threads"),
  31. help_text=_("Only threads started within time limit and "
  32. "with no replies can be hidden."),
  33. coerce=int,
  34. initial=0,
  35. choices=(
  36. (0, _("No")),
  37. (1, _("Hide threads")),
  38. (2, _("Delete threads"))
  39. ))
  40. thread_edit_time = forms.IntegerField(
  41. label=_("Time limit for own threads edits, in minutes"),
  42. help_text=_("Enter 0 to don't limit time for editing own threads."),
  43. initial=0,
  44. min_value=0)
  45. can_hide_threads = forms.TypedChoiceField(
  46. label=_("Can hide all threads"),
  47. coerce=int,
  48. initial=0,
  49. choices=(
  50. (0, _("No")),
  51. (1, _("Hide threads")),
  52. (2, _("Delete threads"))
  53. ))
  54. can_edit_posts = forms.TypedChoiceField(
  55. label=_("Can edit posts"),
  56. coerce=int,
  57. initial=0,
  58. choices=((0, _("No")), (1, _("Own posts")), (2, _("All posts"))))
  59. can_hide_own_posts = forms.TypedChoiceField(
  60. label=_("Can hide own posts"),
  61. help_text=_("Only last posts to thread made within "
  62. "edit time limit can be hidden."),
  63. coerce=int,
  64. initial=0,
  65. choices=(
  66. (0, _("No")),
  67. (1, _("Hide posts")),
  68. (2, _("Delete posts"))
  69. ))
  70. post_edit_time = forms.IntegerField(
  71. label=_("Time limit for own post edits, in minutes"),
  72. help_text=_("Enter 0 to don't limit time for editing own posts."),
  73. initial=0,
  74. min_value=0)
  75. can_hide_posts = forms.TypedChoiceField(
  76. label=_("Can hide all posts"),
  77. coerce=int,
  78. initial=0,
  79. choices=(
  80. (0, _("No")),
  81. (1, _("Hide posts")),
  82. (2, _("Delete posts"))
  83. ))
  84. can_protect_posts = forms.YesNoSwitch(
  85. label=_("Can protect posts"),
  86. help_text=_("Only users with this permission "
  87. "can edit protected posts."))
  88. can_move_posts = forms.YesNoSwitch(
  89. label=_("Can move posts"))
  90. can_merge_posts = forms.YesNoSwitch(
  91. label=_("Can merge posts"))
  92. can_change_threads_labels = forms.TypedChoiceField(
  93. label=_("Can change threads labels"), coerce=int, initial=0,
  94. choices=((0, _("No")), (1, _("Own threads")), (2, _("All threads"))))
  95. can_pin_threads = forms.YesNoSwitch(
  96. label=_("Can pin threads"))
  97. can_close_threads = forms.YesNoSwitch(label=_("Can close threads"))
  98. can_move_threads = forms.YesNoSwitch(
  99. label=_("Can move threads"))
  100. can_merge_threads = forms.YesNoSwitch(
  101. label=_("Can merge threads"))
  102. can_split_threads = forms.YesNoSwitch(
  103. label=_("Can split threads"))
  104. can_review_moderated_content = forms.YesNoSwitch(
  105. label=_("Can review moderated content"),
  106. help_text=_("Will see and be able to accept moderated content."))
  107. can_report_content = forms.YesNoSwitch(label=_("Can report posts"))
  108. can_see_reports = forms.YesNoSwitch(label=_("Can see reports"))
  109. can_hide_events = forms.TypedChoiceField(
  110. label=_("Can hide events"),
  111. coerce=int,
  112. initial=0,
  113. choices=(
  114. (0, _("No")),
  115. (1, _("Hide events")),
  116. (2, _("Delete events"))
  117. ))
  118. def change_permissions_form(role):
  119. if isinstance(role, ForumRole):
  120. return PermissionsForm
  121. else:
  122. return None
  123. """
  124. ACL Builder
  125. """
  126. def build_acl(acl, roles, key_name):
  127. acl['moderated_forums'] = []
  128. forums_roles = get_forums_roles(roles)
  129. for forum in Forum.objects.all_forums():
  130. forum_acl = acl['forums'].get(forum.pk, {'can_browse': 0})
  131. if forum_acl['can_browse']:
  132. acl['forums'][forum.pk] = build_forum_acl(
  133. forum_acl, forum, forums_roles, key_name)
  134. return acl
  135. def build_forum_acl(acl, forum, forums_roles, key_name):
  136. forum_roles = forums_roles.get(forum.pk, [])
  137. final_acl = {
  138. 'can_see_all_threads': 0,
  139. 'can_start_threads': 0,
  140. 'can_reply_threads': 0,
  141. 'can_edit_threads': 0,
  142. 'can_edit_posts': 0,
  143. 'can_hide_own_threads': 0,
  144. 'can_hide_own_posts': 0,
  145. 'thread_edit_time': 0,
  146. 'post_edit_time': 0,
  147. 'can_hide_threads': 0,
  148. 'can_hide_posts': 0,
  149. 'can_protect_posts': 0,
  150. 'can_move_posts': 0,
  151. 'can_merge_posts': 0,
  152. 'can_change_threads_labels': 0,
  153. 'can_pin_threads': 0,
  154. 'can_close_threads': 0,
  155. 'can_move_threads': 0,
  156. 'can_merge_threads': 0,
  157. 'can_split_threads': 0,
  158. 'can_review_moderated_content': 0,
  159. 'can_report_content': 0,
  160. 'can_see_reports': 0,
  161. 'can_hide_events': 0,
  162. }
  163. final_acl.update(acl)
  164. algebra.sum_acls(final_acl, roles=forum_roles, key=key_name,
  165. can_see_all_threads=algebra.greater,
  166. can_start_threads=algebra.greater,
  167. can_reply_threads=algebra.greater,
  168. can_edit_threads=algebra.greater,
  169. can_edit_posts=algebra.greater,
  170. can_hide_threads=algebra.greater,
  171. can_hide_posts=algebra.greater,
  172. can_hide_own_threads=algebra.greater,
  173. can_hide_own_posts=algebra.greater,
  174. thread_edit_time=algebra.greater_or_zero,
  175. post_edit_time=algebra.greater_or_zero,
  176. can_protect_posts=algebra.greater,
  177. can_move_posts=algebra.greater,
  178. can_merge_posts=algebra.greater,
  179. can_change_threads_labels=algebra.greater,
  180. can_pin_threads=algebra.greater,
  181. can_close_threads=algebra.greater,
  182. can_move_threads=algebra.greater,
  183. can_merge_threads=algebra.greater,
  184. can_split_threads=algebra.greater,
  185. can_review_moderated_content=algebra.greater,
  186. can_report_content=algebra.greater,
  187. can_see_reports=algebra.greater,
  188. can_hide_events=algebra.greater,
  189. )
  190. return final_acl
  191. """
  192. ACL's for targets
  193. """
  194. def add_acl_to_target(user, target):
  195. if isinstance(target, Forum):
  196. add_acl_to_forum(user, target)
  197. if isinstance(target, Thread):
  198. add_acl_to_thread(user, target)
  199. if isinstance(target, Post):
  200. add_acl_to_post(user, target)
  201. if isinstance(target, Event):
  202. add_acl_to_event(user, target)
  203. def add_acl_to_forum(user, forum):
  204. forum_acl = user.acl['forums'].get(forum.pk, {})
  205. forum.acl.update({
  206. 'can_see_all_threads': 0,
  207. 'can_start_threads': 0,
  208. 'can_reply_threads': 0,
  209. 'can_edit_threads': 0,
  210. 'can_edit_posts': 0,
  211. 'can_hide_own_threads': 0,
  212. 'can_hide_own_posts': 0,
  213. 'thread_edit_time': 0,
  214. 'post_edit_time': 0,
  215. 'can_hide_threads': 0,
  216. 'can_hide_posts': 0,
  217. 'can_protect_posts': 0,
  218. 'can_move_posts': 0,
  219. 'can_merge_posts': 0,
  220. 'can_change_threads_labels': 0,
  221. 'can_pin_threads': 0,
  222. 'can_close_threads': 0,
  223. 'can_move_threads': 0,
  224. 'can_merge_threads': 0,
  225. 'can_split_threads': 0,
  226. 'can_review_moderated_content': 0,
  227. 'can_report_content': 0,
  228. 'can_see_reports': 0,
  229. 'can_hide_events': 0,
  230. })
  231. algebra.sum_acls(forum.acl, acls=[forum_acl],
  232. can_see_all_threads=algebra.greater)
  233. if user.is_authenticated():
  234. algebra.sum_acls(forum.acl, acls=[forum_acl],
  235. can_start_threads=algebra.greater,
  236. can_reply_threads=algebra.greater,
  237. can_edit_threads=algebra.greater,
  238. can_edit_posts=algebra.greater,
  239. can_hide_threads=algebra.greater,
  240. can_hide_posts=algebra.greater,
  241. can_hide_own_threads=algebra.greater,
  242. can_hide_own_posts=algebra.greater,
  243. thread_edit_time=algebra.greater_or_zero,
  244. post_edit_time=algebra.greater_or_zero,
  245. can_protect_posts=algebra.greater,
  246. can_move_posts=algebra.greater,
  247. can_merge_posts=algebra.greater,
  248. can_change_threads_labels=algebra.greater,
  249. can_pin_threads=algebra.greater,
  250. can_close_threads=algebra.greater,
  251. can_move_threads=algebra.greater,
  252. can_merge_threads=algebra.greater,
  253. can_split_threads=algebra.greater,
  254. can_review_moderated_content=algebra.greater,
  255. can_report_content=algebra.greater,
  256. can_see_reports=algebra.greater,
  257. can_hide_events=algebra.greater,
  258. )
  259. forum.acl['can_see_own_threads'] = not forum.acl['can_see_all_threads']
  260. def add_acl_to_thread(user, thread):
  261. forum_acl = user.acl['forums'].get(thread.forum_id, {})
  262. thread.acl.update({
  263. 'can_reply': can_reply_thread(user, thread),
  264. 'can_edit': can_edit_thread(user, thread),
  265. 'can_hide': forum_acl.get('can_hide_threads'),
  266. 'can_change_label': forum_acl.get('can_change_threads_labels') == 2,
  267. 'can_pin': forum_acl.get('can_pin_threads'),
  268. 'can_close': forum_acl.get('can_close_threads'),
  269. 'can_move': forum_acl.get('can_move_threads'),
  270. 'can_review': forum_acl.get('can_review_moderated_content'),
  271. 'can_report': forum_acl.get('can_report_content'),
  272. 'can_see_reports': forum_acl.get('can_see_reports')
  273. })
  274. if can_change_owned_thread(user, thread):
  275. if not thread.acl['can_change_label']:
  276. can_change_label = forum_acl.get('can_change_threads_labels') == 1
  277. thread.acl['can_change_label'] = can_change_label
  278. if not thread.acl['can_hide']:
  279. if not thread.replies:
  280. thread.acl['can_hide'] = forum_acl.get('can_hide_own_threads')
  281. def add_acl_to_post(user, post):
  282. forum_acl = user.acl['forums'].get(post.forum_id, {})
  283. post.acl.update({
  284. 'can_reply': can_reply_thread(user, post.thread),
  285. 'can_edit': can_edit_post(user, post),
  286. 'can_unhide': forum_acl.get('can_hide_threads'),
  287. 'can_hide': forum_acl.get('can_hide_threads'),
  288. 'can_delete': forum_acl.get('can_hide_threads'),
  289. 'can_protect': forum_acl.get('can_protect_posts'),
  290. 'can_report': forum_acl.get('can_report_content'),
  291. 'can_see_reports': forum_acl.get('can_see_reports'),
  292. 'can_approve': forum_acl.get('can_review_moderated_content'),
  293. })
  294. def add_acl_to_event(user, event):
  295. forum_acl = user.acl['forums'].get(event.forum_id, {})
  296. can_hide_events = forum_acl.get('can_hide_events', 0)
  297. event.acl['can_hide'] = can_hide_events > 0
  298. event.acl['can_delete'] = can_hide_events == 2
  299. """
  300. ACL tests
  301. """
  302. def allow_see_thread(user, target):
  303. forum_acl = user.acl['forums'].get(target.forum_id, {})
  304. if not forum_acl.get('can_browse'):
  305. raise Http404()
  306. if not forum_acl.get('can_see_all_threads'):
  307. if user.is_anonymous() or user.pk != target.starter_id:
  308. raise Http404()
  309. can_see_thread = return_boolean(allow_see_thread)
  310. def allow_start_thread(user, target):
  311. if target.is_closed:
  312. message = _("This forum is closed. You can't start new threads in it.")
  313. raise PermissionDenied(message)
  314. if user.is_anonymous():
  315. raise PermissionDenied(_("You have to sign in to start new thread."))
  316. if not user.acl['forums'].get(target.id, {'can_start_threads': False}):
  317. raise PermissionDenied(_("You don't have permission to start "
  318. "new threads in this forum."))
  319. can_start_thread = return_boolean(allow_start_thread)
  320. def allow_reply_thread(user, target):
  321. if target.forum.is_closed:
  322. message = _("This forum is closed.")
  323. raise PermissionDenied(message)
  324. if user.is_anonymous():
  325. raise PermissionDenied(_("You have to sign in to reply threads."))
  326. forum_acl = target.forum.acl
  327. if not forum_acl['can_reply_threads']:
  328. raise PermissionDenied(_("You can't reply to threads in this forum."))
  329. if target.is_closed and not forum_acl['can_close_threads']:
  330. raise PermissionDenied(
  331. _("You can't reply to closed threads in this forum."))
  332. can_reply_thread = return_boolean(allow_reply_thread)
  333. def allow_edit_thread(user, target):
  334. if target.forum.is_closed:
  335. message = _("This forum is closed. You can't edit threads in it.")
  336. raise PermissionDenied(message)
  337. if user.is_anonymous():
  338. raise PermissionDenied(_("You have to sign in to edit threads."))
  339. forum_acl = target.forum.acl
  340. if not forum_acl['can_edit_threads']:
  341. raise PermissionDenied(_("You can't edit threads in this forum."))
  342. if target.is_closed and not forum_acl['can_close_threads']:
  343. raise PermissionDenied(
  344. _("You can't edit closed threads in this forum."))
  345. if forum_acl['can_edit_threads'] == 1:
  346. if target.starter_id != user.pk:
  347. raise PermissionDenied(
  348. _("You can't edit other users threads in this forum."))
  349. if not has_time_to_edit_thread(user, target):
  350. message = ungettext("You can't edit threads that are "
  351. "older than %(minutes)s minute.",
  352. "You can't edit threads that are "
  353. "older than %(minutes)s minutes.",
  354. forum_acl['thread_edit_time'])
  355. raise PermissionDenied(
  356. message % {'minutes': forum_acl['thread_edit_time']})
  357. can_edit_thread = return_boolean(allow_edit_thread)
  358. def allow_see_post(user, target):
  359. if target.is_moderated:
  360. forum_acl = user.acl['forums'].get(target.forum_id, {})
  361. if not forum_acl.get('can_review_moderated_content'):
  362. if user.is_anonymous() or user.pk != target.poster_id:
  363. raise Http404()
  364. can_see_post = return_boolean(allow_see_post)
  365. def allow_edit_post(user, target):
  366. if target.forum.is_closed:
  367. message = _("This forum is closed. You can't edit posts in it.")
  368. raise PermissionDenied(message)
  369. if user.is_anonymous():
  370. raise PermissionDenied(_("You have to sign in to edit posts."))
  371. forum_acl = target.forum.acl
  372. if not forum_acl['can_edit_posts']:
  373. raise PermissionDenied(_("You can't edit posts in this forum."))
  374. if target.thread.is_closed and not forum_acl['can_close_threads']:
  375. raise PermissionDenied(
  376. _("You can't edit posts in closed threads."))
  377. if forum_acl['can_edit_posts'] == 1:
  378. if target.poster_id != user.pk:
  379. raise PermissionDenied(
  380. _("You can't edit other users posts in this forum."))
  381. if not has_time_to_edit_post(user, target):
  382. message = ungettext("You can't edit posts that are "
  383. "older than %(minutes)s minute.",
  384. "You can't edit posts that are "
  385. "older than %(minutes)s minutes.",
  386. forum_acl['post_edit_time'])
  387. raise PermissionDenied(
  388. message % {'minutes': forum_acl['post_edit_time']})
  389. if target.is_protected and not forum_acl['can_protect_posts']:
  390. raise PermissionDenied(_("This post is protected. You can't edit it."))
  391. can_edit_post = return_boolean(allow_edit_post)
  392. """
  393. Permission check helperts
  394. """
  395. def can_change_owned_thread(user, target):
  396. forum_acl = user.acl['forums'].get(target.forum_id, {})
  397. if user.is_anonymous() or user.pk != target.starter_id:
  398. return False
  399. if target.forum.is_closed or target.is_closed:
  400. return False
  401. if target.first_post.is_protected:
  402. return False
  403. return has_time_to_edit_thread(user, target)
  404. def has_time_to_edit_thread(user, target):
  405. forum_acl = user.acl['forums'].get(target.forum_id, {})
  406. if forum_acl.get('thread_edit_time'):
  407. diff = timezone.now() - target.started_on
  408. diff_minutes = int(diff.total_seconds() / 60)
  409. return diff_minutes < forum_acl.get('thread_edit_time')
  410. else:
  411. return True
  412. def has_time_to_edit_post(user, target):
  413. forum_acl = user.acl['forums'].get(target.forum_id, {})
  414. if forum_acl.get('post_edit_time'):
  415. diff = timezone.now() - target.posted_on
  416. diff_minutes = int(diff.total_seconds() / 60)
  417. return diff_minutes < forum_acl.get('post_edit_time')
  418. else:
  419. return True
  420. """
  421. Queryset helpers
  422. """
  423. def exclude_invisible_threads(queryset, user, forum=None):
  424. if forum:
  425. return exclude_invisible_forum_threads(queryset, user, forum)
  426. else:
  427. return exclude_all_invisible_threads(queryset, user)
  428. def exclude_invisible_forum_threads(queryset, user, forum):
  429. if user.is_authenticated():
  430. condition_author = Q(starter_id=user.id)
  431. can_mod = forum.acl['can_review_moderated_content']
  432. can_hide = forum.acl['can_hide_threads']
  433. if not can_mod and not can_hide:
  434. condition = Q(is_moderated=False) & Q(is_hidden=False)
  435. queryset = queryset.filter(condition_author | condition)
  436. elif not can_mod:
  437. condition = Q(is_moderated=False)
  438. queryset = queryset.filter(condition_author | condition)
  439. elif not can_hide:
  440. condition = Q(is_hidden=False)
  441. queryset = queryset.filter(condition_author | condition)
  442. else:
  443. if not forum.acl['can_review_moderated_content']:
  444. queryset = queryset.filter(is_moderated=False)
  445. if not forum.acl['can_hide_threads']:
  446. queryset = queryset.filter(is_hidden=False)
  447. return queryset
  448. def exclude_all_invisible_threads(queryset, user):
  449. forums_in = []
  450. conditions = None
  451. for forum in Forum.objects.all_forums():
  452. add_acl(user, forum)
  453. condition_forum = Q(forum=forum)
  454. condition_author = Q(starter_id=user.id)
  455. # can see all threads?
  456. if forum.acl['can_see_all_threads']:
  457. can_mod = forum.acl['can_review_moderated_content']
  458. can_hide = forum.acl['can_hide_threads']
  459. if not can_mod or not can_hide:
  460. if not can_mod and not can_hide:
  461. condition = Q(is_moderated=False) & Q(is_hidden=False)
  462. elif not can_mod:
  463. condition = Q(is_moderated=False)
  464. elif not can_hide:
  465. condition = Q(is_hidden=False)
  466. visibility_condition = condition_author | condition
  467. visibility_condition = condition_forum & visibility_condition
  468. else:
  469. # user can see everything so don't bother with rest of routine
  470. forums_in.append(forum.pk)
  471. continue
  472. else:
  473. # show all threads in forum made by user
  474. visibility_condition = condition_forum & condition_author
  475. if conditions:
  476. conditions = conditions | visibility_condition
  477. else:
  478. conditions = visibility_condition
  479. if conditions and forums_in:
  480. return queryset.filter(Q(forum_id__in=forums_in) | conditions)
  481. elif conditions:
  482. return queryset.filter(conditions)
  483. elif forums_in:
  484. return queryset.filter(forum_id__in=forums_in)
  485. else:
  486. return Thread.objects.none()
  487. def exclude_invisible_posts(queryset, user, forum):
  488. if not forum.acl['can_review_moderated_content']:
  489. if user.is_authenticated():
  490. condition_author = Q(poster=user.id)
  491. condition = Q(is_moderated=False)
  492. queryset = queryset.filter(condition_author | condition)
  493. else:
  494. queryset = queryset.filter(is_moderated=False)
  495. return queryset