Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / user-update.py @ 6bdf0aa3

History | View | Annotate | Download (8.5 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

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

    
50
    option_list = BaseCommand.option_list + (
51
        make_option('--invitations',
52
                    dest='invitations',
53
                    metavar='NUM',
54
                    help="Update user's invitations"),
55
        make_option('--level',
56
                    dest='level',
57
                    metavar='NUM',
58
                    help="Update user's level"),
59
        make_option('--password',
60
                    dest='password',
61
                    metavar='PASSWORD',
62
                    help="Set user's password"),
63
        make_option('--provider',
64
                    dest='provider',
65
                    metavar='PROVIDER',
66
                    help="Set user's provider"),
67
        make_option('--renew-token',
68
                    action='store_true',
69
                    dest='renew_token',
70
                    default=False,
71
                    help="Renew the user's token"),
72
        make_option('--renew-password',
73
                    action='store_true',
74
                    dest='renew_password',
75
                    default=False,
76
                    help="Renew the user's password"),
77
        make_option('--set-admin',
78
                    action='store_true',
79
                    dest='admin',
80
                    default=False,
81
                    help="Give user admin rights"),
82
        make_option('--set-noadmin',
83
                    action='store_true',
84
                    dest='noadmin',
85
                    default=False,
86
                    help="Revoke user's admin rights"),
87
        make_option('--set-active',
88
                    action='store_true',
89
                    dest='active',
90
                    default=False,
91
                    help="Change user's state to inactive"),
92
        make_option('--set-inactive',
93
                    action='store_true',
94
                    dest='inactive',
95
                    default=False,
96
                    help="Change user's state to inactive"),
97
        make_option('--add-group',
98
                    dest='add-group',
99
                    help="Add user group"),
100
        make_option('--delete-group',
101
                    dest='delete-group',
102
                    help="Delete user group"),
103
        make_option('--add-permission',
104
                    dest='add-permission',
105
                    help="Add user permission"),
106
        make_option('--delete-permission',
107
                    dest='delete-permission',
108
                    help="Delete user permission"),
109
        make_option('--refill-credits',
110
                    action='store_true',
111
                    dest='refill',
112
                    default=False,
113
                    help="Refill user credits"),
114
    )
115

    
116
    def handle(self, *args, **options):
117
        if len(args) != 1:
118
            raise CommandError("Please provide a user ID")
119

    
120
        if args[0].isdigit():
121
            user = AstakosUser.objects.get(id=int(args[0]))
122
        else:
123
            raise CommandError("Invalid ID")
124

    
125
        if not user:
126
            raise CommandError("Unknown user")
127

    
128
        if options.get('admin'):
129
            user.is_superuser = True
130
        elif options.get('noadmin'):
131
            user.is_superuser = False
132

    
133
        if options.get('active'):
134
            user.is_active = True
135
        elif options.get('inactive'):
136
            user.is_active = False
137

    
138
        invitations = options.get('invitations')
139
        if invitations is not None:
140
            user.invitations = int(invitations)
141

    
142
        groupname = options.get('add-group')
143
        if groupname is not None:
144
            try:
145
                group = AstakosGroup.objects.get(name=groupname)
146
                m = Membership(
147
                    person=user, group=group, date_joined=datetime.now())
148
                m.save()
149
            except AstakosGroup.DoesNotExist, e:
150
                self.stdout.write(
151
                    "Group named %s does not exist\n" % groupname)
152
            except IntegrityError, e:
153
                self.stdout.write("User is already member of %s\n" % groupname)
154

    
155
        groupname = options.get('delete-group')
156
        if groupname is not None:
157
            try:
158
                group = AstakosGroup.objects.get(name=groupname)
159
                m = Membership.objects.get(person=user, group=group)
160
                m.delete()
161
            except AstakosGroup.DoesNotExist, e:
162
                self.stdout.write(
163
                    "Group named %s does not exist\n" % groupname)
164
            except Membership.DoesNotExist, e:
165
                self.stdout.write("User is not a member of %s\n" % groupname)
166

    
167
        pname = options.get('add-permission')
168
        if pname is not None:
169
            try:
170
                r, created = add_user_permission(user, pname)
171
                if created:
172
                    self.stdout.write(
173
                        'Permission: %s created successfully\n' % pname)
174
                if r > 0:
175
                    self.stdout.write(
176
                        'Permission: %s added successfully\n' % pname)
177
                elif r == 0:
178
                    self.stdout.write(
179
                        'User has already permission: %s\n' % pname)
180
            except Exception, e:
181
                raise CommandError(e)
182

    
183
        pname = options.get('delete-permission')
184
        if pname is not None and not user.has_perm(pname):
185
            try:
186
                r = remove_user_permission(user, pname)
187
                if r < 0:
188
                    self.stdout.write(
189
                        'Invalid permission codename: %s\n' % pname)
190
                elif r == 0:
191
                    self.stdout.write('User has not permission: %s\n' % pname)
192
                elif r > 0:
193
                    self.stdout.write(
194
                        'Permission: %s removed successfully\n' % pname)
195
            except Exception, e:
196
                raise CommandError(e)
197

    
198
        level = options.get('level')
199
        if level is not None:
200
            user.level = int(level)
201

    
202
        password = options.get('password')
203
        if password is not None:
204
            user.set_password(password)
205

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

    
210
        password = None
211
        if options['renew_password']:
212
            password = AstakosUser.objects.make_random_password()
213
            user.set_password(password)
214

    
215
        if options['renew_token']:
216
            user.renew_token()
217

    
218
        if options['refill']:
219
            report_user_credits_event(user)
220

    
221
        try:
222
            user.save()
223
        except ValidationError, e:
224
            raise CommandError(e)
225

    
226
        if password:
227
            self.stdout.write('User\'s new password: %s\n' % password)