Add authentication for pre-existing users.

This commit is contained in:
Joachim Lusiardi 2015-08-03 22:24:55 +02:00
parent eb77d03ea3
commit a12d5f541b
4 changed files with 83 additions and 10 deletions

View File

@ -47,6 +47,29 @@ class Db(object):
return None return None
return services[0] return services[0]
def get_salt_for_user(self, user):
salt = self._perform_query_param('select salt from users where name = ?', [user])
if len(salt) == 0:
return None
return salt[0]['salt']
def check_password_for_user(self, user, password):
user = self._perform_query_param('select * from users where name = ? and password = ?', [user, password])
if len(user) == 0:
return False
return True
def _perform_query_param(self, query, data):
cursor = self.db.execute(query, data)
names = list(map(lambda x: x[0], cursor.description))
result = []
for row in cursor.fetchall():
row_result = {}
for index in range(0, len(names)):
row_result[names[index]] = row[index]
result.append(row_result)
return result
def _perform_query(self, query): def _perform_query(self, query):
cursor = self.db.execute(query) cursor = self.db.execute(query)
names = list(map(lambda x: x[0], cursor.description)) names = list(map(lambda x: x[0], cursor.description))

View File

@ -1,11 +1,15 @@
from datetime import datetime from datetime import datetime
from flask import Flask from flask import Flask
from flask import render_template from flask import render_template, make_response
from flask import request, redirect, g from flask import request, redirect, g
from flask import url_for from flask import url_for
from flask import Response
import hashlib
import os.path import os.path
import time import time
from functools import wraps
import db import db
#from db import Db #from db import Db
@ -13,10 +17,34 @@ app = Flask(__name__)
DATABASE = '/data/rollerverbrauch.db' DATABASE = '/data/rollerverbrauch.db'
DEBUG = True DEBUG = True
SECRET_KEY = 'development key' SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
app.config.from_object(__name__) app.config.from_object(__name__)
def check_auth(username, password):
salt = g.db2.get_salt_for_user(username)
if salt == None:
return False
m = hashlib.sha256(password.encode('utf-8'))
m = hashlib.sha256((m.hexdigest()+salt).encode('utf-8'))
digest = m.hexdigest()
ok = g.db2.check_password_for_user(username, digest)
if not ok:
app.logger.error("digest: " + digest)
return ok
def authenticate():
resp = make_response(render_template('login_required.html'), 401)
resp.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
return resp
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
@app.before_request @app.before_request
def before_request(): def before_request():
g.db2 = db.Db(app.config['DATABASE']) g.db2 = db.Db(app.config['DATABASE'])
@ -28,10 +56,12 @@ def teardown_request(exception):
pass pass
@app.route('/') @app.route('/')
@requires_auth
def index(): def index():
return redirect(url_for('get_pit_stops')) return redirect(url_for('get_pit_stops'))
@app.route('/services') @app.route('/services')
@requires_auth
def get_services(): def get_services():
data = g.db2.getAllServices() data = g.db2.getAllServices()
data.reverse() data.reverse()
@ -39,6 +69,7 @@ def get_services():
return render_template('services.html', data=g.data) return render_template('services.html', data=g.data)
@app.route('/pitstops', methods=['POST']) @app.route('/pitstops', methods=['POST'])
@requires_auth
def create_pit_stop(): def create_pit_stop():
last_pitstop = g.db2.getLastPitStop() last_pitstop = g.db2.getLastPitStop()
errorMsg = {} errorMsg = {}
@ -84,6 +115,7 @@ def create_pit_stop():
return redirect(url_for('get_pit_stops')) return redirect(url_for('get_pit_stops'))
@app.route('/pitstops/createForm', methods=['GET']) @app.route('/pitstops/createForm', methods=['GET'])
@requires_auth
def create_pit_stop_form(): def create_pit_stop_form():
values = g.db2.getLastPitStop() values = g.db2.getLastPitStop()
values['date'] = time.strftime("%Y-%m-%d") values['date'] = time.strftime("%Y-%m-%d")
@ -96,16 +128,19 @@ def add_service_warning(data):
data['service_info'] = service_info data['service_info'] = service_info
@app.route('/pitstops', methods=['GET']) @app.route('/pitstops', methods=['GET'])
@requires_auth
def get_pit_stops(): def get_pit_stops():
data = prepare_pit_stops(g.db2.getAllPitStops()) data = prepare_pit_stops(g.db2.getAllPitStops())
g.data['pitstops'] = data g.data['pitstops'] = data
return render_template('pitstops.html', data=g.data) return render_template('pitstops.html', data=g.data)
@app.route('/manual', methods=['GET']) @app.route('/manual', methods=['GET'])
@requires_auth
def get_manual(): def get_manual():
return render_template('manual.html', data=g.data) return render_template('manual.html', data=g.data)
@app.route('/statistics', methods=['GET']) @app.route('/statistics', methods=['GET'])
@requires_auth
def get_statistics(): def get_statistics():
pitstops = g.db2.getAllPitStops() pitstops = g.db2.getAllPitStops()
count = len(pitstops) count = len(pitstops)

View File

@ -5,6 +5,7 @@ create table pitstops (
`odometer` INTEGER NOT NULL, `odometer` INTEGER NOT NULL,
`litres` REAL NOT NULL `litres` REAL NOT NULL
); );
drop table if exists services; drop table if exists services;
CREATE TABLE `services` ( CREATE TABLE `services` (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
@ -13,3 +14,12 @@ CREATE TABLE `services` (
`odometer_done` INTEGER, `odometer_done` INTEGER,
`tasks` TEXT NOT NULL `tasks` TEXT NOT NULL
); );
drop table if exists users;
create table `users` (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL,
`salt` TEXT NOT NULL,
`password` TEXT NOT NULL
);
insert into users (name, salt, password) values ('shing19m', 'pL85Kl2U', '207357fdbf6f379c53bb5ab7fa0bc8c0072ae743973a510f551db7b5c90049b7');

View File

@ -0,0 +1,5 @@
{% extends "layout.html" %}
{% block body %}
Please authorize yourself!
{% endblock %}