Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / user-add.py @ 04e05445

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

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

    
42
from astakos.im.models import AstakosUser
43
from astakos.im.api.callpoint import AstakosCallpoint
44
from astakos.im.functions import activate
45

    
46
def filter_custom_options(options):
47
    base_dests = list(
48
        getattr(o, 'dest', None) for o in BaseCommand.option_list)
49
    return dict((k, v) for k, v in options.iteritems() if k not in base_dests)
50

    
51

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

    
56
    option_list = BaseCommand.option_list + (
57
        make_option('--affiliation',
58
                    dest='affiliation',
59
                    metavar='AFFILIATION',
60
                    help="Set user's affiliation"),
61
        make_option('--password',
62
                    dest='password',
63
                    metavar='PASSWORD',
64
                    help="Set user's password"),
65
        make_option('--active',
66
                    action='store_true',
67
                    dest='active',
68
                    default=False,
69
                    help="Set active"),
70
        make_option('--admin',
71
                    action='store_true',
72
                    dest='is_superuser',
73
                    default=False,
74
                    help="Give user admin rights"),
75
        make_option('-g',
76
                    action='append',
77
                    dest='groups',
78
                    help="Add user group (may be used multiple times)"),
79
        make_option('-p',
80
                    action='append',
81
                    dest='permissions',
82
                    help="Add user permission (may be used multiple times)")
83
    )
84

    
85
    def handle(self, *args, **options):
86
        if len(args) != 3:
87
            raise CommandError("Invalid number of arguments")
88

    
89
        email, first_name, last_name = (args[i].decode('utf8') for i in range(3))
90

    
91
        try:
92
            validate_email(email)
93
        except ValidationError:
94
            raise CommandError("Invalid email")
95

    
96
        u = {'email': email,
97
             'first_name':first_name,
98
             'last_name':last_name
99
        }
100
        u.update(filter_custom_options(options))
101
        u.pop('active')
102
        if not u.get('password'):
103
            u['password'] = AstakosUser.objects.make_random_password()
104

    
105
        try:
106
            c = AstakosCallpoint()
107
            r = c.create_users((u,)).next()
108
        except BaseException, e:
109
            raise CommandError(e)
110
        else:
111
            if not r.is_success:
112
                raise CommandError(r.reason)
113
            else:
114
                if options['active']:
115
                    user_id = r.data.get('id')
116
                    user = AstakosUser.objects.get(id = user_id)
117
                    activate(user)
118
                self.stdout.write('User created successfully ')
119
                if not options.get('password'):
120
                    self.stdout.write('with password: %s\n' % u['password'])
121
                else:
122
                    self.stdout.write('\n')