Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #API to work with user login and password data base
- import hashlib
- import sqlite3
- DB_PATH = 'C:\\Users\\user\\Desktop\\users.sqlite'
- TABLE_NAME = 'users'
- ID = 'id'
- LOGIN = 'login'
- PASSWORD = 'password'
- ERR_PASSWORD_TOO_SHORT = 'Password is too short!'
- ERR_LOGIN_EXISTS = 'Login already exists!'
- MIN_PASS = 6
- MAX_PASS = 20
- TABLE_DICT = \
- {
- ID: 0,
- LOGIN: 1,
- PASSWORD: 2
- }
- CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS '\
- +TABLE_NAME+'(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, '\
- +LOGIN+' varchar, '\
- +PASSWORD+' INTEGER)'
- ADD_USER = "INSERT INTO "+TABLE_NAME+" ("+LOGIN+","+PASSWORD+") VALUES ('%s','%s')"
- def _checkIfTableExists_(c):
- c.execute(CREATE_TABLE)
- def _checkPassLength_(password):
- length = len(password)
- return length >= MIN_PASS or length <= MAX_PASS
- def _checkLoginUniqueness_(c, login):
- # TODO: simplify the query
- c.execute("SELECT * FROM " + TABLE_NAME)
- row = c.fetchone()
- while row is not None:
- if (login == row[TABLE_DICT[LOGIN]]):
- return False
- row = c.fetchone()
- return True
- def str2hashstr(string):
- tNumber = string
- hashObj = hashlib.sha256()
- byteArray = str.encode(string)
- hashObj.update(byteArray)
- return hashObj.hexdigest()
- def createAccount(login, password):
- if not _checkPassLength_(password):
- print(ERR_PASSWORD_TOO_SHORT)
- return
- conn = sqlite3.connect(DB_PATH)
- c = conn.cursor()
- _checkIfTableExists_(c)
- if not _checkLoginUniqueness_(c, login):
- print(ERR_LOGIN_EXISTS)
- return
- hash = str2hashstr(password)
- c.execute(ADD_USER%(login,hash))
- conn.commit()
- c.close()
- conn.close()
- def authentification(login, password):
- conn = sqlite3.connect(DB_PATH)
- c = conn.cursor()
- _checkIfTableExists_(c)
- # TODO: simplify the query
- c.execute("SELECT * FROM " + TABLE_NAME)
- row = c.fetchone()
- while row is not None:
- if login == row[TABLE_DICT[LOGIN]]:
- conn.commit()
- c.close()
- conn.close()
- return (str2hashstr(password) == row[TABLE_DICT[PASSWORD]])
- row = c.fetchone()
- #print('Login not found!')
- conn.commit()
- c.close()
- conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement