forked from iceman2077/ttlock_admin_panel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
186 lines (152 loc) · 6.59 KB
/
Copy pathauth.py
File metadata and controls
186 lines (152 loc) · 6.59 KB
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
# --- Add to auth.py ---
import hashlib
import requests
import logging
import time
from flask import Blueprint, render_template, request, redirect, url_for, flash, session
from flask_login import login_user, logout_user, login_required
from .models import db, User
from .api_requests import TTLockConfigError, get_token, get_ttlock_config
log = logging.getLogger(__name__)
auth = Blueprint('auth', __name__)
@auth.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
email = request.form.get('email', '')
password = request.form.get('password', '')
confirm = request.form.get('confirm_password', '')
if not email or not password or not confirm:
flash("All fields are required", "danger")
return redirect(url_for('auth.register'))
if password != confirm:
flash("Passwords do not match", "danger")
return redirect(url_for('auth.register'))
session['pending_email'] = email
session['pending_password'] = password
try:
config = get_ttlock_config()
except TTLockConfigError as exc:
log.error("TTLock configuration error while sending verification code: %s", exc)
flash("TTLock configuration is missing or invalid.", "danger")
return redirect(url_for('auth.register'))
payload = {
'clientId': config.client_id,
'username': email
}
r = requests.post("https://euapi.ttlock.com/v3/user/sendRegisterVerificationCode", data=payload)
log.debug("[sendVerification] Sent verification code request for %s", email)
log.debug("[sendVerification] Response: %s %s", r.status_code, r.text)
try:
response_data = r.json()
except Exception as e:
log.error(f"[sendVerification] Failed to parse JSON: {e}")
flash("API error — invalid response format.", "danger")
return redirect(url_for('auth.register'))
if r.ok and response_data.get('errcode') == 0:
return redirect(url_for('auth.verify'))
else:
flash(response_data.get('errmsg', 'Failed to send code'), 'danger')
return redirect(url_for('auth.register'))
return render_template('register.html')
@auth.route('/verify', methods=['GET', 'POST'])
def verify():
if request.method == 'POST':
email = session.get('pending_email')
raw_password = session.get('pending_password')
code = request.form.get('code', '')
if not email or not raw_password or not code:
flash("Missing verification information.", "danger")
return redirect(url_for('auth.verify'))
try:
config = get_ttlock_config()
except TTLockConfigError as exc:
log.error("TTLock configuration error during verification: %s", exc)
flash("TTLock configuration is missing or invalid.", "danger")
return redirect(url_for('auth.verify'))
hashed_pw = hashlib.md5(raw_password.encode()).hexdigest()
payload = {
'clientId': config.client_id,
'clientSecret': config.client_secret,
'username': email,
'password': hashed_pw,
'code': code,
'date': int(time.time() * 1000)
}
r = requests.post("https://api.ttlock.com/v3/user/register", data=payload)
log.debug("[register] Submitted registration for %s", email)
log.debug("[register] Response: %s %s", r.status_code, r.text)
if r.ok and r.json().get('errcode') == 0:
new_user = User(username=email, password=hashed_pw)
db.session.add(new_user)
db.session.commit()
flash("Registered! You may now login.", "success")
return redirect(url_for('auth.login'))
else:
flash(r.json().get('errmsg', 'Registration failed'), 'danger')
return render_template('verify.html')
@auth.route('/login')
def login():
return render_template('login.html')
@auth.route('/login', methods=['POST'])
def login_post():
username = request.form.get('email', '').strip()
password_raw = request.form.get('password', '')
remember = True if request.form.get('remember') else False
if not username or not password_raw:
flash("Email and password are required.")
return redirect(url_for('auth.login'))
hashed_password = hashlib.md5(password_raw.encode('utf-8')).hexdigest()
log.debug("[login_post] Username: %s", username)
try:
request_user_ttlock = get_token(username, hashed_password)
except TTLockConfigError as exc:
log.error("TTLock configuration error during login: %s", exc)
flash("TTLock configuration is missing or invalid.")
return redirect(url_for('auth.login'))
try:
tt_response = request_user_ttlock.json()
except Exception as e:
flash("Could not decode TTLock response.")
log.error("[login_post] Invalid JSON response from TTLock: %s", e)
return redirect(url_for('auth.login'))
log.debug("[login_post] TTLock API response status: %s", request_user_ttlock.status_code)
if 'errcode' in tt_response:
flash(f"TTLock Error: {tt_response.get('errmsg', 'Unknown error')}")
return redirect(url_for('auth.login'))
access_token = tt_response.get('access_token')
refresh_token = tt_response.get('refresh_token')
uid = tt_response.get('uid')
openid = tt_response.get('openid')
scope = tt_response.get('scope')
if not all([access_token, uid, refresh_token]):
flash("TTLock did not return all required credentials.")
return redirect(url_for('auth.login'))
check_username = User.query.filter_by(username=username).first()
if check_username:
check_username.access_token = access_token
check_username.refresh_token = refresh_token
check_username.uid = uid
check_username.openid = openid
check_username.scope = scope
check_username.password = hashed_password
db.session.commit()
else:
new_user = User(
username=username,
uid=uid,
password=hashed_password,
access_token=access_token,
openid=openid,
scope=scope,
refresh_token=refresh_token
)
db.session.add(new_user)
db.session.commit()
user = User.query.filter_by(username=username).first()
login_user(user, remember=remember)
return redirect(url_for('main.index'))
@auth.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('auth.login'))