-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreport.py
191 lines (139 loc) · 5.9 KB
/
report.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/home/tao.liu1/anaconda/bin/python
# coding: utf8
import requests
from flask import Flask, make_response, render_template
from flask import session, request, redirect, url_for
# from flask_sslify import SSLify
from mysql.connector.pooling import MySQLConnectionPool
import os
import redis
import hashlib
import argparse
from datetime import datetime, timedelta
import logging
# import mail
import tab_api
from aes import AESCipher
import db
import conf
app = Flask(__name__)
# sslify = SSLify(app)
app.secret_key = "\xb2'\xb7\xff\xd3\xb0@s+q\x86M\xf9\x0e4PRVL\xa0\xa31\xe9z"
app.permanent_session_lifetime = timedelta(hours=3)
r = redis.StrictRedis(**conf.redis_conf)
@app.route('/')
def index():
if 'token' in session:
return redirect(url_for('report_list'))
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session.pop('token', None)
session.pop('email', None)
email, password = request.form['email'], request.form['password']
# login_ok = mail.pop3_login(email, password)
login_ok = mail_pop3_login(email, password)
logging.info('email:%s login: %s', email, login_ok)
if login_ok:
token = db.token_by_email(cnx_pool, email)
logging.debug('email:%s token:%s', email, token)
if token is None:
return render_template('login.html', err_msg=u'该邮箱没有授权, 请联系管理员')
xsrf_token, workgroup_session_id = get_tab_token_session()
session['token'] = token
session['email'] = email
resp = make_response(redirect(url_for('report_list')))
resp.set_cookie('XSRF-TOKEN', xsrf_token, domain=conf.MAIN_DOMAIN)
resp.set_cookie('workgroup_session_id', workgroup_session_id, domain=conf.MAIN_DOMAIN)
return resp
return render_template('login.html', err_msg=u'邮箱验证失败')
else:
if 'token' in session:
return redirect(url_for('report_list'))
return render_template('login.html', err_msg='')
@app.route('/logout')
def logout():
logging.info("user:%s logout", session['email'])
# remove the token from the session if it's there
session.pop('token', None)
session.pop('email', None)
resp = make_response(render_template('login.html', err_msg=''))
resp.set_cookie('XSRF-TOKEN', '', max_age=0, expires=0, domain=conf.MAIN_DOMAIN)
resp.set_cookie('workgroup_session_id', '', max_age=0, expires=0, domain=conf.MAIN_DOMAIN)
return resp
@app.route('/alive')
def alive():
return 'ok'
@app.errorhandler(500)
def internal_server_error(e):
logging.error("internal error: %s", e)
return render_template('50x.html'), 500
@app.route('/report_list')
def report_list():
token = session.get('token', None)
if token is None:
return redirect(url_for('login'))
reports = db.get_reports_by_token(cnx_pool, token=token)
reports = [(rpt[0], report_full_url(rpt[0], rpt[1], token)) for rpt in reports]
return render_template('tab_report_list.html', reports=reports)
@app.route('/report')
def report():
token = session.get('token', None)
if token is None:
return redirect(url_for('login'))
name = request.args.get('name', None)
url = request.args.get('url', None)
if name is None or url is None:
return '', 400
reports = db.get_reports_by_token(cnx_pool, token=token)
reports = [(rpt[0], report_full_url(rpt[0], rpt[1], token)) for rpt in reports]
return render_template('tab_report.html', token=token, tab_name=name, tab_url=url, reports=reports)
def report_full_url(report_name, report_url, token):
# return '%s%s?:embed=y&:showShareOptions=false&TOKEN=%s' % (supervisord.dashboard_server, report_url, token)
return '/report?name=%s&url=%s' % (report_name, report_url)
def mail_pop3_login(email, passwd):
payload = {
'email': aes_cipher.encrypt(email),
'password': aes_cipher.encrypt(passwd),
'sign': hashlib.sha1('%s:%s:%s' % (email, passwd, conf.mail_relay_key)).hexdigest()
}
req = requests.post(conf.mail_relay_url, data=payload)
return req.status_code == 200
def get_tab_token_session():
tsess = r.hgetall('tableau_session')
if len(tsess) == 2:
return tsess['xsrf_token'], tsess['workgroup_session_id']
# Establish a session so we can retain the cookies
req_sess = requests.Session()
xsrf_token, workgroup_session_id = tab_api.tab_login(req_sess)
r.hset('tableau_session', 'xsrf_token', xsrf_token)
r.hset('tableau_session', 'workgroup_session_id', workgroup_session_id)
r.expire('tableau_session', timedelta(hours=3))
return xsrf_token, workgroup_session_id
def init_logger():
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
work_dir, _ = os.path.split(os.path.abspath(__file__))
log_dir = work_dir + '/logs'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
console_handler = logging.StreamHandler()
file_suffix = datetime.today().strftime('%Y%m%d')
logfile_name = '%s/%s.%s' % (log_dir, 'tab_report.log', file_suffix)
file_handler = logging.FileHandler(logfile_name)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
init_logger()
cnx_pool = MySQLConnectionPool(pool_name="tab_pool", pool_size=conf.mysql_pool_size, **conf.dbconfig)
logging.info('connected to mysql db:%s', conf.dbconfig['host'])
aes_cipher = AESCipher(conf.mail_relay_key)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--port', type=int, default=5000, help='Service Port')
args = parser.parse_args()
# mail.connect_mailbox()
app.run(host='0.0.0.0', port=args.port, debug=False)