60 lines
1.9 KiB
Python
60 lines
1.9 KiB
Python
import urllib.request, json, http.cookiejar, urllib.error, ssl
|
|
|
|
# Disable SSL verification for localhost testing
|
|
ctx = ssl.create_default_context()
|
|
ctx.check_hostname = False
|
|
ctx.verify_mode = ssl.CERT_NONE
|
|
|
|
cj = http.cookiejar.CookieJar()
|
|
opener = urllib.request.build_opener(
|
|
urllib.request.HTTPCookieProcessor(cj),
|
|
urllib.request.HTTPSHandler(context=ctx)
|
|
)
|
|
|
|
# Get CSRF token
|
|
csrf_resp = opener.open('http://localhost:8301/api/auth/csrf')
|
|
csrf = json.loads(csrf_resp.read())
|
|
print('CSRF token:', csrf['csrfToken'][:20] + '...')
|
|
|
|
# Login (don't follow redirect)
|
|
data = urllib.parse.urlencode({
|
|
'csrfToken': csrf['csrfToken'],
|
|
'email': 'admin@zhuiguang.com',
|
|
'password': 'Admin123!'
|
|
}).encode()
|
|
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
return None
|
|
def http_error_302(self, req, fp, code, msg, headers):
|
|
return fp
|
|
|
|
no_redirect_opener = urllib.request.build_opener(
|
|
urllib.request.HTTPCookieProcessor(cj),
|
|
NoRedirect
|
|
)
|
|
|
|
req = urllib.request.Request(
|
|
'http://localhost:8301/api/auth/callback/credentials',
|
|
data=data,
|
|
method='POST'
|
|
)
|
|
try:
|
|
resp = no_redirect_opener.open(req)
|
|
print('Status:', resp.status)
|
|
print('Location:', resp.headers.get('location', 'none'))
|
|
# Check cookies
|
|
for cookie in cj:
|
|
if 'session-token' in cookie.name or 'next-auth' in cookie.name:
|
|
print('Cookie:', cookie.name, '=', cookie.value[:30] + '...')
|
|
except urllib.error.HTTPError as e:
|
|
print('Error:', e.code, '->', e.headers.get('location', ''))
|
|
|
|
# Check session
|
|
sess_req = urllib.request.Request('http://localhost:8301/api/auth/session')
|
|
sess_resp = opener.open(sess_req)
|
|
sess = json.loads(sess_resp.read())
|
|
print('Session:', json.dumps(sess, indent=2))
|
|
if sess.get('user'):
|
|
print('>>> LOGIN SUCCESS! User:', sess['user'].get('email'))
|