Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / user_update.py @ fc1e2f02

History | View | Annotate | Download (8.1 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
42
from astakos.im.endpoints.aquarium.producer import report_user_credits_event
43
from ._common import remove_user_permission, add_user_permission
44

    
45
class Command(BaseCommand):
46
    args = "<user ID>"
47
    help = "Modify a user's attributes"
48
    
49
    option_list = BaseCommand.option_list + (
50
        make_option('--invitations',
51
            dest='invitations',
52
            metavar='NUM',
53
            help="Update user's invitations"),
54
        make_option('--level',
55
            dest='level',
56
            metavar='NUM',
57
            help="Update user's level"),
58
        make_option('--password',
59
            dest='password',
60
            metavar='PASSWORD',
61
            help="Set user's password"),
62
        make_option('--provider',
63
            dest='provider',
64
            metavar='PROVIDER',
65
            help="Set user's provider"),
66
        make_option('--renew-token',
67
            action='store_true',
68
            dest='renew_token',
69
            default=False,
70
            help="Renew the user's token"),
71
        make_option('--renew-password',
72
            action='store_true',
73
            dest='renew_password',
74
            default=False,
75
            help="Renew the user's password"),
76
        make_option('--set-admin',
77
            action='store_true',
78
            dest='admin',
79
            default=False,
80
            help="Give user admin rights"),
81
        make_option('--set-noadmin',
82
            action='store_true',
83
            dest='noadmin',
84
            default=False,
85
            help="Revoke user's admin rights"),
86
        make_option('--set-active',
87
            action='store_true',
88
            dest='active',
89
            default=False,
90
            help="Change user's state to inactive"),
91
        make_option('--set-inactive',
92
            action='store_true',
93
            dest='inactive',
94
            default=False,
95
            help="Change user's state to inactive"),
96
        make_option('--add-group',
97
            dest='add-group',
98
            help="Add user group"),
99
        make_option('--delete-group',
100
            dest='delete-group',
101
            help="Delete user group"),
102
        make_option('--add-permission',
103
            dest='add-permission',
104
            help="Add user permission"),
105
        make_option('--delete-permission',
106
            dest='delete-permission',
107
            help="Delete user permission"),
108
        make_option('--refill-credits',
109
            action='store_true',
110
            dest='refill',
111
            default=False,
112
            help="Refill user credits"),
113
        )
114
    
115
    def handle(self, *args, **options):
116
        if len(args) != 1:
117
            raise CommandError("Please provide a user ID")
118
        
119
        if args[0].isdigit():
120
            user = AstakosUser.objects.get(id=int( args[0]))
121
        else:
122
            raise CommandError("Invalid ID")
123
        
124
        if not user:
125
            raise CommandError("Unknown user")
126
        
127
        if options.get('admin'):
128
            user.is_superuser = True
129
        elif options.get('noadmin'):
130
            user.is_superuser = False
131
        
132
        if options.get('active'):
133
            user.is_active = True
134
        elif options.get('inactive'):
135
            user.is_active = False
136
        
137
        invitations = options.get('invitations')
138
        if invitations is not None:
139
            user.invitations = int(invitations)
140
        
141
        groupname = options.get('add-group')
142
        if groupname is not None:
143
            try:
144
                group = AstakosGroup.objects.get(name=groupname)
145
                m = Membership(person=user, group=group, date_joined=datetime.now())
146
                m.save()
147
            except AstakosGroup.DoesNotExist, e:
148
                self.stdout.write("Group named %s does not exist\n" % groupname)
149
            except IntegrityError, e:
150
                self.stdout.write("User is already member of %s\n" % groupname)
151
        
152
        groupname = options.get('delete-group')
153
        if groupname is not None:
154
            try:
155
                group = AstakosGroup.objects.get(name=groupname)
156
                m = Membership.objects.get(person=user, group=group)
157
                m.delete()
158
            except AstakosGroup.DoesNotExist, e:
159
                self.stdout.write("Group named %s does not exist\n" % groupname)
160
            except Membership.DoesNotExist, e:
161
                self.stdout.write("User is not a member of %s\n" % groupname)
162
        
163
        pname = options.get('add-permission')
164
        if pname is not None:
165
            try:
166
                r, created = add_user_permission(user, pname)
167
                if created:
168
                    self.stdout.write('Permission: %s created successfully\n' % pname)
169
                if r > 0:
170
                    self.stdout.write('Permission: %s added successfully\n' % pname)
171
                elif r==0:
172
                    self.stdout.write('User has already permission: %s\n' % pname)
173
            except Exception, e:
174
                raise CommandError(e)
175
        
176
        pname  = options.get('delete-permission')
177
        if pname is not None and not user.has_perm(pname):
178
            try:
179
                r = remove_user_permission(user, pname)
180
                if r < 0:
181
                    self.stdout.write('Invalid permission codename: %s\n' % pname)
182
                elif r == 0:
183
                    self.stdout.write('User has not permission: %s\n' % pname)
184
                elif r > 0:
185
                    self.stdout.write('Permission: %s removed successfully\n' % pname)
186
            except Exception, e:
187
                raise CommandError(e)
188
        
189
        level = options.get('level')
190
        if level is not None:
191
            user.level = int(level)
192
        
193
        password = options.get('password')
194
        if password is not None:
195
            user.set_password(password)
196
        
197
        provider = options.get('provider')
198
        if provider is not None:
199
            user.provider = provider
200
        
201
        
202
        password = None
203
        if options['renew_password']:
204
            password = AstakosUser.objects.make_random_password()
205
            user.set_password(password)
206
        
207
        if options['renew_token']:
208
            user.renew_token()
209
        
210
        if options['refill']:
211
            report_user_credits_event(user)
212
        
213
        try:
214
            user.save()
215
        except ValidationError, e:
216
            raise CommandError(e)
217
        
218
        if password:
219
            self.stdout.write('User\'s new password: %s\n' % password)