Advertisement
Guest User

Untitled

a guest
Feb 5th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #API to work with user login and password data base
  2. import hashlib
  3. import sqlite3
  4.  
  5. DB_PATH = 'C:\\Users\\user\\Desktop\\users.sqlite'
  6. TABLE_NAME = 'users'
  7. ID = 'id'
  8. LOGIN = 'login'
  9. PASSWORD = 'password'
  10. PASSWORD_TOO_SHORT = 'Password is too short!'
  11. MIN_PASS = 6
  12. MAX_PASS = 20
  13. TABLE_DICT = \
  14. {
  15. ID: 0,
  16. LOGIN: 1,
  17. PASSWORD: 2
  18. }
  19. CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS '\
  20. +TABLE_NAME+'(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, '\
  21. +LOGIN+' varchar, '\
  22. +PASSWORD+' INTEGER)'
  23. ADD_USER = "INSERT INTO "+TABLE_NAME+" ("+LOGIN+","+PASSWORD+") VALUES ('%s','%s')"
  24.  
  25. def _createTable_(c):
  26. c.execute(CREATE_TABLE)
  27.  
  28. def _checkPassLength_(password):
  29. length = len(password)
  30. return length < MIN_PASS or length > MAX_PASS
  31.  
  32. def _checkLoginUniqueness_(c, login):
  33. c.execute("SELECT * FROM " + TABLE_NAME)
  34. row = c.fetchone()
  35. while row is not None:
  36. if (login == row[TABLE_DICT[LOGIN]]):
  37. return False
  38. row = c.fetchone()
  39. return True
  40.  
  41. def str2hashstr(string):
  42. tNumber = string
  43. hashObj = hashlib.sha256()
  44. byteArray = str.encode(string)
  45. hashObj.update(byteArray)
  46. return hashObj.hexdigest()
  47.  
  48. def createAccount(login, password):
  49. if not _checkPassLength_(password):
  50. print(PASSWORD_TOO_SHORT)
  51. return
  52. conn = sqlite3.connect(DB_PATH)
  53. c = conn.cursor()
  54. if not _checkLoginUniqueness_(c, login):
  55. print('Login already exists!')
  56. return
  57. hash = str2hashstr(password)
  58.  
  59. c.execute(ADD_USER%(login,hash))
  60. conn.commit()
  61. c.close()
  62. conn.close()
  63.  
  64. def authentification(login, password):
  65. conn = sqlite3.connect(DB_PATH)
  66. c = conn.cursor()
  67. c.execute("SELECT * FROM " + TABLE_NAME)
  68. row = c.fetchone()
  69. while row is not None:
  70. if login == row[TABLE_DICT[LOGIN]]:
  71. conn.commit()
  72. c.close()
  73. conn.close()
  74. return (str2hashstr(password) == row[TABLE_DICT[PASSWORD]])
  75. row = c.fetchone()
  76. #print('Login not found!')
  77. conn.commit()
  78. c.close()
  79. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement