forked from COSCUP/COSCUP-Volunteer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
279 lines (225 loc) · 8.58 KB
/
main.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import logging
logging.basicConfig(
filename='./log/log.log',
format='%(asctime)s [%(levelname)-5.5s][%(thread)6.6s] [%(module)s:%(funcName)s#%(lineno)d]: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.DEBUG)
import hashlib
import os
import traceback
#import re
from urllib.parse import parse_qs
from urllib.parse import urlparse
import arrow
import google_auth_oauthlib.flow
from apiclient import discovery
from flask import Flask
from flask import g
from flask import got_request_exception
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from markdown import markdown
import setting
from celery_task.task_mail_sys import mail_sys_weberror
from models.mailletterdb import MailLetterDB
from module.mattermost_bot import MattermostTools
from module.mc import MC
from module.oauth import OAuth
from module.team import Team
from module.users import User
from module.usession import USession
from view.api import VIEW_API
from view.guide import VIEW_GUIDE
from view.links import VIEW_LINKS
from view.project import VIEW_PROJECT
from view.sender import VIEW_SENDER
from view.setting import VIEW_SETTING
from view.tasks import VIEW_TASKS
from view.team import VIEW_TEAM
from view.user import VIEW_USER
app = Flask(__name__)
app.config['SESSION_COOKIE_SECURE'] = True
app.secret_key = setting.SECRET_KEY
app.register_blueprint(VIEW_API)
app.register_blueprint(VIEW_GUIDE)
app.register_blueprint(VIEW_LINKS)
app.register_blueprint(VIEW_PROJECT)
app.register_blueprint(VIEW_SENDER)
app.register_blueprint(VIEW_SETTING)
app.register_blueprint(VIEW_TASKS)
app.register_blueprint(VIEW_TEAM)
app.register_blueprint(VIEW_USER)
NO_NEED_LOGIN_PATH = (
'/',
'/oauth2callback',
'/logout',
'/links/chat',
'/privacy',
'/bug-report',
'/robots.txt',
'/api/members',
)
@app.before_request
def need_login():
app.logger.info('[X-SSL-SESSION-ID: %s] [X-REAL-IP: %s] [USER-AGENT: %s] [SESSION: %s]' % (
request.headers.get('X-SSL-SESSION-ID'),
request.headers.get('X-REAL-IP'),
request.headers.get('USER-AGENT'),
session, )
)
if request.path.startswith('/user') and request.path[-1] == '/':
return redirect(request.path[:-1])
if 'sid' in session and session['sid']:
mc = MC.get_client()
user_g_data = mc.get('sid:%s' % session['sid'])
if user_g_data:
g.user = user_g_data
else:
session_data = USession.get(session['sid'])
if session_data:
uid = session_data['uid']
g.user = {}
g.user['account'] = User(uid=session_data['uid']).get()
if g.user['account']:
g.user['data'] = OAuth(mail=g.user['account']['mail']).get()['data']
g.user['participate_in'] = [{'pid': team['pid'], 'tid': team['tid'], 'name': team['name']} for team in Team.participate_in(uid=session_data['uid'])]
mc.set('sid:%s' % session['sid'], g.user, 600)
else:
session.pop('sid', None)
session['r'] = request.path
return redirect(url_for('oauth2callback', _scheme='https', _external=True))
else:
session.pop('sid', None)
session['r'] = request.path
return redirect(url_for('oauth2callback', _scheme='https', _external=True))
else:
if request.path.startswith('/tasks'):
return
if request.path not in NO_NEED_LOGIN_PATH:
# ----- Let user profile public ----- #
#if re.match(r'(\/user\/[a-z0-9]{8}).*', request.path):
# return
session['r'] = request.path
app.logger.info('r: %s' % session['r'])
return redirect(url_for('oauth2callback', _scheme='https', _external=True))
@app.after_request
def no_store(response):
''' return no-store '''
if 'sid' in session and session['sid']:
response.headers['Cache-Control'] = 'no-store'
return response
@app.route('/')
def index():
if 'user' not in g:
return render_template('index.html')
check = {
'profile': False,
'participate_in': False,
'mattermost': False,
}
if 'profile' in g.user['account'] and 'intro' in g.user['account']['profile']:
if len(g.user['account']['profile']['intro']) > 100:
check['profile'] = True
if list(Team.participate_in(uid=g.user['account']['_id'])):
check['participate_in'] = True
if MattermostTools.find_possible_mid(uid=g.user['account']['_id']):
check['mattermost'] = True
return render_template('index_guide.html', check=check)
@app.route('/oauth2callback')
def oauth2callback():
if 'r' in request.args and request.args['r'].startswith('/'):
session['r'] = request.args['r']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'./client_secret.json',
scopes=(
'openid',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
),
redirect_uri='https://%s/oauth2callback' % setting.DOMAIN,
)
if 'code' not in request.args:
authorization_url, state = flow.authorization_url(
access_type='offline',
include_granted_scopes='true',
state=hashlib.sha256(os.urandom(2048)).hexdigest(),
)
session['state'] = state
return redirect(authorization_url)
url = request.url.replace('http://', 'https://')
url_query = parse_qs(urlparse(url).query)
if 'state' in url_query and url_query['state'] and url_query['state'][0] == session.get('state'):
flow.fetch_token(authorization_response=url)
auth_client = discovery.build('oauth2', 'v2', credentials=flow.credentials, cache_discovery=False)
user_info = auth_client.userinfo().get().execute()
# ----- save oauth info ----- #
OAuth.add(mail=user_info['email'], data=user_info, token=flow.credentials)
# ----- Check account or create ----- #
owner = OAuth.owner(mail=user_info['email'])
if owner:
user = User(uid=owner).get()
else:
user = User.create(mail=user_info['email'])
MailLetterDB().create(uid=user['_id'])
user_session= USession.make_new(uid=user['_id'], header=dict(request.headers))
session['sid'] = user_session.inserted_id
if 'r' in session:
r = session['r']
app.logger.info('login r: %s' % r)
session.pop('r', None)
session.pop('state', None)
return redirect(r)
return redirect(url_for('index', _scheme='https', _external=True))
else:
session.pop('state', None)
return redirect(url_for('oauth2callback', _scheme='https', _external=True))
@app.route('/logout')
def oauth2logout():
''' Logout
**GET** ``/logout``
:return: Remove cookie/session.
'''
if 'sid' in session:
USession.make_dead(sid=session['sid'])
session.pop('state', None)
session.pop('sid', None)
return redirect(url_for('index', _scheme='https', _external=True))
@app.route('/privacy')
def privacy():
mc = MC.get_client()
content = mc.get('page:privacy')
if not content:
with open('./privacy.md', 'r') as files:
content = markdown(files.read())
mc.set('page:privacy', content, 3600)
return render_template('./privacy.html', content=content)
@app.route('/bug-report')
def bug_report():
return render_template('./bug_report.html')
@app.route('/robots.txt')
def robots():
return u'''User-agent: *
Allow: /'''
@app.route('/exception')
def exception():
try:
1/0
except Exception as e:
raise Exception('Error: [%s]' % e)
def error_exception(sender, exception, **extra):
mail_sys_weberror.apply_async(
kwargs={
'title': u'%s %s %s' % (request.method, request.path, arrow.now()),
'body': '''<b>%s</b> %s<br>
<pre>%s</pre>
<pre>%s</pre>
<pre>User: %s\n\nsid: %s\n\nargs: %s\n\nform: %s\n\nvalues: %s\n\n%s</pre>''' %
(request.method, request.path, os.environ, request.headers,
g.get('user', {}).get('account', {}).get('_id'), session.get('sid'), request.args, request.form, request.values, traceback.format_exc())
})
got_request_exception.connect(error_exception, app)
if __name__ == '__main__':
app.run(debug=False, host=setting.SERVER_HOST, port=setting.SERVER_PORT)