Advertisement
Guest User

User Data Base

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