Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / user-modify.py @ 71b37f75

History | View | Annotate | Download (8.7 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.utils.translation import ugettext as _
38
from django.core.management.base import BaseCommand, CommandError
39
from django.contrib.auth.models import Group
40
from django.core.exceptions import ValidationError
41

    
42
from astakos.im.models import AstakosUser
43
from astakos.im.functions import (activate, deactivate,
44
                                  set_pending_application_limit,
45
                                  unset_pending_application_limit)
46
from ._common import remove_user_permission, add_user_permission
47

    
48

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

    
53
    option_list = BaseCommand.option_list + (
54
        make_option('--invitations',
55
                    dest='invitations',
56
                    metavar='NUM',
57
                    help="Update user's invitations"),
58
        make_option('--level',
59
                    dest='level',
60
                    metavar='NUM',
61
                    help="Update user's level"),
62
        make_option('--password',
63
                    dest='password',
64
                    metavar='PASSWORD',
65
                    help="Set user's password"),
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 active"),
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('--set-max-pending',
109
                    dest='pending',
110
                    metavar='INT',
111
                    help=("Set limit on user's maximum pending "
112
                          "project applications")),
113
        make_option('--unset-max-pending',
114
                    dest='unset_pending',
115
                    action='store_true',
116
                    default=False,
117
                    help=("Restore default limit of user's maximum pending "
118
                          "project applications")),
119
    )
120

    
121
    def handle(self, *args, **options):
122
        if len(args) != 1:
123
            raise CommandError("Please provide a user ID")
124

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

    
131
        if not user:
132
            raise CommandError("Unknown user")
133

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

    
139
        if options.get('active'):
140
            activate(user)
141
        elif options.get('inactive'):
142
            deactivate(user)
143

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

    
148
        groupname = options.get('add-group')
149
        if groupname is not None:
150
            try:
151
                group = Group.objects.get(name=groupname)
152
                user.groups.add(group)
153
            except Group.DoesNotExist, e:
154
                self.stdout.write(
155
                    "Group named %s does not exist\n" % groupname)
156

    
157
        groupname = options.get('delete-group')
158
        if groupname is not None:
159
            try:
160
                group = Group.objects.get(name=groupname)
161
                user.groups.remove(group)
162
            except Group.DoesNotExist, e:
163
                self.stdout.write(
164
                    "Group named %s does not exist\n" % groupname)
165

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

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

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

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

    
205
        password = None
206
        if options['renew_password']:
207
            password = AstakosUser.objects.make_random_password()
208
            user.set_password(password)
209

    
210
        if options['renew_token']:
211
            user.renew_token()
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)
220

    
221
        pending = options.get('pending')
222
        if pending:
223
            try:
224
                pending = int(pending)
225
            except ValueError as e:
226
                m = _("Expected integer argument")
227
                raise CommandError(m)
228
            else:
229
                set_pending_application_limit(user_id, pending)
230

    
231
        unset_pending = options.get('unset_pending')
232
        if unset_pending:
233
            unset_pending_application_limit(user_id)