Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / user-add.py @ 6bdf0aa3

History | View | Annotate | Download (5.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
import socket
35

    
36
from optparse import make_option
37
from uuid import uuid4
38
from datetime import datetime
39

    
40
from django.core.management.base import BaseCommand, CommandError
41
from django.core.validators import validate_email
42
from django.core.exceptions import ValidationError
43

    
44
from astakos.im.models import AstakosUser, AstakosGroup, Membership
45
from astakos.im.util import reserved_email
46

    
47
from ._common import add_user_permission
48

    
49

    
50
class Command(BaseCommand):
51
    args = "<email> <first name> <last name> <affiliation>"
52
    help = "Create a user"
53

    
54
    option_list = BaseCommand.option_list + (
55
        make_option('--active',
56
                    action='store_true',
57
                    dest='active',
58
                    default=False,
59
                    help="Activate user"),
60
        make_option('--admin',
61
                    action='store_true',
62
                    dest='admin',
63
                    default=False,
64
                    help="Give user admin rights"),
65
        make_option('--password',
66
                    dest='password',
67
                    metavar='PASSWORD',
68
                    help="Set user's password"),
69
        make_option('--add-group',
70
                    dest='add-group',
71
                    help="Add user group"),
72
        make_option('--add-permission',
73
                    dest='add-permission',
74
                    help="Add user permission")
75
    )
76

    
77
    def handle(self, *args, **options):
78
        if len(args) != 4:
79
            raise CommandError("Invalid number of arguments")
80

    
81
        args = [a.decode('utf8') for a in args]
82
        email, first, last, affiliation = args
83

    
84
        #try:
85
        #    validate_email(email)
86
        #except ValidationError:
87
        #    raise CommandError("Invalid email")
88

    
89
        username = uuid4().hex[:30]
90
        password = options.get('password')
91
        if password is None:
92
            password = AstakosUser.objects.make_random_password()
93

    
94
        if reserved_email(email):
95
            raise CommandError("A user with this email already exists")
96

    
97
        user = AstakosUser(username=username, first_name=first, last_name=last,
98
                           email=email, affiliation=affiliation,
99
                           provider='local')
100
        user.set_password(password)
101
        user.renew_token()
102

    
103
        if options['active']:
104
            user.is_active = True
105
        if options['admin']:
106
            user.is_superuser = True
107

    
108
        try:
109
            user.save()
110
        except socket.error, e:
111
            raise CommandError(e)
112
        except ValidationError, e:
113
            raise CommandError(e)
114
        else:
115
            msg = "Created user id %d" % (user.id,)
116
            if options['password'] is None:
117
                msg += " with password '%s'" % (password,)
118
            self.stdout.write(msg + '\n')
119

    
120
            groupname = options.get('add-group')
121
            if groupname is not None:
122
                try:
123
                    group = AstakosGroup.objects.get(name=groupname)
124
                    Membership(group=group,
125
                               person=user, date_joined=datetime.now()).save()
126
                    self.stdout.write(
127
                        'Group: %s added successfully\n' % groupname)
128
                except AstakosGroup.DoesNotExist, e:
129
                    self.stdout.write(
130
                        'Group named %s does not exist\n' % groupname)
131

    
132
            pname = options.get('add-permission')
133
            if pname is not None:
134
                try:
135
                    r, created = add_user_permission(user, pname)
136
                    if created:
137
                        self.stdout.write(
138
                            'Permission: %s created successfully\n' % pname)
139
                    if r > 0:
140
                        self.stdout.write(
141
                            'Permission: %s added successfully\n' % pname)
142
                    elif r == 0:
143
                        self.stdout.write(
144
                            'User has already permission: %s\n' % pname)
145
                except Exception, e:
146
                    raise CommandError(e)