Commit 2dc466cfc525e3904d33a86c18b77dd03e556345

Authored by Miguel Barão
1 parent 6d8bb39a
Exists in master and in 1 other branch dev

- fixed initdb_from_csv.py to empty passwords (not bcrypt).

- fixed myauth.py to use bcrypt.
Showing 2 changed files with 29 additions and 32 deletions   Show diff stats
initdb_from_csv.py
... ... @@ -15,12 +15,10 @@ def fixname(s):
15 15  
16 16 def genstudent(reader, pw=''):
17 17 for i, r in enumerate(reader):
18   - print('\rInserting students into database... [{}]'.format(i+1), end='')
19 18 num = r['N.º']
20 19 name = fixname(r['Nome'])
21   - pwhash = bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt())
22   - yield (num, name, pwhash)
23   - print('\nDone.')
  20 + yield (r['N.º'], fixname(r['Nome']), '')
  21 + print('{} students inserted.'.format(i+1))
24 22  
25 23 # ---- DATABASE SCHEMA ----
26 24 sql_cmd = '''PRAGMA foreign_keys = ON;
... ... @@ -49,12 +47,11 @@ sql_cmd = '''PRAGMA foreign_keys = ON;
49 47 # --------- Parse command line options -----------
50 48 argparser = argparse.ArgumentParser(description='Create new database from a CSV file (SIIUE format)')
51 49 argparser.add_argument('--db', default='students.db', type=str, help='database filename')
52   -argparser.add_argument('--pw', default='', type=str, help='initial password')
53 50 argparser.add_argument('csvfile', type=str, help='CSV filename')
54 51 args = argparser.parse_args()
55 52  
56 53  
57   -# -------- Parse CSV --------
  54 +# --------- Parse CSV --------
58 55 with open(args.csvfile, encoding='iso-8859-1') as csvfile: # SIIUE format
59 56 reader = csv.DictReader(csvfile, delimiter=';', quotechar='"')
60 57 db_exists = os.path.exists(args.db)
... ... @@ -63,13 +60,12 @@ with open(args.csvfile, encoding='iso-8859-1') as csvfile: # SIIUE format
63 60 if not db_exists:
64 61 print('Creating new database "{}"...'.format(args.db))
65 62 c.executescript(sql_cmd)
66   - pwhash = bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt())
67   - c.execute('INSERT INTO students VALUES (?,?,?)', ('0', 'Professor', pwhash))
  63 + c.execute('INSERT INTO students VALUES (?,?,?)', ('0', 'Professor', ''))
68 64 else:
69 65 print('Database "{}" already exists.'.format(args.db))
70 66  
71   - print('Warning: Passwords are generated using bcrypt wich takes a lot of time...')
  67 + print('Inserting students into database... ', end='')
72 68 try:
73   - c.executemany('INSERT INTO students VALUES (?,?,?)', genstudent(reader, args.pw))
  69 + c.executemany('INSERT INTO students VALUES (?,?,?)', genstudent(reader))
74 70 except sqlite3.IntegrityError:
75 71 print('\rStudents already in the database. Aborting!!!')
... ...
myauth.py
... ... @@ -7,7 +7,7 @@
7 7  
8 8 import cherrypy
9 9 import sqlite3
10   -from hashlib import sha256
  10 +import bcrypt
11 11 from mako.lookup import TemplateLookup
12 12 import urllib
13 13 import html
... ... @@ -27,33 +27,34 @@ def credentials_ok(uid, password, db):
27 27 updated if it's initially empty.
28 28 Returns the name of the student on success, otherwise returns None.
29 29 '''
30   - success = False
31   - tryhash = sha256(password.encode('utf-8')).hexdigest()
  30 + # success = False
  31 + # tryhash = sha256(password.encode('utf-8')).hexdigest()
32 32  
33 33 # search student in database
34   - conn = sqlite3.connect(db)
35   - sql_cmd = 'SELECT * FROM students WHERE number=?'
36   - found = conn.execute(sql_cmd, [uid]).fetchone()
37   - if found is not None:
38   - num, name, pw_hash = found
39   - if pw_hash == '':
  34 + with sqlite3.connect(db) as c:
  35 + sql_cmd = 'SELECT name,password FROM students WHERE number=?'
  36 + try:
  37 + name, pwhash = c.execute(sql_cmd, [uid]).fetchone()
  38 + except:
  39 + cherrypy.log.error('Student %s not found!' % uid, 'APPLICATION')
  40 + return None
  41 +
  42 + # student found in db
  43 + if pwhash == '':
40 44 # update password on first login
41   - pw_hash = tryhash
  45 + hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
42 46 sql_cmd = 'UPDATE students SET password=? WHERE number=?'
43   - conn.execute(sql_cmd, (pw_hash, num))
44   - conn.commit()
  47 + c.execute(sql_cmd, (hashed, uid))
45 48 cherrypy.log.error('Student %s updated his password.' % uid, 'APPLICATION')
46   -
47   - # check password
48   - success = (tryhash == pw_hash)
49   - if success:
50   - cherrypy.log.error('Student %s logged in.' % uid, 'APPLICATION')
  49 + return name
51 50 else:
52   - cherrypy.log.error('Student %s wrong password.' % uid, 'APPLICATION')
53   - else:
54   - cherrypy.log.error('Student %s not found!' % uid, 'APPLICATION')
55   - conn.close()
56   - return name if success else None
  51 + # check password
  52 + if bcrypt.hashpw(password.encode('utf-8'), pwhash) == pwhash:
  53 + cherrypy.log.error('Student %s logged in.' % uid, 'APPLICATION')
  54 + return name
  55 + else:
  56 + cherrypy.log.error('Student %s wrong password.' % uid, 'APPLICATION')
  57 + return None
57 58  
58 59  
59 60 def check_auth(*args, **kwargs):
... ...