六十三:CSRF攻击与防御之系统准备之登录与转账功能

 

登录功能

在forms里面添加验证

class LoginForm(Form):
email = StringField(validators=[Email(message='邮箱格式错误')])
password = StringField(validators=[Length(3, 20, message='用户名长度3~20位')])

在视图中添加登录的视图

class LoginView(views.MethodView):
""" 登录视图 """

def get(self):
return render_template('login.html')

def post(self):
form = LoginForm(request.form)
if form.validate():
email = form.email.data
password = form.password.data
user = User.query.filter(User.email == email, User.password == password).first()
if user:
session['user_id'] = user.id
return '登录成功'
else:
return '邮箱或密码错误'


app.add_url_rule('/login/', view_func=LoginView.as_view('login'))

页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="" method="post">
<table>
<tbody>
<tr>
<td>邮箱:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="点击登录"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

在首页中添加入口

 

转账功能

转账接口需登录后才能访问

from functools import wraps
from flask import session, redirect, url_for


def login_required(func):
""" 登录验证 """

@wraps(func)
def wrapper(*args, **kwargs):
if session.get('user_id'):
return func(*args, **kwargs)
else:
return redirect(url_for('login'))

return wrapper

转账验证

class TransferForm(Form):
email = StringField(validators=[Email(message='邮箱格式错误')])
money = FloatField(validators=[NumberRange(1, 100000, message='金额区间为1~100000')])

视图

class TransferView(views.MethodView):
""" 转账的视图 """

decorators = [login_required] # 转账接口需登录后才能访问

def get(self):
return render_template('transfer.html')

def post(self):
form = TransferForm(request.form)
if form.validate():
email = form.email.data
money = form.money.data
user = User.query.filter_by(email=email).first()
if user:
user_id = session.get('user_id')
myself = User.query.get(user_id)
if myself.deposit >= money:
user.deposit += money
myself.deposit -= money
db.session.commit()
return '转账成功'
else:
return '余额不足'
else:
return '数据不正确'


app.add_url_rule('/transfer/', view_func=TransferView.as_view('transfer'))

页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>转账</title>
</head>
<body>
<form action="" method="post">
<table>
<tbody>
<tr>
<td>转到邮箱:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>转账金额:</td>
<td><input type="text" name="money"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="点击转账"></td>
</tr>
</tbody>
</table>
</form>

</body>
</html>

在首页中加入口

登录并转账

 

posted @ 2019-11-14 23:01  向前走。  阅读(306)  评论(0编辑  收藏  举报