Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / user-show.py @ ff5edb80

History | View | Annotate | Download (7.3 kB)

1
# Copyright 2012-2014 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 django.core.management.base import CommandError
35
from optparse import make_option
36

    
37
from django.db.models import Q
38
from astakos.im.models import AstakosUser, get_latest_terms, Project
39
from astakos.im.quotas import get_user_quotas
40

    
41
from synnefo.lib.ordereddict import OrderedDict
42
from snf_django.management.commands import SynnefoCommand
43
from snf_django.management import utils
44

    
45
from ._common import show_user_quotas, style_options, check_style
46

    
47
import uuid
48

    
49

    
50
class Command(SynnefoCommand):
51
    args = "<user ID or email or uuid>"
52
    help = "Show user info"
53

    
54
    option_list = SynnefoCommand.option_list + (
55
        make_option('--quota',
56
                    action='store_true',
57
                    dest='list_quotas',
58
                    default=False,
59
                    help="Also list user quota"),
60
        make_option('--unit-style',
61
                    default='mb',
62
                    help=("Specify display unit for resource values "
63
                          "(one of %s); defaults to mb") % style_options),
64
        make_option('--projects',
65
                    action='store_true',
66
                    dest='list_projects',
67
                    default=False,
68
                    help="Also list project memberships"),
69
    )
70

    
71
    def handle(self, *args, **options):
72
        if len(args) != 1:
73
            raise CommandError("Please provide a user ID or email")
74

    
75
        identifier = args[0]
76
        if identifier.isdigit():
77
            users = AstakosUser.objects.filter(id=int(identifier))
78
        else:
79
            try:
80
                uuid.UUID(identifier)
81
            except:
82
                users = AstakosUser.objects.filter(email__iexact=identifier)
83
            else:
84
                users = AstakosUser.objects.filter(uuid=identifier)
85
        if users.count() == 0:
86
            field = 'id' if identifier.isdigit() else 'email'
87
            msg = "Unknown user with %s '%s'" % (field, identifier)
88
            raise CommandError(msg)
89

    
90
        for user in users:
91
            kv = OrderedDict(
92
                [
93
                    ('id', user.id),
94
                    ('uuid', user.uuid),
95
                    ('status', user.status_display),
96
                    ('email', user.email),
97
                    ('first name', user.first_name),
98
                    ('last name', user.last_name),
99
                    ('active', user.is_active),
100
                    ('admin', user.is_superuser),
101
                    ('last login', user.last_login),
102
                    ('date joined', user.date_joined),
103
                    ('last update', user.updated),
104
                    #('token', user.auth_token),
105
                    ('token expiration', user.auth_token_expires),
106
                    ('providers', user.auth_providers_display),
107
                    ('verified', user.is_verified),
108
                    ('groups', [elem.name for elem in user.groups.all()]),
109
                    ('permissions', [elem.codename
110
                                     for elem in user.user_permissions.all()]),
111
                    ('group permissions', user.get_group_permissions()),
112
                    ('email verified', user.email_verified),
113
                    ('username', user.username),
114
                    ('activation_sent_date', user.activation_sent),
115
                ])
116

    
117
            if get_latest_terms():
118
                has_signed_terms = user.signed_terms
119
                kv['has_signed_terms'] = has_signed_terms
120
                if has_signed_terms:
121
                    kv['date_signed_terms'] = user.date_signed_terms
122

    
123
            utils.pprint_table(self.stdout, [kv.values()], kv.keys(),
124
                               options["output_format"], vertical=True)
125

    
126
            if options["list_quotas"] and user.is_accepted():
127
                unit_style = options["unit_style"]
128
                check_style(unit_style)
129

    
130
                quotas = get_user_quotas(user)
131
                if quotas:
132
                    self.stdout.write("\n")
133
                    print_data, labels = show_user_quotas(quotas,
134
                                                          style=unit_style)
135
                    utils.pprint_table(self.stdout, print_data, labels,
136
                                       options["output_format"],
137
                                       title="User Quota")
138

    
139
            if options["list_projects"]:
140
                print_data, labels = ownerships(user)
141
                if print_data:
142
                    self.stdout.write("\n")
143
                    utils.pprint_table(self.stdout, print_data, labels,
144
                                       options["output_format"],
145
                                       title="Owned Projects")
146

    
147
                print_data, labels = memberships(user)
148
                if print_data:
149
                    self.stdout.write("\n")
150
                    utils.pprint_table(self.stdout, print_data, labels,
151
                                       options["output_format"],
152
                                       title="Project Memberships")
153

    
154

    
155
def memberships(user):
156
    ms = user.projectmembership_set.all()
157
    print_data = []
158
    labels = ('project id', 'project name', 'status')
159

    
160
    for m in ms:
161
        project = m.project
162
        print_data.append((project.uuid,
163
                           project.realname,
164
                           m.state_display(),
165
                           ))
166
    return print_data, labels
167

    
168

    
169
def ownerships(user):
170
    chains = Project.objects.select_related("last_application").\
171
        filter(owner=user)
172
    return chain_info(chains)
173

    
174

    
175
def chain_info(chains):
176
    labels = ('project id', 'project name', 'status', 'pending app id')
177
    l = []
178
    for project in chains:
179
        status = project.state_display()
180
        app = project.last_application
181
        pending_appid = app.id if app and app.state == app.PENDING else ""
182

    
183
        t = (project.uuid,
184
             project.realname,
185
             status,
186
             pending_appid,
187
             )
188
        l.append(t)
189
    return l, labels