コード例 #1
0
ファイル: security.py プロジェクト: debon/comt
def has_own_perm(request, perm_name, text, comment):
    
    user = get_request_user(request)
    
    if not user:
        return False
    
    # bypass sec if NO_SECURITY
    if cm_settings.NO_SECURITY:
        return True
    
    # make sure perm exist
    assert Permission.objects.get(codename=perm_name)

    try:
      myself = request.GET.get('name', None)
    except AttributeError:
      myself = None
    key = sha1(str((settings.SITE_URL, 'has_own_perm', (user, myself, text, comment, perm_name)))).hexdigest()
    val = cache.get(key)
    if val != None:
      return val
    
    # 2 special cases for comment own edition:
    
    # 1
    # if perm = can_edit_own_comment and 
    # text is a priori moderated and
    # comment is approved and
    # don't have moderation rights and
    if comment and comment.state == 'approved' and \
       perm_name == 'can_edit_comment_own' and \
       text.last_text_version.mod_posteriori == False and \
       not has_perm(request, 'can_manage_text', text=text):
        cache.set(key, False)
        return False
    
    # 2       
    # if perm = can_edit_own_comment and and 
    # text is a posteriori moderated and
    # there is a reply
    # don't have moderation rights and
    if comment and comment.state == 'approved' and \
       perm_name == 'can_edit_comment_own' and \
       text.last_text_version.mod_posteriori == True and \
       comment.comment_set.count() != 0 and \
       not has_perm(request, 'can_manage_text', text=text):
        cache.set(key, False)
        return False
    
    actual_own_user = False
    if comment.user == request.user:
      if DECORATED_CREATORS:
        if myself == comment.get_name():
          actual_own_user = True
      else:
        actual_own_user = True
    ret = (actual_own_user and has_perm(request, perm_name, text=text)) 
    cache.set(key, ret)
    return ret
コード例 #2
0
ファイル: security.py プロジェクト: ovnicraft/comt
        def _check_global_or_local_perm(request, *args, **kwargs):
            if must_be_logged_in and not is_authenticated(request):
                if not api:
                    raise UnauthorizedException('Should be logged in')
                else:
                    return rc.FORBIDDEN

            if has_perm(request, global_perm_name, text=None):
                return view_func(request, *args, **kwargs)

            if cm_settings.NO_SECURITY:
                return view_func(request, *args, **kwargs)

            if 'key' in kwargs:
                text = get_object_or_404(Text, key=kwargs['key'])
            else:
                raise Exception('no security check possible')

            # in api, the view has an object as first parameter, request is args[0]
            if not api:
                req = request
            else:
                req = args[0]

            if has_perm(req, perm_name, text=text):
                return view_func(request, *args, **kwargs)

            if not api:
                raise UnauthorizedException('No perm %s' % perm_name)
            else:
                return rc.FORBIDDEN

            raise UnauthorizedException('No global perm %s nor local perm %s' %
                                        (global_perm_name, perm_name))
コード例 #3
0
ファイル: security.py プロジェクト: debon/comt
    def _check_global_or_local_perm(request, *args, **kwargs):
      if must_be_logged_in and not is_authenticated(request):
        if not api:
          raise UnauthorizedException('Should be logged in')
        else:
          return rc.FORBIDDEN

      if has_perm(request, global_perm_name, text=None): 
        return view_func(request, *args, **kwargs)
            
      if cm_settings.NO_SECURITY:
        return view_func(request, *args, **kwargs)

      if 'key' in kwargs: 
        text = get_object_or_404(Text, key=kwargs['key'])                
      else:
        raise Exception('no security check possible')
                
      # in api, the view has an object as first parameter, request is args[0]
      if not api:                
        req = request
      else:                    
        req = args[0]     

      if has_perm(req, perm_name, text=text): 
        return view_func(request, *args, **kwargs)
            
      if not api:
        raise UnauthorizedException('No perm %s' % perm_name)
      else:
        return rc.FORBIDDEN

      raise UnauthorizedException('No global perm %s nor local perm %s' %(global_perm_name, perm_name))
コード例 #4
0
ファイル: client.py プロジェクト: clarkcui89/papermache
    def default(self, obj):
        if isinstance(obj, Comment) :
            comment = obj
            #replies = list(comment.comment_set.order_by('created'))
            text=comment.text_version.text
            replies = get_viewable_comments(self.request, comment.comment_set.all(), text)
            
            # can_view == true because of get_viewable_comments filter
            can_moderate = has_perm(self.request, 'can_edit_comment', text)   
            can_edit = has_perm(self.request, 'can_edit_comment', text) or has_own_perm(self.request, 'can_edit_comment_own', text, comment)  
            can_delete = has_perm(self.request, 'can_delete_comment', text) or has_own_perm(self.request, 'can_delete_comment_own', text, comment)
            
            return {'id' : comment.id, 
                    'key' : comment.key,
                    'id_key' : comment.id_key,
                   'created_user_str' : datetime_to_user_str(request_tz_convert(comment.created, self.request)),
                   'modified_user_str' : datetime_to_user_str(request_tz_convert(comment.modified, self.request)),
#                   'created_str' : datetime_to_str(comment.created), # TODO change to a simple number as modified if possible
                   'created' : datetime_to_epoch(comment.created), # TODO change to a simple number as modified if possible
                   'modified' : datetime_to_epoch(comment.modified),  
#                   'modified' : time.mktime(comment.modified.timetuple()),  
#                   'created' : datetime_to_js_date_str(comment.created),
                   'reply_to_id' : comment.reply_to_id,
                   'replies' : replies,
                   'name' : comment.get_name(), 
                   'email' : comment.get_email(), 
                   'logged_author' : (comment.user != None), 
                   'title':comment.title,
                   'content':comment.content, 
                   'content_html':comment.content_html, 
                   'tags': ', '.join(parse_tag_input(comment.tags)), 
                   'format': comment.format, 
                   'start_wrapper' : comment.start_wrapper, 
                   'end_wrapper' : comment.end_wrapper,
                   'start_offset' : comment.start_offset, 
                   'end_offset' : comment.end_offset,
                   'url': comment.url,
                   'state' : comment.state,
                   'permalink' : reverse('text-view-show-comment', args=[text.key, comment.id_key]),
                   # permission
                   'can_edit' : can_edit,
                   'can_delete' : can_delete,
                   'can_moderate' : can_moderate,
                   }
        if isinstance(obj, Tag) :
            tag = obj
            # RBE each time issuing a db request to find comments related to this tag !!! TODO  
            return { 'ids' : [t.id for t in tag.items.all()], 'name' : tag.name, 'font_size' : tag.font_size}            

        return simplejson.JSONEncoder.default(self, obj)
コード例 #5
0
    def default(self, obj):
        if isinstance(obj, Comment) :
            comment = obj
            #replies = list(comment.comment_set.order_by('created'))
            text=comment.text_version.text
            replies = get_viewable_comments(self.request, comment.comment_set.all(), text)
            
            # can_view == true because of get_viewable_comments filter
            can_moderate = has_perm(self.request, 'can_edit_comment', text)   
            can_edit = has_perm(self.request, 'can_edit_comment', text) or has_own_perm(self.request, 'can_edit_comment_own', text, comment)  
            can_delete = has_perm(self.request, 'can_delete_comment', text) or has_own_perm(self.request, 'can_delete_comment_own', text, comment)
            
            return {'id' : comment.id, 
                    'key' : comment.key,
                    'id_key' : comment.id_key,
                   'created_user_str' : datetime_to_user_str(request_tz_convert(comment.created, self.request)),
                   'modified_user_str' : datetime_to_user_str(request_tz_convert(comment.modified, self.request)),
#                   'created_str' : datetime_to_str(comment.created), # TODO change to a simple number as modified if possible
                   'created' : datetime_to_epoch(comment.created), # TODO change to a simple number as modified if possible
                   'modified' : datetime_to_epoch(comment.modified),  
#                   'modified' : time.mktime(comment.modified.timetuple()),  
#                   'created' : datetime_to_js_date_str(comment.created),
                   'reply_to_id' : comment.reply_to_id,
                   'replies' : replies,
                   'name' : comment.get_name(), 
                   'email' : comment.get_email(), 
                   'logged_author' : (comment.user != None), 
                   'title':comment.title,
                   'content':comment.content, 
                   'content_html':comment.content_html, 
                   'tags': ', '.join(parse_tag_input(comment.tags)), 
                   'category': comment.category,
                   'format': comment.format, 
                   'start_wrapper' : comment.start_wrapper, 
                   'end_wrapper' : comment.end_wrapper,
                   'start_offset' : comment.start_offset, 
                   'end_offset' : comment.end_offset,
                   'state' : comment.state,
                   'permalink' : reverse('text-view-show-comment', args=[text.key, comment.id_key]),
                   # permission
                   'can_edit' : can_edit,
                   'can_delete' : can_delete,
                   'can_moderate' : can_moderate,
                   }
        if isinstance(obj, Tag) :
            tag = obj
            # RBE each time issuing a db request to find comments related to this tag !!! TODO  
            return { 'ids' : [t.id for t in tag.items.all()], 'name' : tag.name, 'font_size' : tag.font_size}            

        return simplejson.JSONEncoder.default(self, obj)
コード例 #6
0
ファイル: security.py プロジェクト: debon/comt
        def _check_local_perm(request, *args, **kwargs):
            if cm_settings.NO_SECURITY:
                return view_func(request, *args, **kwargs)

            if must_be_logged_in and not is_authenticated(request):
                if not api:
                    raise UnauthorizedException('Should be logged in')
                else:
                    return rc.FORBIDDEN

            
            if 'key' in kwargs: 
                text = get_object_or_404(Text, key=kwargs['key'])                
            else:
                raise Exception('no security check possible')
                
            # in api, the view has an object as first parameter, request is args[0]
            if not api:                
                req = request
            else:                    
                req = args[0]     
            if has_perm(req, perm_name, text=text): 
                return view_func(request, *args, **kwargs)
            #else:
                # TODO: (? useful ?) if some user have the perm and not logged-in : redirect to login
                #if not request.user.is_authenticated() and number_has_perm_on_text(permission, text_id) > 0:
                #    return HttpResponseRedirect('%s?%s=%s' % (login_url, redirect_field_name, urlquote(request.get_full_path())))                    
            # else : unauthorized
            
            if not api:
                raise UnauthorizedException('No perm %s' % perm_name)
            else:
                return rc.FORBIDDEN
コード例 #7
0
ファイル: security.py プロジェクト: ovnicraft/comt
def get_viewable_activities(request=None, act_types={}, text=None):
    """
    Get activities user in request is allowed to see
    """
    from cm.security import has_perm, get_texts_with_perm, get_viewable_comments

    selected_activities = reduce(list.__add__, [
        Activity.VIEWABLE_ACTIVITIES[k]
        for k in act_types.keys() if act_types[k]
    ], [])

    activities = Activity.objects.filter(type__in=selected_activities)
    if text:
        activities = activities.filter(text=text)

    if not has_perm(request, 'can_manage_workspace'):
        texts = get_texts_with_perm(request, 'can_view_text')
        activities = activities.filter(Q(text__in=texts))

        comments = []
        [
            comments.extend(
                get_viewable_comments(request,
                                      t.last_text_version.comment_set.all(),
                                      t)) for t in texts
        ]

        activities = activities.filter(
            Q(comment__in=comments) | Q(comment=None))
    return activities.order_by('-created')
コード例 #8
0
ファイル: security.py プロジェクト: ovnicraft/comt
        def _check_local_perm(request, *args, **kwargs):
            if cm_settings.NO_SECURITY:
                return view_func(request, *args, **kwargs)

            if must_be_logged_in and not is_authenticated(request):
                if not api:
                    raise UnauthorizedException('Should be logged in')
                else:
                    return rc.FORBIDDEN

            if 'key' in kwargs:
                text = get_object_or_404(Text, key=kwargs['key'])
            else:
                raise Exception('no security check possible')

            # in api, the view has an object as first parameter, request is args[0]
            if not api:
                req = request
            else:
                req = args[0]
            if has_perm(req, perm_name, text=text):
                return view_func(request, *args, **kwargs)
            #else:
            # TODO: (? useful ?) if some user have the perm and not logged-in : redirect to login
            #if not request.user.is_authenticated() and number_has_perm_on_text(permission, text_id) > 0:
            #    return HttpResponseRedirect('%s?%s=%s' % (login_url, redirect_field_name, urlquote(request.get_full_path())))
            # else : unauthorized

            if not api:
                raise UnauthorizedException('No perm %s' % perm_name)
            else:
                return rc.FORBIDDEN
コード例 #9
0
 def render(self, context):
     context[self.var_name] = has_perm(
         self.request.resolve(context),
         self.perm_name,
         None,
     )
     return ''
コード例 #10
0
def has_own_perm(request, perm_name, text, comment):

    user = get_request_user(request)

    if not user:
        return False

    # bypass sec if NO_SECURITY
    if cm_settings.NO_SECURITY:
        return True

    # make sure perm exist
    assert Permission.objects.get(codename=perm_name)

    # 2 special cases for comment own edition:

    # 1
    # if perm = can_edit_own_comment and
    # text is a priori moderated and
    # comment is approved and
    # don't have moderation rights and
    if comment and comment.state == 'approved' and \
       perm_name == 'can_edit_comment_own' and \
       text.last_text_version.mod_posteriori == False and \
       not has_perm(request, 'can_manage_text', text=text):
        return False

    # 2
    # if perm = can_edit_own_comment and and
    # text is a posteriori moderated and
    # there is a reply
    # don't have moderation rights and
    if comment and comment.state == 'approved' and \
       perm_name == 'can_edit_comment_own' and \
       text.last_text_version.mod_posteriori == True and \
       comment.comment_set.count() != 0 and \
       not has_perm(request, 'can_manage_text', text=text):
        return False

    actual_own_user = False
    if comment.user == request.user:
        if DECORATED_CREATORS:
            if request.GET.get('name', None) == comment.get_name():
                actual_own_user = True
        else:
            actual_own_user = True
    return (actual_own_user and has_perm(request, perm_name, text=text))
コード例 #11
0
ファイル: security.py プロジェクト: clarkcui89/papermache
def has_own_perm(request, perm_name, text, comment):
    
    user = get_request_user(request)
    
    if not user:
        return False
    
    # bypass sec if NO_SECURITY
    if cm_settings.NO_SECURITY:
        return True
    
    # make sure perm exist
    assert Permission.objects.get(codename=perm_name)
    
    # 2 special cases for comment own edition:
    
    # 1
    # if perm = can_edit_own_comment and 
    # text is a priori moderated and
    # comment is approved and
    # don't have moderation rights and
    if comment and comment.state == 'approved' and \
       perm_name == 'can_edit_comment_own' and \
       text.last_text_version.mod_posteriori == False and \
       not has_perm(request, 'can_manage_text', text=text):
        return False
    
    # 2       
    # if perm = can_edit_own_comment and and 
    # text is a posteriori moderated and
    # there is a reply
    # don't have moderation rights and
    if comment and comment.state == 'approved' and \
       perm_name == 'can_edit_comment_own' and \
       text.last_text_version.mod_posteriori == True and \
       comment.comment_set.count() != 0 and \
       not has_perm(request, 'can_manage_text', text=text):
        return False
    
    actual_own_user = False
    if comment.user == request.user:
      if DECORATED_CREATORS:
        if request.GET.get('name', None) == comment.get_name():
          actual_own_user = True
      else:
        actual_own_user = True
    return (actual_own_user and has_perm(request, perm_name, text=text)) 
コード例 #12
0
ファイル: security.py プロジェクト: debon/comt
 def _check_global_perm(request, *args, **kwargs):
     if must_be_logged_in and not is_authenticated(request):
         raise UnauthorizedException('Should be logged in')
     
     if has_perm(request, perm_name, text=None): 
         return view_func(request, *args, **kwargs)
     
     raise UnauthorizedException('No global perm %s' % perm_name)
コード例 #13
0
ファイル: security.py プロジェクト: ovnicraft/comt
        def _check_global_perm(request, *args, **kwargs):
            if must_be_logged_in and not is_authenticated(request):
                raise UnauthorizedException('Should be logged in')

            if has_perm(request, perm_name, text=None):
                return view_func(request, *args, **kwargs)

            raise UnauthorizedException('No global perm %s' % perm_name)
コード例 #14
0
def add_comment(request, key, version_key):
#    if edit_comment_id : #
#    if self.request.user.is_anonymous() : # accessing via an admin url ?
#    and comment.user == self.request.user
    user = None if request.user.is_anonymous() else request.user 
    name, email, title, content, tags, category, reply_to_id, format, start_wrapper, end_wrapper, start_offset, end_offset = read_comment_args(request)
    errors = {} 
    errors = validate_comment_args(name, email, title, content, tags)

    if start_wrapper == "" :
        errors['selection_place'] = selection_place_error_msg   

    #TODO validate pandoc conversion
    content_html = pandoc_convert(content, format, "html", full=False)
        
    ret = {} 
    if errors != {} :
        ret['errors'] = errors
    else :
    # INSERT
    # TODO check version still exist ...
        reply_to = None
        if reply_to_id :
            reply_to = Comment.objects.get(id=reply_to_id)
            
        text = Text.objects.get(key=key)
        text_version = TextVersion.objects.get(key=version_key)
        
        comment_state = 'approved' if text_version.mod_posteriori else 'pending'
        comment = Comment.objects.create(state=comment_state, text_version=text_version, user=user, name=name, email=email, title=title, content=content, content_html=content_html, tags = tags, category = category, start_wrapper = start_wrapper, end_wrapper = end_wrapper, start_offset = start_offset, end_offset = end_offset, reply_to=reply_to)
        
        ask_for_notification = True
        if user : 
            workspace_notify_count = Notification.objects.filter(text=None,type='workspace',user=user, active=True).count()
            text_notify_count = Notification.objects.filter(text=text,type='text',user=user, active=True).count()
            if workspace_notify_count > 0 or text_notify_count > 0 : 
                ask_for_notification = False

        if ask_for_notification :
            ask_for_notification = ( None == Notification.objects.get_notifications(text=None, type='own', email_or_user=(user if user else email)))
        ret['ask_for_notification'] = ask_for_notification
        ret['email'] = '' if user else email

        if text_version.mod_posteriori or has_perm(request, 'can_view_unapproved_comment', text=text) or has_perm(request, 'can_view_comment_own', text=text) : 
            ret['comment'] = comment
            ret['msg'] = _(u"comment saved")
        else :
            ret['msg'] = _(u"comment saved, it is being held for moderation")
        
        if AUTO_CONTRIB_REGISTER:
            Notification.objects.set_notification(text=text, type='own', active=True, email_or_user=user or email)            
        register_activity(request, "comment_created", text, comment)
        cache.clear()
    return ret
コード例 #15
0
ファイル: notifications.py プロジェクト: debon/comt
def notify(sender, **kwargs):
    from cm.security import get_viewable_comments, has_perm

    allready_notified = set()  # avoid sending multiple notifications to same user

    activity = kwargs["instance"]
    if activity.type in Activity.VIEWABLE_ACTIVITIES.get("view_users"):  # user activity: only viewed by managers
        notifications = Notification.objects.filter(text=None, active=True).exclude(type="own")
        for notification in notifications:
            if notification.user:
                from cm.security import user_has_perm  # import here!

                if user_has_perm(notification.user, "can_manage_workspace"):
                    send_notification(activity, notification)
                    allready_notified.add(notification.user)
    elif activity.type in Activity.VIEWABLE_ACTIVITIES.get("view_comments"):
        notifications = Notification.objects.filter(Q(text=activity.text) | Q(text=None), active=True)
        for notification in notifications:
            viewable = get_viewable_comments(
                FakeRequest(notification.user), Comment.objects.filter(id__in=[activity.comment.id]), text=activity.text
            )
            if viewable and (
                (
                    notification.type == "own"
                    and activity.comment.user != notification.user
                    and activity.comment.top_comment().user == notification.user
                )
                or (notification.type != "own")
            ):
                if not notification.user in allready_notified:
                    send_notification(activity, notification)
                    allready_notified.add(notification.user)
    elif activity.type in Activity.VIEWABLE_ACTIVITIES.get("view_texts"):
        notifications = Notification.objects.filter(Q(text=activity.text) | Q(text=None), active=True).exclude(
            type="own"
        )
        for notification in notifications:
            if notification.user:
                from cm.security import user_has_perm  # import here!

                if (
                    user_has_perm(notification.user, "can_view_text", text=activity.text)
                    and not notification.user in allready_notified
                ):
                    send_notification(activity, notification)
                    allready_notified.add(notification.user)
            else:
                if has_perm(None, "can_view_text", text=activity.text) and not notification.email in allready_notified:
                    send_notification(activity, notification)
                    allready_notified.add(notification.email)
コード例 #16
0
def notify(sender, **kwargs):
    from cm.security import get_viewable_comments, has_perm
    allready_notified = set(
    )  # avoid sending multiple notifications to same user

    activity = kwargs['instance']
    if activity.type in Activity.VIEWABLE_ACTIVITIES.get(
            'view_users'):  # user activity: only viewed by managers
        notifications = Notification.objects.filter(
            text=None, active=True).exclude(type='own')
        for notification in notifications:
            if notification.user:
                from cm.security import user_has_perm  # import here!
                if user_has_perm(notification.user, 'can_manage_workspace'):
                    send_notification(activity, notification)
                    allready_notified.add(notification.user)
    elif activity.type in Activity.VIEWABLE_ACTIVITIES.get('view_comments'):
        notifications = Notification.objects.filter(Q(text=activity.text)
                                                    | Q(text=None),
                                                    active=True)
        for notification in notifications:
            viewable = get_viewable_comments(
                FakeRequest(notification.user),
                Comment.objects.filter(id__in=[activity.comment.id]),
                text=activity.text)
            if viewable and \
                ((notification.type == 'own' and activity.comment.user != notification.user and activity.comment.top_comment().user == notification.user) or
                 (notification.type != 'own')):
                if not notification.user in allready_notified:
                    send_notification(activity, notification)
                    allready_notified.add(notification.user)
    elif activity.type in Activity.VIEWABLE_ACTIVITIES.get('view_texts'):
        notifications = Notification.objects.filter(
            Q(text=activity.text) | Q(text=None),
            active=True).exclude(type='own')
        for notification in notifications:
            if notification.user:
                from cm.security import user_has_perm  # import here!
                if user_has_perm(
                        notification.user, 'can_view_text', text=activity.text
                ) and not notification.user in allready_notified:
                    send_notification(activity, notification)
                    allready_notified.add(notification.user)
            else:
                if has_perm(None, 'can_view_text', text=activity.text
                            ) and not notification.email in allready_notified:
                    send_notification(activity, notification)
                    allready_notified.add(notification.email)
コード例 #17
0
ファイル: texts.py プロジェクト: clarkcui89/papermache
def text_list(request):
    paginate_by = get_int(request.GET,'paginate',TEXT_PAGINATION)
    tag_selected = request.GET.get('tag_selected', 0)
        
    order_by = get_among(request.GET,'order',('title','author','modified','-title','-author','-modified'),'-modified')

    if request.method == 'POST':
        action = request.POST.get('action',None)
        text_keys = get_keys_from_dict(request.POST, 'check-').keys()        
        if action == 'delete':
            for text_key in text_keys:
                text = Text.objects.get(key=text_key)
                if has_perm(request, 'can_delete_text', text=text):
                    text.delete()
                else:
                    raise UnauthorizedException('No perm can_delete_text on comment') 
            display_message(request, _(u'%(nb_texts)i text(s) deleted') %{'nb_texts':len(text_keys)})
            return HttpResponseRedirect(reverse('text'))

    texts = get_texts_with_perm(request, 'can_view_text').order_by(order_by)

    try:
        tag_list = Tag.objects.usage_for_queryset(TextVersion.objects.filter(id__in = [t.last_text_version_id for t in get_texts_with_perm(request, 'can_view_text')]))
    except EmptyResultSet:
        tag_list = []
    context = {    
               'tag_list' : tag_list,
               'tag_selected': tag_selected,
               }

    if tag_selected:     
        tag_ids = Tag.objects.filter(name=tag_selected)
        if tag_ids:   
            content_type_id = ContentType.objects.get_for_model(TextVersion).pk
            # table cm_userprofile is not present if display_suspended_users: fix this 
            texts = texts.extra(where=['tagging_taggeditem.object_id = cm_text.last_text_version_id', 
                                       'tagging_taggeditem.content_type_id = %i' %content_type_id,
                                       'tagging_taggeditem.tag_id = %i' %tag_ids[0].id],
                                tables=['tagging_taggeditem'],
                                )
    
    return object_list(request, texts,
                       template_name = 'site/text_list.html',
                       paginate_by = paginate_by,
                       extra_context=context,
                       )
コード例 #18
0
ファイル: security.py プロジェクト: debon/comt
        def _check_local_perm(request, *args, **kwargs):
            if cm_settings.NO_SECURITY:
                return view_func(request, *args, **kwargs)
            
            if 'key' in kwargs: 
                text = get_object_or_404(Text, key=kwargs['key'])
                # first try permission on text                
                if has_perm(request, perm_name, text=text) :
                    return view_func(request, *args, **kwargs)
                if 'comment_key' in kwargs:
                    comment = get_object_or_404(Comment, key=kwargs['comment_key'])
                    if has_own_perm(request, perm_name + "_own", text, comment) :
                        return view_func(request, *args, **kwargs)
                else:
                    raise Exception('no security check possible: no comment key')
            else:
                raise Exception('no security check possible: no text key')

            raise UnauthorizedException('No perm %s on comment' % perm_name)
コード例 #19
0
ファイル: security.py プロジェクト: debon/comt
def get_viewable_activities(request=None, act_types={}, text=None):
    """
    Get activities user in request is allowed to see
    """
    from cm.security import has_perm, get_texts_with_perm, get_viewable_comments
    
    selected_activities = reduce(list.__add__,[Activity.VIEWABLE_ACTIVITIES[k] for k in act_types.keys() if act_types[k]], [])
    
    activities = Activity.objects.filter(type__in=selected_activities)
    if text:
        activities = activities.filter(text=text)
        
    if not has_perm(request, 'can_manage_workspace'):
        texts = get_texts_with_perm(request, 'can_view_text')
        activities = activities.filter(Q(text__in=texts))
        
        comments = [] 
        [comments.extend(get_viewable_comments(request, t.last_text_version.comment_set.all(), t)) for t in texts]

        activities = activities.filter(Q(comment__in=comments) | Q(comment=None))
    return activities.order_by('-created')
コード例 #20
0
ファイル: security.py プロジェクト: ovnicraft/comt
        def _check_local_perm(request, *args, **kwargs):
            if cm_settings.NO_SECURITY:
                return view_func(request, *args, **kwargs)

            if 'key' in kwargs:
                text = get_object_or_404(Text, key=kwargs['key'])
                # first try permission on text
                if has_perm(request, perm_name, text=text):
                    return view_func(request, *args, **kwargs)
                if 'comment_key' in kwargs:
                    comment = get_object_or_404(Comment,
                                                key=kwargs['comment_key'])
                    if has_own_perm(request, perm_name + "_own", text,
                                    comment):
                        return view_func(request, *args, **kwargs)
                else:
                    raise Exception(
                        'no security check possible: no comment key')
            else:
                raise Exception('no security check possible: no text key')

            raise UnauthorizedException('No perm %s on comment' % perm_name)
コード例 #21
0
ファイル: local_perms.py プロジェクト: clarkcui89/papermache
 def render(self, context):
     context[self.var_name] =  has_perm(self.request.resolve(context),
                                        self.perm_name,
                                        None,
                                        )        
     return ''
コード例 #22
0
ファイル: security.py プロジェクト: ovnicraft/comt
def get_viewable_comments(request, comments, text, order_by=('created', )):
    """
    Get comments visibles by user
    comments: queryset
    """
    user = get_request_user(request)
    try:
        myself = request.GET.get('name', None)
    except AttributeError:
        myself = None
    key = sha1(
        str((settings.SITE_URL, 'get_viewable_comments',
             (user, myself, text, comments)))).hexdigest()
    val = cache.get(key)
    if val != None:
        return val

    if user and has_perm(request, 'can_view_unapproved_comment', text=text):
        ret = list(comments.order_by(*order_by))
        cache.set(key, ret)
        return ret
    else:
        # Fetch role_model to process specific behaviour for role_teacher model
        from cm.models import ApplicationConfiguration
        role_model = ApplicationConfiguration.get_key('workspace_role_model')

        if has_perm(request, 'can_view_approved_comment', text=text):
            visible_comments = comments.filter(state='approved').order_by(
                *order_by)
            # filter comments with a non visible (i.e. moderated) comment in the above thread
            comments_thread_viewable = [
                c for c in visible_comments if c.is_thread_full_visible()
            ]

            # for role_teacher role model, do not show 'individual student' comments
            if (role_model == 'teacher'):
                unfiltered_comments = list(comments_thread_viewable)
                for c in unfiltered_comments:
                    if c.user_id and c.user_id != 1:
                        try:
                            userrole = UserRole.objects.get(user=c.user,
                                                            text=text)
                        except:
                            userrole = UserRole.objects.get(user=None,
                                                            text=None)
                        if userrole.role_id == None:
                            role = c.user.get_profile().global_userrole().role
                        else:
                            role = userrole.role
                        if role.name == 'Individual student':
                            comments_thread_viewable.remove(c)
            cache.set(key, comments_thread_viewable)
            return comments_thread_viewable
        elif user and has_perm(request, 'can_view_comment_own', text=text):
            if DECORATED_CREATORS:
                visible_comments = comments.filter(name=myself).order_by(
                    *order_by)
            else:
                visible_comments = comments.filter(user=user).order_by(
                    *order_by)

            # for role_teacher role model, add 'teacher' comments
            if (role_model == 'teacher'):
                with_teachers = []
                for u in list(
                        User.objects.filter(userrole__role__name='Teacher')):
                    with_teachers.append(u.id)

                # add admin and current user
                admin = User.objects.get(id=1)
                with_teachers.append(admin.id)
                if DECORATED_CREATORS:
                    visible_comments = comments.filter(
                        Q(user__id__in=with_teachers)
                        | Q(name=myself)).order_by(*order_by)
                else:
                    with_teachers.append(user.id)
                    visible_comments = comments.filter(
                        user__id__in=with_teachers).order_by(*order_by)

            # filter comments with a non visible (i.e. moderated) comment in the above thread
            comments_thread_viewable = [
                c for c in visible_comments
                if c.is_thread_full_visible(own_user=user)
            ]
            cache.set(key, comments_thread_viewable)
            return comments_thread_viewable
        else:
            cache.set(key, [])
            return []
コード例 #23
0
ファイル: texts.py プロジェクト: clarkcui89/papermache
def dashboard(request):
    request.session.set_test_cookie()
    if request.user.is_authenticated():
        act_view = {
                    'view_texts' : get_int(request.GET, 'view_texts',1),
                    'view_comments' : get_int(request.GET, 'view_comments',1),
                    'view_users' : get_int(request.GET, 'view_users',1),
                    }
            
        paginate_by = get_int(request.GET, 'paginate', ACTIVITY_PAGINATION)
                
        # texts with can_view_unapproved_comment perms
        moderator_texts = get_texts_with_perm(request, 'can_view_unapproved_comment')
        viewer_texts = get_texts_with_perm(request, 'can_view_approved_comment')
        all_texts_ids = [t.id for t in moderator_texts] + [t.id for t in viewer_texts]
                    
        span = get_among(request.GET, 'span', ('day','month','week',),'week')        
        template_dict = { 
                         'span' : span,
                         'last_texts' : get_texts_with_perm(request, 'can_view_text').order_by('-modified')[:RECENT_TEXT_NB],
                         'last_comments' : Comment.objects.filter(text_version__text__in=all_texts_ids).order_by('-created')[:RECENT_COMMENT_NB],# TODO: useful?
                         #'last_users' : User.objects.all().order_by('-date_joined')[:5],
                         }
        template_dict.update(act_view)
        
        all_activities = {
                               'view_comments' : ['comment_created','comment_removed'],
                               'view_users' : ['user_created', 'user_activated', 'user_suspended','user_enabled',],
                               'view_texts' : ['text_created','text_removed', 'text_edited', 'text_edited_new_version'],
                               }
        
        selected_activities = []
        [selected_activities.extend(all_activities[k]) for k in act_view.keys() if act_view[k]]
        
        activities = Activity.objects.filter(type__in = selected_activities)
        if not has_perm(request,'can_manage_workspace'):
            texts = get_texts_with_perm(request, 'can_view_text')
            activities = activities.filter(Q(text__in=texts))
            
            comments = [] 
            [comments.extend(get_viewable_comments(request, t.last_text_version.comment_set.all(), t)) for t in texts]

            activities = activities.filter(Q(comment__in=comments) | Q(comment=None) )
            template_dict['to_mod_profiles'] = []
        else:
            template_dict['to_mod_profiles'] = UserProfile.objects.filter(user__is_active=False).filter(is_suspended=True).order_by('-user__date_joined')[:MODERATE_NB]
        template_dict['to_mod_comments'] = Comment.objects.filter(state='pending').filter(text_version__text__in=moderator_texts).order_by('-modified')[:MODERATE_NB-len(template_dict['to_mod_profiles'])]

        activities = activities.order_by('-created')
        return object_list(request, activities,
                           template_name = 'site/dashboard.html',
                           paginate_by = paginate_by,
                           extra_context = template_dict,
                           )
        
    else:
        if request.method == 'POST':
            form = AuthenticationForm(request, request.POST)
            if form.is_valid():
                user = form.get_user()
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                cm_login(request, user)            
                display_message(request, _(u"You're logged in!"))
                return HttpResponseRedirect(reverse('index'))
        else:
            form = AuthenticationForm()        


        public_texts = get_texts_with_perm(request, 'can_view_text').order_by('-modified')

        template_dict = {
                         'form' : form,
                         'texts' : public_texts,
                         }
        return render_to_response('site/non_authenticated_index.html', template_dict, context_instance=RequestContext(request))
コード例 #24
0
ファイル: security.py プロジェクト: ovnicraft/comt
def user_has_perm(user, perm_name, text=None):
    return has_perm(FakeRequest(user), perm_name, text)
コード例 #25
0
ファイル: security.py プロジェクト: ovnicraft/comt
def has_own_perm(request, perm_name, text, comment):

    user = get_request_user(request)

    if not user:
        return False

    # bypass sec if NO_SECURITY
    if cm_settings.NO_SECURITY:
        return True

    # make sure perm exist
    assert Permission.objects.get(codename=perm_name)

    try:
        myself = request.GET.get('name', None)
    except AttributeError:
        myself = None
    key = sha1(
        str((settings.SITE_URL, 'has_own_perm', (user, myself, text, comment,
                                                 perm_name)))).hexdigest()
    val = cache.get(key)
    if val != None:
        return val

    # 2 special cases for comment own edition:

    # 1
    # if perm = can_edit_own_comment and
    # text is a priori moderated and
    # comment is approved and
    # don't have moderation rights and
    if comment and comment.state == 'approved' and \
       perm_name == 'can_edit_comment_own' and \
       text.last_text_version.mod_posteriori == False and \
       not has_perm(request, 'can_manage_text', text=text):
        cache.set(key, False)
        return False

    # 2
    # if perm = can_edit_own_comment and and
    # text is a posteriori moderated and
    # there is a reply
    # don't have moderation rights and
    if comment and comment.state == 'approved' and \
       perm_name == 'can_edit_comment_own' and \
       text.last_text_version.mod_posteriori == True and \
       comment.comment_set.count() != 0 and \
       not has_perm(request, 'can_manage_text', text=text):
        cache.set(key, False)
        return False

    actual_own_user = False
    if comment.user == request.user:
        if DECORATED_CREATORS:
            if myself == comment.get_name():
                actual_own_user = True
        else:
            actual_own_user = True
    ret = (actual_own_user and has_perm(request, perm_name, text=text))
    cache.set(key, ret)
    return ret
コード例 #26
0
ファイル: security.py プロジェクト: debon/comt
def get_viewable_comments(request, comments, text, order_by=('created',)):
    """
    Get comments visibles by user
    comments: queryset
    """
    user = get_request_user(request)
    try:
      myself = request.GET.get('name', None)
    except AttributeError:
      myself = None
    key = sha1(str((settings.SITE_URL, 'get_viewable_comments', (user, myself, text, comments)))).hexdigest()
    val = cache.get(key)
    if val != None:
      return val
        
    if user and has_perm(request, 'can_view_unapproved_comment', text=text):
        ret = list(comments.order_by(*order_by))
        cache.set(key, ret)
        return ret
    else:
        # Fetch role_model to process specific behaviour for role_teacher model
        from cm.models import ApplicationConfiguration
        role_model = ApplicationConfiguration.get_key('workspace_role_model')

        if has_perm(request, 'can_view_approved_comment', text=text):
            visible_comments = comments.filter(state = 'approved').order_by(*order_by)
            # filter comments with a non visible (i.e. moderated) comment in the above thread 
            comments_thread_viewable = [c for c in visible_comments if c.is_thread_full_visible()]

            # for role_teacher role model, do not show 'individual student' comments
            if (role_model == 'teacher'):
              unfiltered_comments = list(comments_thread_viewable)
              for c in unfiltered_comments:
                if c.user_id and c.user_id != 1:
                  try:
                    userrole = UserRole.objects.get(user=c.user, text=text)
                  except:
                    userrole = UserRole.objects.get(user=None, text=None)
                  if userrole.role_id == None:
                    role = c.user.get_profile().global_userrole().role
                  else:
                    role = userrole.role
                  if role.name == 'Individual student':
                    comments_thread_viewable.remove(c)
            cache.set(key, comments_thread_viewable)
            return comments_thread_viewable 
        elif user and has_perm(request, 'can_view_comment_own', text=text):
            if DECORATED_CREATORS:
              visible_comments = comments.filter(name=myself).order_by(*order_by)
            else:
              visible_comments = comments.filter(user=user).order_by(*order_by)

            # for role_teacher role model, add 'teacher' comments
            if (role_model == 'teacher'):
              with_teachers = []
              for u in list(User.objects.filter(userrole__role__name = 'Teacher')):
                with_teachers.append(u.id)

              # add admin and current user
              admin =  User.objects.get(id=1)
              with_teachers.append(admin.id)
              if DECORATED_CREATORS:
                visible_comments = comments.filter(Q(user__id__in=with_teachers) | Q(name=myself)).order_by(*order_by)
              else:
                with_teachers.append(user.id)
                visible_comments = comments.filter(user__id__in=with_teachers).order_by(*order_by)

            # filter comments with a non visible (i.e. moderated) comment in the above thread 
            comments_thread_viewable = [c for c in visible_comments if c.is_thread_full_visible(own_user=user)]
            cache.set(key, comments_thread_viewable)
            return comments_thread_viewable                
        else:
            cache.set(key, [])
            return []
コード例 #27
0
ファイル: security.py プロジェクト: debon/comt
def user_has_perm(user, perm_name, text=None):
    return has_perm(FakeRequest(user),perm_name, text)