Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / user-update.py @ 9eafaa32

History | View | Annotate | Download (9.4 kB)

1
# Copyright 2012 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from optparse import make_option
35
from datetime import datetime
36

    
37
from django.core.management.base import BaseCommand, CommandError
38
from django.core.exceptions import ValidationError
39
from django.db.utils import IntegrityError
40

    
41
from astakos.im.models import (AstakosUser, AstakosGroup, Membership, Resource,
42
                               AstakosUserQuota)
43
from astakos.im.endpoints.aquarium.producer import report_user_credits_event
44
from ._common import remove_user_permission, add_user_permission
45

    
46

    
47
class Command(BaseCommand):
48
    args = "<user ID>"
49
    help = "Modify a user's attributes"
50

    
51
    option_list = list(BaseCommand.option_list) + [
52
        make_option('--invitations',
53
                    dest='invitations',
54
                    metavar='NUM',
55
                    help="Update user's invitations"),
56
        make_option('--level',
57
                    dest='level',
58
                    metavar='NUM',
59
                    help="Update user's level"),
60
        make_option('--password',
61
                    dest='password',
62
                    metavar='PASSWORD',
63
                    help="Set user's password"),
64
        make_option('--provider',
65
                    dest='provider',
66
                    metavar='PROVIDER',
67
                    help="Set user's provider"),
68
        make_option('--renew-token',
69
                    action='store_true',
70
                    dest='renew_token',
71
                    default=False,
72
                    help="Renew the user's token"),
73
        make_option('--renew-password',
74
                    action='store_true',
75
                    dest='renew_password',
76
                    default=False,
77
                    help="Renew the user's password"),
78
        make_option('--set-admin',
79
                    action='store_true',
80
                    dest='admin',
81
                    default=False,
82
                    help="Give user admin rights"),
83
        make_option('--set-noadmin',
84
                    action='store_true',
85
                    dest='noadmin',
86
                    default=False,
87
                    help="Revoke user's admin rights"),
88
        make_option('--set-active',
89
                    action='store_true',
90
                    dest='active',
91
                    default=False,
92
                    help="Change user's state to inactive"),
93
        make_option('--set-inactive',
94
                    action='store_true',
95
                    dest='inactive',
96
                    default=False,
97
                    help="Change user's state to inactive"),
98
        make_option('--add-group',
99
                    dest='add-group',
100
                    help="Add user group"),
101
        make_option('--delete-group',
102
                    dest='delete-group',
103
                    help="Delete user group"),
104
        make_option('--add-permission',
105
                    dest='add-permission',
106
                    help="Add user permission"),
107
        make_option('--delete-permission',
108
                    dest='delete-permission',
109
                    help="Delete user permission"),
110
        make_option('--refill-credits',
111
                    action='store_true',
112
                    dest='refill',
113
                    default=False,
114
                    help="Refill user credits"),
115
    ]
116
    resources = Resource.objects.select_related().all()
117
    append = option_list.append
118
    for r in resources:
119
        append(make_option('--%s-set-quota' % r,
120
                    dest='%s-set-quota' % r,
121
                    metavar='QUANTITY',
122
                    help="Set resource quota"))
123
    
124
    def handle(self, *args, **options):
125
        if len(args) != 1:
126
            raise CommandError("Please provide a user ID")
127

    
128
        if args[0].isdigit():
129
            user = AstakosUser.objects.get(id=int(args[0]))
130
        else:
131
            raise CommandError("Invalid ID")
132

    
133
        if not user:
134
            raise CommandError("Unknown user")
135

    
136
        if options.get('admin'):
137
            user.is_superuser = True
138
        elif options.get('noadmin'):
139
            user.is_superuser = False
140

    
141
        if options.get('active'):
142
            user.is_active = True
143
        elif options.get('inactive'):
144
            user.is_active = False
145

    
146
        invitations = options.get('invitations')
147
        if invitations is not None:
148
            user.invitations = int(invitations)
149

    
150
        groupname = options.get('add-group')
151
        if groupname is not None:
152
            try:
153
                group = AstakosGroup.objects.get(name=groupname)
154
                m = Membership(
155
                    person=user, group=group, date_joined=datetime.now())
156
                m.save()
157
            except AstakosGroup.DoesNotExist, e:
158
                self.stdout.write(
159
                    "Group named %s does not exist\n" % groupname)
160
            except IntegrityError, e:
161
                self.stdout.write("User is already member of %s\n" % groupname)
162

    
163
        groupname = options.get('delete-group')
164
        if groupname is not None:
165
            try:
166
                group = AstakosGroup.objects.get(name=groupname)
167
                m = Membership.objects.get(person=user, group=group)
168
                m.delete()
169
            except AstakosGroup.DoesNotExist, e:
170
                self.stdout.write(
171
                    "Group named %s does not exist\n" % groupname)
172
            except Membership.DoesNotExist, e:
173
                self.stdout.write("User is not a member of %s\n" % groupname)
174

    
175
        pname = options.get('add-permission')
176
        if pname is not None:
177
            try:
178
                r, created = add_user_permission(user, pname)
179
                if created:
180
                    self.stdout.write(
181
                        'Permission: %s created successfully\n' % pname)
182
                if r > 0:
183
                    self.stdout.write(
184
                        'Permission: %s added successfully\n' % pname)
185
                elif r == 0:
186
                    self.stdout.write(
187
                        'User has already permission: %s\n' % pname)
188
            except Exception, e:
189
                raise CommandError(e)
190

    
191
        pname = options.get('delete-permission')
192
        if pname is not None and not user.has_perm(pname):
193
            try:
194
                r = remove_user_permission(user, pname)
195
                if r < 0:
196
                    self.stdout.write(
197
                        'Invalid permission codename: %s\n' % pname)
198
                elif r == 0:
199
                    self.stdout.write('User has not permission: %s\n' % pname)
200
                elif r > 0:
201
                    self.stdout.write(
202
                        'Permission: %s removed successfully\n' % pname)
203
            except Exception, e:
204
                raise CommandError(e)
205

    
206
        level = options.get('level')
207
        if level is not None:
208
            user.level = int(level)
209

    
210
        password = options.get('password')
211
        if password is not None:
212
            user.set_password(password)
213

    
214
        provider = options.get('provider')
215
        if provider is not None:
216
            user.provider = provider
217

    
218
        password = None
219
        if options['renew_password']:
220
            password = AstakosUser.objects.make_random_password()
221
            user.set_password(password)
222

    
223
        if options['renew_token']:
224
            user.renew_token()
225

    
226
        if options['refill']:
227
            report_user_credits_event(user)
228

    
229
        try:
230
            user.save()
231
        except ValidationError, e:
232
            raise CommandError(e)
233

    
234
        if password:
235
            self.stdout.write('User\'s new password: %s\n' % password)
236
        
237
        for r in self.resources:
238
            limit = options.get('%s-set-quota' % r)
239
            if not limit:
240
                continue
241
            if not limit.isdigit():
242
                raise CommandError('Invalid limit')
243
            
244
            q = AstakosUserQuota.objects
245
            q, created = q.get_or_create(resource=r, user=user,
246
                                         defaults={'uplimit': limit})
247
            verb = 'set' if created else 'updated'
248
            self.stdout.write('User\'s quota %s successfully\n' % verb)