Skip to content

Commit 8c6411e

Browse files
committed
csrf demo
1 parent f80edd8 commit 8c6411e

7 files changed

Lines changed: 204 additions & 2 deletions

File tree

‎web/dblib/mysql_db.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,6 @@ def conn(self):
3737

3838
@staticmethod
3939
def close():
40-
MySQLdb.instance.conn.close()
41-
MySQLdb.instance = None
40+
if MySQLdb.instance is not None:
41+
MySQLdb.instance.conn.close()
42+
MySQLdb.instance = None

‎web/login/app.py‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#!/usr/bin/env python3
2+
3+
# author: greyshell
4+
5+
import os
6+
7+
from flask import Flask, render_template, session, redirect, url_for, jsonify
8+
from flask import request
9+
from flask_wtf.csrf import CSRFProtect
10+
from web.login.models import *
11+
12+
templates_path = os.path.abspath(
13+
'./template/'
14+
)
15+
app = Flask(__name__, template_folder=templates_path)
16+
app.config.update(dict(
17+
SECRET_KEY="woopie"
18+
))
19+
csrf = CSRFProtect(app)
20+
21+
22+
def get_logged_in_user():
23+
if "userid" not in session:
24+
return None
25+
return User.logged_user(session['userid'])
26+
27+
28+
@app.before_request
29+
def before_request_func():
30+
MySQLdb() # create database
31+
32+
33+
@app.after_request
34+
def after_request_func(response):
35+
MySQLdb.close()
36+
return response
37+
38+
39+
@app.route('/', methods=['GET', 'POST'])
40+
@csrf.exempt
41+
def index():
42+
user = get_logged_in_user()
43+
if user is not None:
44+
return redirect(url_for('welcome'))
45+
if request.method == 'GET':
46+
return render_template("index.html")
47+
username = request.form.get('username')
48+
password = request.form.get('password')
49+
user = User.get_user(username, password)
50+
if not user:
51+
return render_template("index.html", error="User not found")
52+
session['userid'] = user.id
53+
return redirect(url_for('welcome'))
54+
55+
56+
@app.route('/welcome', methods=['GET'])
57+
def welcome():
58+
user = get_logged_in_user()
59+
if user is None:
60+
return redirect(url_for("index"))
61+
return render_template('welcome.html', user=user)
62+
63+
64+
@app.route('/update_age', methods=['POST'])
65+
def update_age():
66+
user = get_logged_in_user()
67+
if user is None:
68+
return jsonify(status="User not logged in")
69+
age = int(request.form.get('age'))
70+
user.age = age
71+
success = user.save()
72+
if success[0]:
73+
return jsonify(status="Age successfully changed")
74+
else:
75+
return jsonify(status="error " + success[1])
76+
77+
78+
@app.route('/logout')
79+
@csrf.exempt
80+
def logout():
81+
if 'userid' in session:
82+
session['userid'] = None
83+
return redirect(url_for('index'))
84+
85+
86+
if __name__ == '__main__':
87+
app.run(port=5000, debug=True)

‎web/login/models/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from user import *

‎web/login/models/user.py‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
from mysql_db import MySQLdb
2+
3+
import traceback
4+
5+
6+
class User:
7+
8+
def __init__(self, details):
9+
self.id = details[0]
10+
self.username = details[1]
11+
self.name = details[3]
12+
self.age = details[4]
13+
14+
def save(self):
15+
db = MySQLdb()
16+
cursor = db.conn.cursor()
17+
rows = None
18+
try:
19+
user_input = (self.age, self.id) # pass the input in the form of a tuple
20+
query = "UPDATE tbl_users SET age = %s WHERE id = %s"
21+
cursor.execute(query, user_input)
22+
db.conn.commit()
23+
cursor.close()
24+
if cursor.rowcount != 0:
25+
return True, cursor.rowcount
26+
return False, cursor.rowcount
27+
28+
except Exception as e:
29+
print(e)
30+
traceback.print_exc()
31+
cursor.close()
32+
db.conn.close()
33+
return False, e
34+
35+
@staticmethod
36+
def get_user(username, password):
37+
# creating the cursor
38+
db = MySQLdb()
39+
cursor = db.conn.cursor()
40+
rows = None
41+
try:
42+
user_input = (username, password) # pass the input in the form of a tuple
43+
query = "SELECT * FROM tbl_users WHERE username = %s AND password = %s"
44+
cursor.execute(query, user_input)
45+
rows = cursor.fetchall()
46+
cursor.close()
47+
return User(rows[0])
48+
49+
except Exception as e:
50+
print(e)
51+
traceback.print_exc()
52+
cursor.close()
53+
db.conn.close()
54+
return None
55+
56+
@staticmethod
57+
def logged_user(user_id):
58+
# creating the cursor
59+
db = MySQLdb()
60+
cursor = db.conn.cursor()
61+
rows = None
62+
try:
63+
user_input = (user_id,) # pass the input in the form of a tuple
64+
query = "SELECT * FROM tbl_users WHERE id = %s"
65+
cursor.execute(query, user_input)
66+
rows = cursor.fetchall()
67+
cursor.close()
68+
return User(rows[0])
69+
70+
except Exception as e:
71+
print(e)
72+
traceback.print_exc()
73+
cursor.close()
74+
db.conn.close()
75+
return None

‎web/login/static/js/change_age.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
function changeAgeRequest() {
2+
var form = document.getElementById("change_age_form");
3+
alert(form);
4+
}

‎web/login/template/index.html‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<html>
2+
<head>
3+
<title>Login</title>
4+
</head>
5+
<body>
6+
<form method="post">
7+
Username: <input type="text" name="username"/> <br/>
8+
Password: <input type="password" name="password"/> <br/>
9+
<input type="submit"/> <br/>
10+
{% if error is defined %}
11+
Error: {{ error }}<br/>
12+
{% endif %}
13+
</form>
14+
</body>
15+
</html>

‎web/login/template/welcome.html‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<html>
2+
<head>
3+
<title>Login</title>
4+
<script src="{{ url_for('static', filename='js/change_age.js') }}"></script>
5+
</head>
6+
<body>
7+
Hello {{ user.name }}, your age is {{ user.age }} <br/>
8+
<a href="/logout">Log out</a><br/>
9+
10+
{% if notice is defined %}
11+
Notice: {{ notice }}<br/>
12+
{% endif %}
13+
14+
<form id="change_age_form">
15+
Change age: <input type="text" name="age"/><br/>
16+
<input type="button" value="submit" onclick="changeAgeRequest()"/>
17+
</form>
18+
</body>
19+
</html>

0 commit comments

Comments
 (0)