user-show.py 7.32 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
38
from django.db.models import Q
from astakos.im.models import AstakosUser, get_latest_terms, Project
39
from astakos.im.quotas import list_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_quotas, style_options, check_style
46

47
import uuid
48

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
49

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

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

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

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

90
        for user in users:
91
92
93
94
            kv = OrderedDict(
                [
                    ('id', user.id),
                    ('uuid', user.uuid),
95
                    ('status', user.status_display),
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
                    ('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()]),
111
112
                    ('group permissions', user.get_group_permissions()),
                    ('email verified', user.email_verified),
113
114
115
116
                    ('username', user.username),
                    ('activation_sent_date', user.activation_sent),
                ])

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
124
            utils.pprint_table(self.stdout, [kv.values()], kv.keys(),
                               options["output_format"], vertical=True)
125
126

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

130
                quotas, initial = list_user_quotas([user])
131
132
                if quotas:
                    self.stdout.write("\n")
133
134
                    print_data, labels = show_quotas(quotas, initial,
                                                     style=unit_style)
135
136
137
                    utils.pprint_table(self.stdout, print_data, labels,
                                       options["output_format"],
                                       title="User Quota")
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

            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):
170
171
    chains = Project.objects.all_with_pending(Q(application__owner=user))
    return chain_info(chains)
172
173


174
def chain_info(chains):
175
176
    labels = ('project id', 'project name', 'status', 'pending app id')
    l = []
177
178
179
180
    for project, pending_app in chains:
        status = project.state_display()
        pending_appid = pending_app.id if pending_app is not None else ""
        application = project.application
181

182
183
        t = (project.pk,
             application.name,
184
             status,
185
             pending_appid,
186
187
188
             )
        l.append(t)
    return l, labels