-
Notifications
You must be signed in to change notification settings - Fork 0
/
route_user.py
428 lines (358 loc) · 16.3 KB
/
route_user.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import math
import random
import oauth2 as oauth
from flask import Blueprint, json, redirect, url_for
from flask_login import login_user, login_required
from config import discord
from constants import SMS_SEVENIO_KEY, TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_KEY_SECRET, DISCORD_BOT_TOKEN, \
DISCORD_CLIENT_KEY
from db_access import *
from discord_check import check_discord, update_users
from email_confirmation import create_verify_email, create_reset_pass_email
from forms import verify_captcha, LoginForm, RegisterForm
from util_geoloc import set_session_geo_lang
from util_render_template import setup_home_template
from utils import *
# Create OAUTH client.
consumer = oauth.Consumer(key=TWITTER_CONSUMER_KEY, secret=TWITTER_CONSUMER_KEY_SECRET)
client = oauth.Client(consumer)
user = Blueprint('user', __name__)
def tweet_twitter():
token = oauth.Token('1486009629792698369-q6Zv5ksJ3OCOi76XP7Q637Mpd9FWGf',
'3OBx6AbCb1SyAZHqNPFrufS8ptqVAkzvgc8lHdTdY3B7j')
# consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer, token)
data = {'status': 'hello world'}
request_uri = 'https://api.twitter.com/1/statuses/update.json'
resp, content = client.request(request_uri, 'POST', urllib.parse.urlencode(data))
pass
@user.route('/login', methods=['POST'])
def login():
# captcha_response = login_form.data['recaptcha']
captcha_response = json.loads(request.data)['recaptcha']
set_session_geo_lang()
# verify captcha
debug_out('login: verifying captcha')
if verify_captcha(captcha_response):
login_form = LoginForm()
if login_form.validate_on_submit():
email = login_form.email.data
password = login_form.password.data
# rememberme = login_form.rememberme.data
next_request = request.args.get('next')
# is_safe_url should check if the url is safe for redirects.
# See http://flask.pocoo.org/snippets/62/ for an example.
if not is_safe_url(next_request):
return flask.abort(400)
# verify valid email
if email_valid(email):
# check user exists and then verify password
debug_out('login: authenticating')
user_db = db_user_verification(email, password)
if user_db is not None:
if user_db.is_active():
# log the login
debug_out('login: update login db')
db_new_login(login_form)
session['logged_in'] = True
session['lang'] = user_db.get_lang()
# debug_out('login: flask login')
login_user(user_db, remember=login_form.rememberme.data)
output = user_db.serialize()
session['admin'] = user_db.is_admin()
# output['page'] = 'profile'
debug_out('login: done, reloading website, check ajax success output')
return jsonify(output)
# return render_template('page-gamehistory.html', page_call='profile')
# return redirect(next or url_for('profile'))
else:
return jsonify(error=translations['created not verified'][session['lang']],
resend_email=email,
link_text=translations['resend verification'][session['lang']])
else:
return jsonify(error=translations['invalid email or password'][session['lang']])
else:
return jsonify(error=translations['invalid email format'][session['lang']])
else:
if len(login_form.email.errors):
email_error = login_form.email.errors[0]
else:
email_error = ''
if len(login_form.password.errors):
password_error = login_form.password.errors[0]
else:
password_error = ''
if email_error or password_error:
return jsonify(error="", email_error=email_error, password_error=password_error)
else:
return jsonify(error=translations['reload:msg'][session['lang']])
else:
return jsonify({"error": translations['recaptcha not verified'][session['lang']]})
# if LoginForm().validate_on_submit():
# return "the form has been submitted. Success!"
# @user.route('/lang/<lang>', methods=['GET'])
# def language(lang):
# if len(lang) > 0:
# session['lang'] = lang
# if 'logged_in' in session and session['logged_in'] is True:
# db_set_language()
# else:
# # set_session_geo_lang(request.remote_addr)
# set_session_geo_lang()
#
# set_flag_from_lang()
# return redirect(url_for('home'))
# # return setup_home_template()
@user.route('/forgot_pass', methods=['POST'])
def forgot_pass():
# check if the email is a user
email = json.loads(request.data)['email']
if db_getuser_email(email) is not None:
create_reset_pass_email(email, translations)
return jsonify(notification_title=translations['check email'][session['lang']],
notification=translations['email sent to'][session['lang']])
# return redirect(url_for('home', notification='Token expired, please try again',
# notification_title='Reset Password'), code=307)
@user.route("/set_password", methods=['POST'])
def set_password():
email = session.pop("email", None)
password = json.loads(request.data)['password']
if db_set_password(email, password) is not None:
return jsonify(notification=translations['password has been updated'][session['lang']],
notification_title=translations['reset password'][session['lang']], reset_pass_popup=False)
else:
return setup_home_template(notification='Account not found',
notification_title=translations['reset password'][session['lang']],
reset_pass_popup=False)
@user.route('/resend', methods=['POST'])
@login_required
def resend():
email = json.loads(request.data)['email'][0:-1]
create_verify_email(email, translations)
return jsonify(notification_title=translations['check email'][session['lang']],
notification=translations['email sent to'][session['lang']])
@user.route('/register', methods=['GET', 'POST'])
def register():
# if 'lang' not in session:
# session['lang'] = 'zh-tw'
# sharing the same captcha as login
captcha_response = json.loads(request.data)['recaptcha']
# verify captcha
if verify_captcha(captcha_response):
register_form = RegisterForm()
email = register_form.email.data
if email_valid(email):
password_not_valid = validate_password(register_form.password.data, session['lang'])
username = register_form.username.data
if len(username) > 2:
# CHANGE this to == 0 on production
if len(password_not_valid) != 0:
# check email exists
user = db_getuser_email(email)
if user is None:
# check username exists
user = db_getuser_username(username)
if user is None:
# create the user
create_verify_email(email, translations)
db_new_user(register_form)
return jsonify(notification_title=translations['check email'][session['lang']],
notification=translations['email sent to'][session['lang']])
else:
if user.is_active():
return jsonify(error=translations['account exists'][session['lang']])
else:
return jsonify(error=translations['account exists but not activated'][session['lang']],
resend_email=email,
link_text=translations['resend verification'][session['lang']])
else:
if user.is_active():
return jsonify(error=translations['account exists'][session['lang']])
else:
return jsonify(error=translations['account exists but not activated'][session['lang']],
resend_email=email,
link_text=translations['resend verification'][session['lang']])
else:
return jsonify(error=password_not_valid)
else:
return jsonify(error=translations['username more than 2'][session['lang']])
else:
return jsonify(error=translations['invalid email format'][session['lang']])
else:
return jsonify(error=translations['recaptcha not verified'][session['lang']])
@user.route('/oauth/twitter', methods=['GET', 'POST'])
# @login_required
def oauth_twitter():
if 'oauth_token' in request.args:
# make sure oauth_token matches
# db_user = db_get_user()
# db_user.oauth_token = request.args['oauth_token']
# match = UserEntry().query.filter_by(oauth_token=request.args['oauth_token']).first()
if session['oauth_token'] == request.args['oauth_token']:
if 'oauth_verifier' in request.args:
# request_token = session['request_token']
token = oauth.Token(
session['oauth_token'],
session['oauth_token_secret']
)
token.set_verifier(request.args['oauth_verifier'])
oauth_client = oauth.Client(consumer, token)
# Request token URL for Twitter.
request_token_url = "https://api.twitter.com/oauth/access_token"
headers = {
# 'Accept': '*/*',
# 'Connection': 'close',
# 'User-Agent': 'OAuth gem v0.4.4',
'Content-Type': 'application/x-www-form-urlencoded',
# 'Content-Length': '76',
# 'Host': 'api.twitter.com'
}
resp, content = oauth_client.request(request_token_url, "POST", headers=headers)
params = content.decode("utf-8")
user = db_get_user()
if user:
twitter_name = parseURLparam(params, 'screen_name')
user.oauth_token = parseURLparam(params, 'oauth_token')
user.oauth_token_secret = parseURLparam(params, 'oauth_token_secret')
user.twt_user_id = parseURLparam(params, 'user_id')
user.snb_twitter = twitter_name
db.session.commit()
session['notify'] = 'oauth'
session['twitter_name'] = twitter_name
return redirect(url_for('home'))
else:
flask.abort(69)
# return setup_home_template(notification=translations['snb:subtask:twt:success'][session['lang']],
# notification_title=translations['snb:subtask:twt'][session['lang']])
return redirect(url_for('home'))
def parseURLparam(big_str, small_str):
index = big_str.find(small_str) + 1
index += len(small_str)
search_str = big_str[index:]
amp = search_str.find('&')
param = search_str[:amp]
return param
@user.route('/submit_tweet_url', methods=['POST'])
@login_required
def submit_tweet_url():
try:
url = json.loads(request.data)['url']
db_user = db_get_user()
db_user.snb_twitter_url = url
db.session.commit()
return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}
except():
return json.dumps({'success': False}), 500, {'ContentType': 'application/json'}
@user.route('/connect_twitter', methods=['GET'])
@login_required
def connect_twitter():
# Create your consumer with the proper key/secret.
# consumer = oauth.Consumer(key=TWITTER_CONSUMER_KEY,
# secret=TWITTER_CONSUMER_KEY_SECRET)
# Request token URL for Twitter.
request_token_url = "https://api.twitter.com/oauth/request_token"
# Create our client.
# client = oauth.Client(consumer)
# The OAuth Client request works just like httplib2 for the most part.
resp, content = client.request(request_token_url, "GET")
# Save auth_token
params = content.decode("utf-8")
# auth_token = parseURLparam(params, 'auth_token')
if parseURLparam(params, 'oauth_callback_confirmed'):
session['oauth_token'] = parseURLparam(params, 'oauth_token')
session['oauth_token_secret'] = parseURLparam(params, 'oauth_token_secret')
# pass
return 'https://api.twitter.com/oauth/authorize?' + content.decode("utf-8")
# return redirect('https://api.twitter.com/oauth/authorize?' + content.decode("utf-8"))
@user.route('/verifySMSOTP', methods=['GET', 'POST'])
@login_required
def verifySMScode():
code = json.loads(request.data)['code']
db_user = db_get_user()
difference = datetime.datetime.now() - db_user.snb_phone_time
if difference.seconds > 900:
return jsonify(error=2)
if db_user.snb_phone_otp == code:
db_user.snb_phone = True
db.session.commit()
return jsonify(error=0)
else:
return jsonify(error=1)
@user.route('/confirm_tweet', methods=['POST'])
@login_required
def confirm_tweet():
user_id = json.loads(request.data)['user_id']
user_db = db_get_user_from_id(user_id)
user_db.snb_twitter = True
db.session.commit()
return jsonify(user_id=user_id)
@user.route('/oauth/discord', methods=['GET'])
@login_required
def oauth_discord():
# try:
# if 'state' in request.args:
# callback = oauth_discord_callback()
# else:
# callback = discord.create_session()
# except:
# callback = discord.create_session()
# return callback
return discord.create_session()
@user.route('/oauth/discord/callback', methods=['GET', 'POST'])
@login_required
def oauth_discord_callback():
discord.callback()
user = discord.fetch_user()
# check user is in the discord
if check_discord(user):
db_user = db_get_user()
db_user.snb_discord = user.name
db.session.commit()
session['notify'] = 'discord:yes'
return redirect(url_for("home"))
session['notify'] = 'discord:no'
return redirect(url_for("home"))
# return f"""
# <html>
# <head>
# <title>{user.name}</title>
# </head>
# <body>
# <img src='{user.avatar_url}' />
# </body>
# </html>"""
@user.route('/send_SMS', methods=['GET', 'POST'])
@login_required
def send_SMS():
url_target = 'https://gateway.sms77.io/api/sms'
to = json.loads(request.data)['recipient']
# create OTP code
digits = "0123456789"
otp_code = ""
for i in range(4):
otp_code += digits[math.floor(random.random() * 10)]
phoneEntry = UserEntry().query.filter_by(snb_phone_number=to).first()
db_user = db_get_user()
if phoneEntry and phoneEntry is not db_user:
return jsonify(error=2)
message = translations['sms:title'][session['lang']] + ' ' + otp_code + '\n' + \
translations['sms:expires'][session['lang']]
payload = {'p': SMS_SEVENIO_KEY,
'to': to,
'from': "Gambit's",
'text': message
}
x = requests.post(url_target, data=payload)
try:
# if x.content.decode("utf-8").split('\n')[0] == '100':
if x.content.decode("utf-8") == '100':
db_user.snb_phone_number = to
db_user.snb_phone_otp = otp_code
db_user.snb_phone_time = datetime.datetime.now(tz=pytz.timezone('Asia/Shanghai'))
db.session.commit()
return jsonify(error=0)
else:
return jsonify(error=1)
except:
return jsonify(error=1)
return jsonify(error=1)