Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.4 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
38
from django.core.exceptions import ValidationError
39

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

    
43

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

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

    
105
    def handle(self, *args, **options):
106
        if len(args) != 1:
107
            raise CommandError("Please provide a user ID")
108

    
109
        if args[0].isdigit():
110
            user = AstakosUser.objects.get(id=int(args[0]))
111
        else:
112
            raise CommandError("Invalid ID")
113

    
114
        if not user:
115
            raise CommandError("Unknown user")
116

    
117
        if options.get('admin'):
118
            user.is_superuser = True
119
        elif options.get('noadmin'):
120
            user.is_superuser = False
121

    
122
        if options.get('active'):
123
            user.is_active = True
124
        elif options.get('inactive'):
125
            user.is_active = False
126

    
127
        invitations = options.get('invitations')
128
        if invitations is not None:
129
            user.invitations = int(invitations)
130

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

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

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

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

    
180
        level = options.get('level')
181
        if level is not None:
182
            user.level = int(level)
183

    
184
        password = options.get('password')
185
        if password is not None:
186
            user.set_password(password)
187

    
188
        password = None
189
        if options['renew_password']:
190
            password = AstakosUser.objects.make_random_password()
191
            user.set_password(password)
192

    
193
        if options['renew_token']:
194
            user.renew_token()
195

    
196
        try:
197
            user.save()
198
        except ValidationError, e:
199
            raise CommandError(e)
200

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