Commit 4bba2691 authored by Vladislav Rykov's avatar Vladislav Rykov
Browse files

DAO introduction

parent 1f43be0a
import psycopg2
import bcrypt
class UserDao:
def __init__(self):
pass
# decorator implementation
def with_psql(f):
def _with_psql(*args, **kwargs):
conn = psycopg2.connect('dbname=gateway')
cur = conn.cursor()
try:
res = f(cur, *args, **kwargs)
except (Exception, psycopg2.DatabaseError) as error:
conn.rollback()
res = (False, error)
else:
conn.commit()
finally:
cur.close()
conn.close()
return res
return _with_psql
@staticmethod
@with_psql
def create(cur, name, password):
query = """
INSERT INTO
users
VALUES
(%s, %s)
"""
cur.execute(query, (name, bcrypt.hashpw(password, bcrypt.gensalt())))
return (True,)
@staticmethod
@with_psql
def delete(cur, name):
query = """
DELETE FROM
users
WHERE
name = %s
"""
cur.execute(query, (name,))
return (True,)
@staticmethod
@with_psql
def update_name(cur, old_name, new_name):
query = """
UPDATE users SET
name = %s
WHERE
name = %s
"""
cur.execute(query, (new_name,))
return (True,)
@staticmethod
@with_psql
def update_password(cur, name, password):
query = """
UPDATE users SET
password = %s
WHERE
name = %s
"""
cur.execute(query, (password, name))
return (True,)
@staticmethod
@with_psql
def get(cur, name, password):
query = """
SELECT * FROM
users
WHERE
name = %s
"""
cur.execute(query, (name,))
user = cur.fetchall()[0]
if user[1].encode('utf-8') == bcrypt.hashpw(password, user[1].encode('utf-8')):
return (True, user)
else:
return (False, 'Password or username do not match')
...@@ -2,6 +2,7 @@ from flask import Flask, render_template, request, redirect, url_for, session ...@@ -2,6 +2,7 @@ from flask import Flask, render_template, request, redirect, url_for, session
import psycopg2 import psycopg2
import bcrypt import bcrypt
import misc import misc
import dao.user.user as ud
APP_KEY_LEN = 8 APP_KEY_LEN = 8
...@@ -10,64 +11,6 @@ APP_KEY_LEN = 8 ...@@ -10,64 +11,6 @@ APP_KEY_LEN = 8
server = Flask(__name__, template_folder='templates/') server = Flask(__name__, template_folder='templates/')
def new_user(name, password):
suc = (True, 'User added')
try:
conn = psycopg2.connect('dbname=gateway')
cur = conn.cursor()
query = """
INSERT INTO
users
VALUES
(%s, %s)
"""
cur.execute(query, (name, bcrypt.hashpw(password, bcrypt.gensalt())))
conn.commit()
print('User added')
except (Exception, psycopg2.DatabaseError) as error:
print('Error adding a user: ', error)
suc = (False, error)
finally:
if (conn):
cur.close()
conn.close()
return suc
def chk_user(name, password):
suc = (True, 'Success')
try:
conn = psycopg2.connect('dbname=gateway')
cur = conn.cursor()
query = """
SELECT * FROM
users
WHERE
name = %s
"""
cur.execute(query, (name,))
user = cur.fetchall()[0]
if user[1].encode('utf-8') == bcrypt.hashpw(password, user[1].encode('utf-8')):
session['name'] = user[0]
print('User logged in')
else:
suc = (False, 'Password or username do not match')
except (Exception, psycopg2.DatabaseError) as error:
print('Error querying a user: ', error)
suc = (False, error)
finally:
if (conn):
cur.close()
conn.close()
return suc
def get_apps(username): def get_apps(username):
res = [] res = []
try: try:
...@@ -149,7 +92,7 @@ def new_app_devs(appkey): ...@@ -149,7 +92,7 @@ def new_app_devs(appkey):
conn = psycopg2.connect('dbname=gateway') conn = psycopg2.connect('dbname=gateway')
cur = conn.cursor() cur = conn.cursor()
query = """ query = """
CREATE TABLE dev_%s ( CREATE TABLE devs_%s (
name VARCHAR(30) NOT NULL, name VARCHAR(30) NOT NULL,
dev_id NUMERIC(3) PRIMARY KEY, dev_id NUMERIC(3) PRIMARY KEY,
app_key VARCHAR(80), app_key VARCHAR(80),
...@@ -159,9 +102,9 @@ def new_app_devs(appkey): ...@@ -159,9 +102,9 @@ def new_app_devs(appkey):
""" """
cur.execute(query, (appkey,)) cur.execute(query, (appkey,))
conn.commit() conn.commit()
print('Dev table created') print('Devs table created')
except (Exception, psycopg2.DatabaseError) as error: except (Exception, psycopg2.DatabaseError) as error:
print('Error creating app: ', error) print('Error creating devs table: ', error)
suc = (False, error) suc = (False, error)
finally: finally:
if (conn): if (conn):
...@@ -200,9 +143,9 @@ def get_devs(appkey): ...@@ -200,9 +143,9 @@ def get_devs(appkey):
@server.route('/') @server.route('/')
def index(): def index():
if len(session['name']) > 0: if 'name' in session and len(session['name']) > 0:
apps = get_apps(session['name'].encode('utf-8')) apps = get_apps(session['name'].encode('utf-8'))
print(apps) print('apps: ', apps)
return render_template('index.html', apps=apps) return render_template('index.html', apps=apps)
return render_template('index.html') return render_template('index.html')
...@@ -221,9 +164,10 @@ def signup(): ...@@ -221,9 +164,10 @@ def signup():
feedback = 'Username or password fields cannot be empty' feedback = 'Username or password fields cannot be empty'
return render_template('signup.html', feedback=feedback) return render_template('signup.html', feedback=feedback)
else: else:
res, msg = new_user(username, password) uh = ud.UserDao()
if (not res): res = uh.create(username, password)
return render_template('signup.html', feedback=msg) if (not res[0]):
return render_template('signup.html', feedback=res[1])
else: else:
session['name'] = username session['name'] = username
...@@ -243,9 +187,10 @@ def login(): ...@@ -243,9 +187,10 @@ def login():
feedback = 'Username or password fields cannot be empty' feedback = 'Username or password fields cannot be empty'
return render_template('login.html', feedback=feedback) return render_template('login.html', feedback=feedback)
else: else:
res, msg = chk_user(username, password) uh = ud.UserDao()
if (not res): res = uh.get(username, password)
return render_template('login.html', feedback=msg) if (not res[0]):
return render_template('login.html', feedback=msg[1])
else: else:
session['name'] = username session['name'] = username
...@@ -279,9 +224,16 @@ def app(): ...@@ -279,9 +224,16 @@ def app():
return render_template('new-app.html', feedback=error) return render_template('new-app.html', feedback=error)
else: else:
res = new_app(request.form['appname'], request.form['appdesc']) res = new_app(request.form['appname'], request.form['appdesc'])
rer = new_app_devs(request.form['appname']) if not res[0]:
return render_template('new-app.html', feedback=res[1])
res = new_app_devs(request.form['appname'])
if not res[0]:
rm_app(request.form['appname'])
return render_template('new-app.html', feedback=res[1])
if not res[0] or not rer[0]: if not res[0] or not rer[0]:
return render_template('new-app.html', feedback=res[1]+'|'+rer[1]) return render_template('new-app.html', feedback=str(res[1])+'|'+str(rer[1]))
else: else:
return redirect(url_for('index')) return redirect(url_for('index'))
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment