Statistics
| Branch: | Tag: | Revision:

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

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

    
36
from django.core.management.base import BaseCommand, CommandError
37
from django.contrib.auth.models import Group, Permission
38
from django.contrib.contenttypes.models import ContentType
39
from django.core.exceptions import ValidationError
40

    
41
from astakos.im.models import AstakosUser
42
from ._common import remove_user_permission, add_user_permission
43

    
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
    )
109

    
110
    def handle(self, *args, **options):
111
        if len(args) != 1:
112
            raise CommandError("Please provide a user ID")
113

    
114
        if args[0].isdigit():
115
            user = AstakosUser.objects.get(id=int(args[0]))
116
        else:
117
            raise CommandError("Invalid ID")
118

    
119
        if not user:
120
            raise CommandError("Unknown user")
121

    
122
        if options.get('admin'):
123
            user.is_superuser = True
124
        elif options.get('noadmin'):
125
            user.is_superuser = False
126

    
127
        if options.get('active'):
128
            user.is_active = True
129
        elif options.get('inactive'):
130
            user.is_active = False
131

    
132
        invitations = options.get('invitations')
133
        if invitations is not None:
134
            user.invitations = int(invitations)
135

    
136
        groupname = options.get('add-group')
137
        if groupname is not None:
138
            try:
139
                group = Group.objects.get(name=groupname)
140
                user.groups.add(group)
141
            except Group.DoesNotExist, e:
142
                self.stdout.write(
143
                    "Group named %s does not exist\n" % groupname)
144

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

    
154
        pname = options.get('add-permission')
155
        if pname is not None:
156
            try:
157
                r, created = add_user_permission(user, pname)
158
                if created:
159
                    self.stdout.write(
160
                        'Permission: %s created successfully\n' % pname)
161
                if r > 0:
162
                    self.stdout.write(
163
                        'Permission: %s added successfully\n' % pname)
164
                elif r == 0:
165
                    self.stdout.write(
166
                        'User has already permission: %s\n' % pname)
167
            except Exception, e:
168
                raise CommandError(e)
169

    
170
        pname = options.get('delete-permission')
171
        if pname is not None and not user.has_perm(pname):
172
            try:
173
                r = remove_user_permission(user, pname)
174
                if r < 0:
175
                    self.stdout.write(
176
                        'Invalid permission codename: %s\n' % pname)
177
                elif r == 0:
178
                    self.stdout.write('User has not permission: %s\n' % pname)
179
                elif r > 0:
180
                    self.stdout.write(
181
                        'Permission: %s removed successfully\n' % pname)
182
            except Exception, e:
183
                raise CommandError(e)
184

    
185
        level = options.get('level')
186
        if level is not None:
187
            user.level = int(level)
188

    
189
        password = options.get('password')
190
        if password is not None:
191
            user.set_password(password)
192

    
193
        provider = options.get('provider')
194
        if provider is not None:
195
            user.provider = provider
196

    
197
        password = None
198
        if options['renew_password']:
199
            password = AstakosUser.objects.make_random_password()
200
            user.set_password(password)
201

    
202
        if options['renew_token']:
203
            user.renew_token()
204

    
205
        try:
206
            user.save()
207
        except ValidationError, e:
208
            raise CommandError(e)
209

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