forked from mizlan/usub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.py
87 lines (70 loc) · 2 KB
/
session.py
1
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'''
handles session sessid invalidation/expiration, and retrieving sessid
'''
import sys
from pathlib import Path
import requests
from bs4 import BeautifulSoup
import auth
import login
def get_authentication():
return auth.get()
def get_cache_filepath():
return Path.home() / 'usub'
def gen_new_sessid():
username, password = get_authentication()
sessid = login.login(username, password)
return sessid
def _get_cached_sessid():
'''
gets cached sessid.
checks file '~/usub' for key.
raises KeyError if neither is found.
'''
tpath = get_cache_filepath()
if tpath.is_file():
tpath = tpath.resolve(strict=True)
return open(tpath).read().strip()
# TODO use a custom exception instead of KeyError
raise KeyError('nothing found')
def write_sessid(sessid: str):
tpath = get_cache_filepath()
with open(tpath, 'w+') as f:
f.write(sessid + '\n')
def invalidate_sessid():
'''
uses try/except to avoid race conditions, see:
https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use
'''
tpath = get_cache_filepath()
try:
tpath.unlink()
except FileNotFoundError:
sys.stderr.write(f'{tpath} not found\n')
def get_sessid(force_invalidate=False):
sessid = None
if force_invalidate:
invalidate_sessid()
try:
sessid = _get_cached_sessid()
if not sessid_is_valid(sessid):
# TODO: use verbose mode
sys.stderr.write('found invalid session ID\n')
raise KeyError
except KeyError:
sessid = gen_new_sessid()
write_sessid(sessid)
return sessid
def get_cookie_dict():
return {
'PHPSESSID': get_sessid()
}
def sessid_is_valid(sessid: str) -> bool:
url = 'http://usaco.org/index.php'
response = requests.get(
url,
cookies={ 'PHPSESSID': sessid }
)
return not ("Not currently logged in." in response.text)
if __name__ == '__main__':
print(sessid_is_valid(_get_cached_sessid()))