1"""User details."""
2# :license: MIT, see LICENSE for more details.
3
4import click
5
6import SoftLayer
7from SoftLayer.CLI import environment
8from SoftLayer.CLI import formatting
9from SoftLayer.CLI import helpers
10from SoftLayer import utils
11
12
13@click.command()
14@click.argument('identifier')
15@click.option('--keys', '-k', is_flag=True, default=False,
16              help="Show the users API key.")
17@click.option('--permissions', '-p', is_flag=True, default=False,
18              help="Display permissions assigned to this user. Master users will show no permissions")
19@click.option('--hardware', '-h', is_flag=True, default=False,
20              help="Display hardware this user has access to.")
21@click.option('--virtual', '-v', is_flag=True, default=False,
22              help="Display virtual guests this user has access to.")
23@click.option('--logins', '-l', is_flag=True, default=False,
24              help="Show login history of this user for the last 30 days")
25@click.option('--events', '-e', is_flag=True, default=False,
26              help="Show event log for this user.")
27@environment.pass_env
28def cli(env, identifier, keys, permissions, hardware, virtual, logins, events):
29    """User details."""
30
31    mgr = SoftLayer.UserManager(env.client)
32    user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
33    object_mask = "userStatus[name], parent[id, username], apiAuthenticationKeys[authenticationKey], "\
34                  "unsuccessfulLogins, successfulLogins"
35
36    user = mgr.get_user(user_id, object_mask)
37    env.fout(basic_info(user, keys))
38
39    if permissions:
40        perms = mgr.get_user_permissions(user_id)
41        env.fout(print_permissions(perms))
42    if hardware:
43        mask = "id, hardware, dedicatedHosts"
44        access = mgr.get_user(user_id, mask)
45        env.fout(print_dedicated_access(access.get('dedicatedHosts', [])))
46        env.fout(print_access(access.get('hardware', []), 'Hardware'))
47    if virtual:
48        mask = "id, virtualGuests"
49        access = mgr.get_user(user_id, mask)
50        env.fout(print_access(access.get('virtualGuests', []), 'Virtual Guests'))
51    if logins:
52        login_log = mgr.get_logins(user_id)
53        env.fout(print_logins(login_log))
54    if events:
55        event_log = mgr.get_events(user_id)
56        env.fout(print_events(event_log))
57
58
59def basic_info(user, keys):
60    """Prints a table of basic user information"""
61
62    table = formatting.KeyValueTable(['Title', 'Basic Information'])
63    table.align['Title'] = 'r'
64    table.align['Basic Information'] = 'l'
65
66    table.add_row(['Id', user.get('id', '-')])
67    table.add_row(['Username', user.get('username', '-')])
68    if keys:
69        for key in user.get('apiAuthenticationKeys'):
70            table.add_row(['APIKEY', key.get('authenticationKey')])
71    table.add_row(['Name', "%s %s" % (user.get('firstName', '-'), user.get('lastName', '-'))])
72    table.add_row(['Email', user.get('email')])
73    table.add_row(['OpenID', user.get('openIdConnectUserName')])
74    address = "%s %s %s %s %s %s" % (
75        user.get('address1'), user.get('address2'), user.get('city'), user.get('state'),
76        user.get('country'), user.get('postalCode'))
77    table.add_row(['Address', address])
78    table.add_row(['Company', user.get('companyName')])
79    table.add_row(['Created', user.get('createDate')])
80    table.add_row(['Phone Number', user.get('officePhone')])
81    if user.get('parentId', False):
82        table.add_row(['Parent User', utils.lookup(user, 'parent', 'username')])
83    table.add_row(
84        ['Status', utils.lookup(user, 'userStatus', 'name')])
85    table.add_row(['SSL VPN', user.get('sslVpnAllowedFlag', 'No')])
86    for login in user.get('unsuccessfulLogins', {}):
87        login_string = "%s From: %s" % (login.get('createDate'), login.get('ipAddress'))
88        table.add_row(['Last Failed Login', login_string])
89        break
90    for login in user.get('successfulLogins', {}):
91        login_string = "%s From: %s" % (login.get('createDate'), login.get('ipAddress'))
92        table.add_row(['Last Login', login_string])
93        break
94
95    return table
96
97
98def print_permissions(permissions):
99    """Prints out a users permissions"""
100
101    table = formatting.Table(['keyName', 'Description'])
102    for perm in permissions:
103        table.add_row([perm['keyName'], perm['name']])
104    return table
105
106
107def print_access(access, title):
108    """Prints out the hardware or virtual guests a user can access"""
109
110    columns = ['id', 'hostname', 'Primary Public IP', 'Primary Private IP', 'Created']
111    table = formatting.Table(columns, title)
112
113    for host in access:
114        host_id = host.get('id')
115        host_fqdn = host.get('fullyQualifiedDomainName', '-')
116        host_primary = host.get('primaryIpAddress')
117        host_private = host.get('primaryBackendIpAddress')
118        host_created = host.get('provisionDate')
119        table.add_row([host_id, host_fqdn, host_primary, host_private, host_created])
120    return table
121
122
123def print_dedicated_access(access):
124    """Prints out the dedicated hosts a user can access"""
125
126    table = formatting.Table(['id', 'Name', 'Cpus', 'Memory', 'Disk', 'Created'], 'Dedicated Access')
127    for host in access:
128        host_id = host.get('id')
129        host_fqdn = host.get('name')
130        host_cpu = host.get('cpuCount')
131        host_mem = host.get('memoryCapacity')
132        host_disk = host.get('diskCapacity')
133        host_created = host.get('createDate')
134        table.add_row([host_id, host_fqdn, host_cpu, host_mem, host_disk, host_created])
135    return table
136
137
138def print_logins(logins):
139    """Prints out the login history for a user"""
140    table = formatting.Table(['Date', 'IP Address', 'Successufl Login?'])
141    for login in logins:
142        table.add_row([login.get('createDate'), login.get('ipAddress'), login.get('successFlag')])
143    return table
144
145
146def print_events(events):
147    """Prints out the event log for a user"""
148    columns = ['Date', 'Type', 'IP Address', 'label', 'username']
149    table = formatting.Table(columns)
150    for event in events:
151        table.add_row([event.get('eventCreateDate'), event.get('eventName'),
152                       event.get('ipAddress'), event.get('label'), event.get('username')])
153    return table
154