First step towards flask security user handling
This commit is contained in:
parent
808e0d80d3
commit
bbfa7b9341
130
app/main.py
130
app/main.py
|
@ -5,6 +5,8 @@ from flask import render_template, make_response
|
|||
from flask import request, redirect, g
|
||||
from flask import url_for
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask.ext.security import Security, SQLAlchemyUserDatastore, \
|
||||
UserMixin, RoleMixin, login_required, utils
|
||||
import uuid
|
||||
import hashlib
|
||||
import time
|
||||
|
@ -13,38 +15,53 @@ from functools import wraps
|
|||
app = Flask(__name__)
|
||||
DATABASE = '/data/rollerverbrauch.db'
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+DATABASE
|
||||
sqldb = SQLAlchemy(app)
|
||||
db = SQLAlchemy(app)
|
||||
|
||||
DEBUG = True
|
||||
SECRET_KEY = 'development key'
|
||||
app.config['DEBUG'] = True
|
||||
app.config['SECRET_KEY'] = 'development key'
|
||||
app.config['SECURITY_PASSWORD_HASH'] = 'pbkdf2_sha512'
|
||||
app.config['SECURITY_PASSWORD_SALT'] = 'xxxxxxxxxxxxxxxxxxxxxx'
|
||||
app.config.from_object(__name__)
|
||||
|
||||
|
||||
class User(sqldb.Model):
|
||||
id = sqldb.Column(sqldb.Integer, primary_key=True)
|
||||
username = sqldb.Column(sqldb.String(80), unique=True)
|
||||
email = sqldb.Column(sqldb.String(120), unique=True)
|
||||
salt = sqldb.Column(sqldb.String(8))
|
||||
password_hash = sqldb.Column(sqldb.String(64))
|
||||
roles_users = db.Table('roles_users',
|
||||
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
|
||||
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
|
||||
|
||||
def __init__(self, username, email, password):
|
||||
self.username = username
|
||||
self.email = email
|
||||
self.salt = uuid.uuid4().hex
|
||||
m = hashlib.sha256(password.encode('utf-8'))
|
||||
m = hashlib.sha256((m.hexdigest() + self.salt).encode('utf-8')).hexdigest()
|
||||
self.password_hash = m
|
||||
pass
|
||||
|
||||
class Role(db.Model, RoleMixin):
|
||||
id = db.Column(db.Integer(), primary_key=True)
|
||||
name = db.Column(db.String(80), unique=True)
|
||||
description = db.Column(db.String(255))
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.name)
|
||||
|
||||
|
||||
class User(db.Model, UserMixin):
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
email = db.Column(db.String(255), unique=True)
|
||||
password = db.Column(db.String(255))
|
||||
active = db.Column(db.Boolean())
|
||||
confirmed_at = db.Column(db.DateTime())
|
||||
roles = db.relationship(
|
||||
'Role',
|
||||
secondary=roles_users,
|
||||
backref=db.backref('users', lazy='dynamic')
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return '<User %r>' % self.username
|
||||
|
||||
|
||||
class Pitstop(sqldb.Model):
|
||||
id = sqldb.Column(sqldb.Integer, primary_key=True)
|
||||
date = sqldb.Column(sqldb.Date)
|
||||
odometer = sqldb.Column(sqldb.Integer)
|
||||
litres = sqldb.Column(sqldb.Numeric(5,2))
|
||||
class Pitstop(db.Model):
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
date = db.Column(db.Date)
|
||||
odometer = db.Column(db.Integer)
|
||||
litres = db.Column(db.Numeric(5,2))
|
||||
|
||||
def __init__(self, odometer, litres, date):
|
||||
self.odometer = odometer
|
||||
|
@ -54,41 +71,31 @@ class Pitstop(sqldb.Model):
|
|||
def __repr__(self):
|
||||
return '<Pitstop %r km, %r l>' % (self.odometer, self.litres)
|
||||
|
||||
sqldb.create_all()
|
||||
if User.query.filter_by(username='jlusiardi').first() is None:
|
||||
user1 = User('jlusiardi', 'joachim@lusiardi.de', 'pitstops')
|
||||
sqldb.session.add(user1)
|
||||
sqldb.session.commit()
|
||||
|
||||
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
|
||||
security = Security(app, user_datastore)
|
||||
|
||||
def check_auth(username, password):
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if user is None:
|
||||
return False
|
||||
salt = user.salt
|
||||
m = hashlib.sha256(password.encode('utf-8'))
|
||||
m = hashlib.sha256((m.hexdigest()+salt).encode('utf-8'))
|
||||
digest = m.hexdigest()
|
||||
ok = (User.query.filter_by(username=username, password_hash=digest).first() is not None)
|
||||
if not ok:
|
||||
app.logger.error("digest: " + digest)
|
||||
return ok
|
||||
@app.before_first_request
|
||||
def before_first_request():
|
||||
db.create_all()
|
||||
|
||||
user_datastore.find_or_create_role(name='admin', description='Administrator')
|
||||
user_datastore.find_or_create_role(name='end-user', description='End user')
|
||||
|
||||
def authenticate():
|
||||
resp = make_response(render_template('login_required.html'), 401)
|
||||
resp.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
|
||||
return resp
|
||||
encrypted_password = utils.encrypt_password('password')
|
||||
if not user_datastore.get_user('someone@example.com'):
|
||||
user_datastore.create_user(email='someone@example.com', password=encrypted_password)
|
||||
if not user_datastore.get_user('admin@example.com'):
|
||||
user_datastore.create_user(email='admin@example.com', password=encrypted_password)
|
||||
|
||||
# Commit any database changes; the User and Roles must exist before we can add a Role to the User
|
||||
db.session.commit()
|
||||
|
||||
def requires_auth(f):
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
auth = request.authorization
|
||||
if not auth or not check_auth(auth.username, auth.password):
|
||||
return authenticate()
|
||||
return f(*args, **kwargs)
|
||||
return decorated
|
||||
# Give one User has the "end-user" role, while the other has the "admin" role. (This will have no effect if the
|
||||
# Users already have these Roles.) Again, commit any database changes.
|
||||
user_datastore.add_role_to_user('someone@example.com', 'end-user')
|
||||
user_datastore.add_role_to_user('admin@example.com', 'admin')
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@app.before_request
|
||||
|
@ -96,19 +103,14 @@ def before_request():
|
|||
g.data = {}
|
||||
|
||||
|
||||
@app.teardown_request
|
||||
def teardown_request(exception):
|
||||
pass
|
||||
|
||||
|
||||
@app.route('/')
|
||||
@requires_auth
|
||||
@login_required
|
||||
def index():
|
||||
return redirect(url_for('get_pit_stops'))
|
||||
|
||||
|
||||
@app.route('/pitstops', methods=['POST'])
|
||||
@requires_auth
|
||||
@login_required
|
||||
def create_pit_stop():
|
||||
last_pitstop = Pitstop.query.order_by(Pitstop.date.desc()).first()
|
||||
if last_pitstop is None:
|
||||
|
@ -152,14 +154,14 @@ def create_pit_stop():
|
|||
return render_template('newPitStopForm.html', data=data)
|
||||
|
||||
new_stop = Pitstop(odometer, litres, datetime.strptime(date_of_pitstop, '%Y-%m-%d'))
|
||||
sqldb.session.add(new_stop)
|
||||
sqldb.session.commit()
|
||||
db.session.add(new_stop)
|
||||
db.session.commit()
|
||||
|
||||
return redirect(url_for('get_pit_stops'))
|
||||
|
||||
|
||||
@app.route('/pitstops/createForm', methods=['GET'])
|
||||
@requires_auth
|
||||
@login_required
|
||||
def create_pit_stop_form():
|
||||
last_stop = Pitstop.query.order_by(Pitstop.date.desc()).first()
|
||||
if last_stop is None:
|
||||
|
@ -174,7 +176,7 @@ def create_pit_stop_form():
|
|||
|
||||
|
||||
@app.route('/pitstops', methods=['GET'])
|
||||
@requires_auth
|
||||
@login_required
|
||||
def get_pit_stops():
|
||||
data = prepare_pit_stops(Pitstop.query.all())
|
||||
g.data['pitstops'] = data
|
||||
|
@ -182,13 +184,13 @@ def get_pit_stops():
|
|||
|
||||
|
||||
@app.route('/manual', methods=['GET'])
|
||||
@requires_auth
|
||||
@login_required
|
||||
def get_manual():
|
||||
return render_template('manual.html', data=g.data)
|
||||
|
||||
|
||||
@app.route('/statistics', methods=['GET'])
|
||||
@requires_auth
|
||||
@login_required
|
||||
def get_statistics():
|
||||
pitstops = Pitstop.query.all()
|
||||
count = len(pitstops)
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
Flask
|
||||
Flask-SQLAlchemy
|
||||
Flask-Security
|
||||
|
|
|
@ -66,7 +66,7 @@
|
|||
{% endblock %}
|
||||
</div>
|
||||
</div>
|
||||
{{ current_user.email }}
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
|
Loading…
Reference in New Issue