Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / user-update.py @ 14a58548

History | View | Annotate | Download (8.8 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
from synnefo.lib.db.transaction import commit_on_success_strict
48

    
49

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

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

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

    
127
        if args[0].isdigit():
128
            user_id = int(args[0])
129
            user = AstakosUser.objects.get(id=user_id)
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
            activate(user)
143
        elif options.get('inactive'):
144
            deactivate(user)
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 = Group.objects.get(name=groupname)
154
                user.groups.add(group)
155
            except Group.DoesNotExist, e:
156
                self.stdout.write(
157
                    "Group named %s does not exist\n" % groupname)
158

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

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

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

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

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

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

    
212
        if options['renew_token']:
213
            user.renew_token()
214

    
215
        try:
216
            user.save()
217
        except ValidationError, e:
218
            raise CommandError(e)
219

    
220
        if password:
221
            self.stdout.write('User\'s new password: %s\n' % password)
222

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

    
233
        unset_pending = options.get('unset_pending')
234
        if unset_pending:
235
            unset_pending_application_limit(user_id)