Completed
Push — master ( 2fc514...cd0c61 )
by Jochen
04:47
created

find_logins_for_ipaddress.find_events()   A

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
#!/usr/bin/env python
2
3
"""Find user login events for an IP address.
4
5
:Copyright: 2006-2019 Jochen Kupperschmidt
6
:License: Modified BSD, see LICENSE for details.
7
"""
8
9
from typing import Dict, List
10
11
import click
12
13
from byceps.services.user.models.event import UserEvent
14
from byceps.services.user import service as user_service
15
from byceps.services.user.transfer.models import User
16
from byceps.typing import PartyID, UserID
17
from byceps.util.system import get_config_filename_from_env_or_exit
18
19
from _util import app_context
20
21
22
@click.command()
23
@click.argument('ip_address')
24
def execute(ip_address: str):
25
    events = find_events(ip_address)
26
    users_by_id = get_users_by_id(events)
27
28
    for event in events:
29
        user = users_by_id[event.user_id]
30
        click.echo(f'{event.occurred_at}\t{ip_address}\t{user.screen_name}')
31
32
33
def find_events(ip_address: str) -> List[UserEvent]:
34
    return UserEvent.query \
35
        .filter_by(event_type='user-logged-in') \
36
        .filter(UserEvent.data['ip_address'].astext == ip_address) \
37
        .order_by(UserEvent.occurred_at) \
38
        .all()
39
40
41
def get_users_by_id(events: List[UserEvent]) -> Dict[UserID, User]:
42
    user_ids = {event.user_id for event in events}
43
    users = user_service.find_users(user_ids)
44
    return {user.id: user for user in users}
45
46
47
if __name__ == '__main__':
48
    config_filename = get_config_filename_from_env_or_exit()
49
    with app_context(config_filename):
50
        execute()
51