Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.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
from ._common import remove_user_permission, add_user_permission
45
from snf_django.lib.db.transaction import commit_on_success_strict
46

    
47

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

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

    
109
    @commit_on_success_strict()
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_id = int(args[0])
116
            user = AstakosUser.objects.get(id=user_id)
117
        else:
118
            raise CommandError("Invalid ID")
119

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

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

    
128
        if options.get('active'):
129
            activate(user)
130
        elif options.get('inactive'):
131
            deactivate(user)
132

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

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

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

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

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

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

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

    
194
        password = None
195
        if options['renew_password']:
196
            password = AstakosUser.objects.make_random_password()
197
            user.set_password(password)
198

    
199
        if options['renew_token']:
200
            user.renew_token()
201

    
202
        try:
203
            user.save()
204
        except ValidationError, e:
205
            raise CommandError(e)
206

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