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 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):
cursor = self.db.execute(query)
names = list(map(lambda x: x[0], cursor.description))

View File

@ -1,11 +1,15 @@
from datetime import datetime
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 url_for
from flask import Response
import hashlib
import os.path
import time
from functools import wraps
import db
#from db import Db
@ -13,10 +17,34 @@ app = Flask(__name__)
DATABASE = '/data/rollerverbrauch.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
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
def before_request():
g.db2 = db.Db(app.config['DATABASE'])
@ -28,10 +56,12 @@ def teardown_request(exception):
pass
@app.route('/')
@requires_auth
def index():
return redirect(url_for('get_pit_stops'))
@app.route('/services')
@requires_auth
def get_services():
data = g.db2.getAllServices()
data.reverse()
@ -39,6 +69,7 @@ def get_services():
return render_template('services.html', data=g.data)
@app.route('/pitstops', methods=['POST'])
@requires_auth
def create_pit_stop():
last_pitstop = g.db2.getLastPitStop()
errorMsg = {}
@ -84,6 +115,7 @@ def create_pit_stop():
return redirect(url_for('get_pit_stops'))
@app.route('/pitstops/createForm', methods=['GET'])
@requires_auth
def create_pit_stop_form():
values = g.db2.getLastPitStop()
values['date'] = time.strftime("%Y-%m-%d")
@ -96,16 +128,19 @@ def add_service_warning(data):
data['service_info'] = service_info
@app.route('/pitstops', methods=['GET'])
@requires_auth
def get_pit_stops():
data = prepare_pit_stops(g.db2.getAllPitStops())
g.data['pitstops'] = data
return render_template('pitstops.html', data=g.data)
@app.route('/manual', methods=['GET'])
@requires_auth
def get_manual():
return render_template('manual.html', data=g.data)
@app.route('/statistics', methods=['GET'])
@requires_auth
def get_statistics():
pitstops = g.db2.getAllPitStops()
count = len(pitstops)

View File

@ -5,6 +5,7 @@ create table pitstops (
`odometer` INTEGER NOT NULL,
`litres` REAL NOT NULL
);
drop table if exists services;
CREATE TABLE `services` (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
@ -13,3 +14,12 @@ CREATE TABLE `services` (
`odometer_done` INTEGER,
`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 %}