Revision 30dc8c1a snf-astakos-app/astakos/im/management/commands/_common.py

b/snf-astakos-app/astakos/im/management/commands/_common.py
34 34
from datetime import datetime
35 35

  
36 36
from django.utils.timesince import timesince, timeuntil
37
from django.contrib.auth.models import Permission
38
from django.contrib.contenttypes.models import ContentType
37 39

  
38 40
from astakos.im.models import AstakosUser
39 41

  
42
content_type = None
40 43

  
41 44
def get_user(email_or_id, **kwargs):
42 45
    try:
......
59 62
        return timesince(d) + ' ago'
60 63
    else:
61 64
        return 'in ' + timeuntil(d)
65

  
66
def get_astakosuser_content_type():
67
    if content_type:
68
        return content_type
69
    
70
    try:
71
        return ContentType.objects.get(app_label='im',
72
                                       model='astakosuser')
73
    except:
74
        return content_type
75
    
76
def add_user_permission(user, pname):
77
    content_type = get_astakosuser_content_type()
78
    if user.has_perm(pname):
79
        return 0, None
80
    p, created = Permission.objects.get_or_create(codename=pname,
81
                                                  name=pname.capitalize(),
82
                                                  content_type=content_type)
83
    user.user_permissions.add(p)
84
    return 1, created
85

  
86
def add_group_permission(group, pname):
87
    content_type = get_astakosuser_content_type()
88
    if pname in [p.codename for p in group.permissions.all()]:
89
        return 0, None
90
    content_type = ContentType.objects.get(app_label='im',
91
                                           model='astakosuser')
92
    p, created = Permission.objects.get_or_create(codename=pname,
93
                                                  name=pname.capitalize(),
94
                                                  content_type=content_type)
95
    group.permissions.add(p)
96
    return 1, created
97

  
98
def remove_user_permission(user, pname):
99
    content_type = get_astakosuser_content_type()
100
    if user.has_perm(pname):
101
        return 0
102
    try:
103
        p = Permission.objects.get(codename=pname,
104
                                    content_type=content_type)
105
        user.user_permissions.remove(p)
106
        return 1
107
    except Permission.DoesNotExist, e:
108
        return -1
109

  
110
def remove_group_permission(group, pname):
111
    content_type = get_astakosuser_content_type()
112
    if pname not in [p.codename for p in group.permissions.all()]:
113
        return 0
114
    try:
115
        p = Permission.objects.get(codename=pname,
116
                                    content_type=content_type)
117
        group.permissions.remove(p)
118
        return 1
119
    except Permission.DoesNotExist, e:
120
        return -1

Also available in: Unified diff