45 lines
1.5 KiB
Python
45 lines
1.5 KiB
Python
import urllib.request, json, http.cookiejar
|
|
|
|
class NoRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
return None
|
|
http_error_301 = http_error_302 = http_error_303 = http_error_307 = lambda self, req, fp, code, msg, headers: fp
|
|
|
|
cj = http.cookiejar.CookieJar()
|
|
opener = urllib.request.build_opener(
|
|
urllib.request.HTTPCookieProcessor(cj),
|
|
NoRedirectHandler
|
|
)
|
|
|
|
# Get CSRF
|
|
csrf = json.loads(opener.open('http://localhost:8301/api/auth/csrf').read())
|
|
print('CSRF:', csrf['csrfToken'][:30])
|
|
|
|
# Login
|
|
data = urllib.parse.urlencode({
|
|
'csrfToken': csrf['csrfToken'],
|
|
'email': 'admin@zhuiguang.com',
|
|
'password': 'Admin123!'
|
|
}).encode()
|
|
|
|
req = urllib.request.Request('http://localhost:8301/api/auth/callback/credentials', data=data, method='POST')
|
|
resp = opener.open(req)
|
|
print('Status:', resp.status)
|
|
loc = resp.headers.get('location', 'NONE')
|
|
print('Location:', loc)
|
|
|
|
if 'error=CredentialsSignin' in (loc or ''):
|
|
print('>>> FAIL: Invalid credentials')
|
|
elif 'csrf=true' in (loc or ''):
|
|
print('>>> FAIL: CSRF token mismatch')
|
|
elif '/api/auth/signin' not in (loc or ''):
|
|
print('>>> SUCCESS: Login accepted, redirecting to caller page')
|
|
|
|
# Session
|
|
opener2 = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
|
|
sess = json.loads(opener2.open('http://localhost:8301/api/auth/session').read())
|
|
if sess.get('user'):
|
|
print('Session OK:', sess['user'].get('email'), '| role:', sess['user'].get('role'))
|
|
else:
|
|
print('Session EMPTY - user not logged in')
|