user-show.py 7.62 KB
Newer Older
1
# Copyright 2012, 2013 GRNET S.A. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

34
from django.core.management.base import CommandError
35
from optparse import make_option
36

37
from astakos.im.models import AstakosUser, get_latest_terms, Chain
38
from astakos.im.quotas import list_user_quotas
39

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

44
from ._common import show_quotas, style_options, check_style
45

46
import uuid
47

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
48

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

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

70
71
    def handle(self, *args, **options):
        if len(args) != 1:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
72
            raise CommandError("Please provide a user ID or email")
73

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

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

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

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

            if options["list_quotas"]:
126
127
128
                unit_style = options["unit_style"]
                check_style(unit_style)

129
                quotas, initial = list_user_quotas([user])
130
131
                if quotas:
                    self.stdout.write("\n")
132
133
                    print_data, labels = show_quotas(quotas, initial,
                                                     style=unit_style)
134
135
136
                    utils.pprint_table(self.stdout, print_data, labels,
                                       options["output_format"],
                                       title="User Quota")
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

            if options["list_projects"]:
                print_data, labels = ownerships(user)
                if print_data:
                    self.stdout.write("\n")
                    utils.pprint_table(self.stdout, print_data, labels,
                                       options["output_format"],
                                       title="Owned Projects")

                print_data, labels = memberships(user)
                if print_data:
                    self.stdout.write("\n")
                    utils.pprint_table(self.stdout, print_data, labels,
                                       options["output_format"],
                                       title="Project Memberships")


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

    for m in ms:
        project = m.project
        print_data.append((project.id,
                           project.application.name,
                           m.state_display(),
                           ))
    return print_data, labels


def ownerships(user):
    chain_dict = Chain.objects.all_full_state()
    chain_dict = filter_by(is_owner(user), chain_dict)
    return chain_info(chain_dict)


def is_owner(user):
    def f(state, project, app):
        return user == app.owner
    return f


def filter_by(f, chain_dict):
    d = {}
    for chain, tpl in chain_dict.iteritems():
        if f(*tpl):
            d[chain] = tpl
    return d


def chain_info(chain_dict):
    labels = ('project id', 'project name', 'status', 'pending app id')
    l = []
    for chain, (state, project, app) in chain_dict.iteritems():
        status = Chain.state_display(state)
        if state in Chain.PENDING_STATES:
            appid = str(app.id)
        else:
            appid = ""

        t = (chain,
             project.application.name if project else app.name,
             status,
             appid,
             )
        l.append(t)
    return l, labels