Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.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.contrib.auth.models import Group
39
from django.core.exceptions import ValidationError
40

    
41
from astakos.im.models import AstakosUser
42
from astakos.im.functions import activate, deactivate
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('--renew-token',
64
                    action='store_true',
65
                    dest='renew_token',
66
                    default=False,
67
                    help="Renew the user's token"),
68
        make_option('--renew-password',
69
                    action='store_true',
70
                    dest='renew_password',
71
                    default=False,
72
                    help="Renew the user's password"),
73
        make_option('--set-admin',
74
                    action='store_true',
75
                    dest='admin',
76
                    default=False,
77
                    help="Give user admin rights"),
78
        make_option('--set-noadmin',
79
                    action='store_true',
80
                    dest='noadmin',
81
                    default=False,
82
                    help="Revoke user's admin rights"),
83
        make_option('--set-active',
84
                    action='store_true',
85
                    dest='active',
86
                    default=False,
87
                    help="Change user's state to active"),
88
        make_option('--set-inactive',
89
                    action='store_true',
90
                    dest='inactive',
91
                    default=False,
92
                    help="Change user's state to inactive"),
93
        make_option('--add-group',
94
                    dest='add-group',
95
                    help="Add user group"),
96
        make_option('--delete-group',
97
                    dest='delete-group',
98
                    help="Delete user group"),
99
        make_option('--add-permission',
100
                    dest='add-permission',
101
                    help="Add user permission"),
102
        make_option('--delete-permission',
103
                    dest='delete-permission',
104
                    help="Delete user permission"),
105
    )
106

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

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

    
116
        if not user:
117
            raise CommandError("Unknown user")
118

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

    
124
        if options.get('active'):
125
            activate(user)
126
        elif options.get('inactive'):
127
            deactivate(user)
128

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

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

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

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

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

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

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

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

    
195
        if options['renew_token']:
196
            user.renew_token()
197

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

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