-
Notifications
You must be signed in to change notification settings - Fork 13
/
auth.py
144 lines (111 loc) · 3.71 KB
/
auth.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# -*- coding: utf-8 -*-
import os
import sys
import cookielib
from getpass import getpass
from ConfigParser import ConfigParser
import requests
from bs4 import BeautifulSoup
from termcolor import colored
import colorama
colorama.init()
requests = requests.Session()
requests.cookies = cookielib.LWPCookieJar('cookies')
try:
requests.cookies.load(ignore_discard=True)
except IOError:
pass
class Logging:
"""Print out message in terminal with color"""
flag = True
@staticmethod
def error(msg):
if Logging.flag:
print "".join([colored("ERROR", "red"), ": ", colored(msg, "white")])
@staticmethod
def warn(msg):
if Logging.flag:
print "".join([colored("WARN", "yellow"), ": ", colored(msg, "white")])
@staticmethod
def info(msg):
if Logging.flag:
print "".join([colored("INFO", "magenta"), ": ", colored(msg, "white")])
@staticmethod
def debug(msg):
if Logging.flag:
print "".join([colored("DEBUG", "magenta"), ": ", colored(msg, "white")])
@staticmethod
def success(msg):
if Logging.flag:
print "".join([colored("SUCCESS", "green"), ": ", colored(msg, "white")])
Logging.flag = True
url = 'https://www.goodreads.com/user/sign_in'
def is_login():
url = 'https://www.goodreads.com/user/sign_in'
r = requests.get(url, allow_redirects=True, verify=False)
status_code = int(r.status_code)
if status_code == 200 and r.history:
return True
else:
return False
def get_extra_form_data():
"""Get built-in field value in form"""
r = requests.get(url, allow_redirects=False, verify=False)
soup = BeautifulSoup(r.content)
csrf_token = soup.find('input', {'name': 'authenticity_token'})['value']
unkonw_n = soup.find('input', {'name': 'n'})['value']
return csrf_token, unkonw_n
def get_account_from_config(config_file='config.ini'):
cf = ConfigParser()
if os.path.exists(config_file) and os.path.isfile(config_file):
Logging.info(u'正在加载配置文件')
cf.read(config_file)
email = cf.get('info', 'email')
password = cf.get('info', 'password')
if email == '' or password == '':
Logging.error(u'未填写配置文件')
return None, None
else:
return email, password
else:
Logging.error(u'配置文件加载失败')
def post_form(email, password):
csrf_token, unkonw_n = get_extra_form_data()
form = {
'utf8': '✓',
'authenticity_token': csrf_token,
'user[email]': email,
'user[password]': password,
'remember_me': 'on',
'next': 'Sign in',
'n': unkonw_n
}
headers = {
'User-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36",
'Host': "www.goodreads.com",
'Origin': "https://www.goodreads.com",
'Referer': "https://www.goodreads.com"
}
r = requests.post(url, data=form, headers=headers, verify=False)
if not r.history:
raise Exception('log in failed')
def login(email=None, password=None):
if is_login():
Logging.success(u'你已经登陆过')
return True
# in case the expired cookies
try:
requests.cookies.revert()
except IOError:
pass
if not email:
email, password = get_account_from_config()
if not email:
sys.stdout.write('Please enter your email: ')
email = raw_input()
password = getpass('Please enter your password:')
post_form(email, password)
requests.cookies.save()
if __name__ == '__main__':
login()
raw_input('Press Enter key to exit')