帮我实现html登陆及登出页面,支持token保存和验证,后端是tornado,给出代码
时间: 2023-05-18 20:05:40 浏览: 255
前端代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<form id="login-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<button type="submit">Login</button>
</form>
<script>
const loginForm = document.querySelector('#login-form');
loginForm.addEventListener('submit', async (event) => {
event.preventDefault();
const username = document.querySelector('#username').value;
const password = document.querySelector('#password').value;
const response = await fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({username, password})
});
const data = await response.json();
if (data.token) {
localStorage.setItem('token', data.token);
window.location.href = '/dashboard';
} else {
alert(data.message);
}
});
</script>
</body>
</html>
后端代码:
import tornado.web
import tornado.ioloop
import jwt
SECRET_KEY = 'my-secret-key'
class LoginHandler(tornado.web.RequestHandler):
def post(self):
username = self.get_argument('username')
password = self.get_argument('password')
if username == 'admin' and password == 'admin':
token = jwt.encode({'username': username}, SECRET_KEY, algorithm='HS256')
self.write({'token': token.decode()})
else:
self.write({'message': 'Invalid username or password'})
class DashboardHandler(tornado.web.RequestHandler):
def get(self):
token = self.request.headers.get('Authorization')
if not token:
self.redirect('/login')
return
try:
decoded_token = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
username = decoded_token['username']
self.write(f'Welcome, {username}!')
except jwt.exceptions.DecodeError:
self.redirect('/login')
return
class LogoutHandler(tornado.web.RequestHandler):
def get(self):
token = self.request.headers.get('Authorization')
if token:
localStorage.removeItem('token')
self.redirect('/login')
if __name__ == '__main__':
app = tornado.web.Application([
(r'/login', LoginHandler),
(r'/dashboard', DashboardHandler),
(r'/logout', LogoutHandler),
])
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
阅读全文