db_manage.py
72 lines
| 2.1 KiB
| text/x-python
|
PythonLexer
Marcin Kuzminski
|
r59 | import logging | ||
import sqlite3 | ||||
Marcin Kuzminski
|
r66 | |||
Marcin Kuzminski
|
r59 | import os | ||
import crypt | ||||
from os.path import dirname as dn | ||||
ROOT = dn(dn(dn(os.path.realpath(__file__)))) | ||||
Marcin Kuzminski
|
r66 | logging.basicConfig(level=logging.DEBUG) | ||
Marcin Kuzminski
|
r59 | |||
def get_sqlite_conn_cur(): | ||||
Marcin Kuzminski
|
r66 | conn = sqlite3.connect(os.path.join(ROOT, 'hg_app.db')) | ||
Marcin Kuzminski
|
r59 | cur = conn.cursor() | ||
return conn, cur | ||||
r88 | def check_for_db(override): | |||
if not override: | ||||
if os.path.isfile(os.path.join(ROOT, 'hg_app.db')): | ||||
raise Exception('database already exists') | ||||
Marcin Kuzminski
|
r66 | |||
r88 | def create_tables(override=False): | |||
Marcin Kuzminski
|
r59 | """ | ||
Create a auth database | ||||
""" | ||||
r88 | check_for_db(override) | |||
Marcin Kuzminski
|
r59 | conn, cur = get_sqlite_conn_cur() | ||
try: | ||||
Marcin Kuzminski
|
r66 | logging.info('creating table %s', 'users') | ||
Marcin Kuzminski
|
r59 | cur.execute("""DROP TABLE IF EXISTS users """) | ||
cur.execute("""CREATE TABLE users | ||||
(user_id INTEGER PRIMARY KEY AUTOINCREMENT, | ||||
username TEXT, | ||||
password TEXT, | ||||
active INTEGER, | ||||
admin INTEGER)""") | ||||
Marcin Kuzminski
|
r67 | logging.info('creating table %s', 'user_logs') | ||
cur.execute("""DROP TABLE IF EXISTS user_logs """) | ||||
cur.execute("""CREATE TABLE user_logs | ||||
Marcin Kuzminski
|
r59 | (id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
user_id INTEGER, | ||||
Marcin Kuzminski
|
r66 | repository TEXT, | ||
action TEXT, | ||||
action_date DATETIME)""") | ||||
Marcin Kuzminski
|
r59 | conn.commit() | ||
except: | ||||
conn.rollback() | ||||
raise | ||||
cur.close() | ||||
Marcin Kuzminski
|
r66 | |||
def admin_prompt(): | ||||
import getpass | ||||
username = raw_input('give username:') | ||||
password = getpass.getpass('Specify admin password:') | ||||
create_user(username, password, True) | ||||
Marcin Kuzminski
|
r59 | |||
def create_user(username, password, admin=False): | ||||
conn, cur = get_sqlite_conn_cur() | ||||
password_crypt = crypt.crypt(password, '6a') | ||||
Marcin Kuzminski
|
r66 | logging.info('creating user %s', username) | ||
Marcin Kuzminski
|
r59 | try: | ||
cur.execute("""INSERT INTO users values (?,?,?,?,?) """, | ||||
(None, username, password_crypt, 1, admin)) | ||||
conn.commit() | ||||
except: | ||||
conn.rollback() | ||||
raise | ||||
Marcin Kuzminski
|
r66 | |||
if __name__ == '__main__': | ||||
r88 | create_tables(True) | |||
Marcin Kuzminski
|
r66 | admin_prompt() | ||