88 lines
2.1 KiB
Python
88 lines
2.1 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
A simple class to manage a simple user list.
|
|
"""
|
|
|
|
|
|
import os
|
|
import json
|
|
|
|
from colorama import Fore
|
|
from .fileCommands import DATA_PATH
|
|
from passlib.hash import pbkdf2_sha512
|
|
from .CommandException import CommandException
|
|
|
|
|
|
__author__ = "HorlogeSkynet"
|
|
__copyright__ = "Copyright 2017, ACMS"
|
|
__license__ = "GPLv3"
|
|
__status__ = "Production"
|
|
__date__ = "02/28/2017"
|
|
|
|
|
|
class UserList():
|
|
|
|
def __init__(self):
|
|
self.__FILE = DATA_PATH + 'shadow.json'
|
|
self.__data = {}
|
|
|
|
self.loadFromFile()
|
|
|
|
def loadFromFile(self):
|
|
if os.path.exists(self.__FILE):
|
|
with open(self.__FILE, 'r') as file:
|
|
try:
|
|
self.__data = json.load(file)
|
|
|
|
except json.JSONDecodeError as e:
|
|
print(Fore.RED + "\nThe backup file (\"" + self.__FILE + "\") looks corrupted (" + e.msg + ' [' + str(e.lineno) + '; ' + str(e.colno) + ']' + "). Contact an administrator." + Fore.RESET)
|
|
|
|
def saveToFile(self):
|
|
with open(self.__FILE, 'w+') as file:
|
|
try:
|
|
json.dump(self.__data, file, ensure_ascii=False, indent='\t')
|
|
|
|
except (TypeError, json.JSONEncodeError):
|
|
print(Fore.RED + "\nAn invalid object is present in the user list dictionary, we\'d advise you to fix the backup in the \"" + self.__FILE + "\" file, and re-import it." + Fore.RESET)
|
|
|
|
def addUser(self, user, password):
|
|
if list(self.__data.keys()).count(user) == 0:
|
|
self.__data[user] = pbkdf2_sha512.hash(password)
|
|
self.saveToFile()
|
|
|
|
else:
|
|
raise CommandException("This user already exist !")
|
|
|
|
def removeUser(self, user):
|
|
try:
|
|
del self.__data[user]
|
|
self.saveToFile()
|
|
|
|
except:
|
|
raise CommandException("This user does not exist !")
|
|
|
|
def updateUserPassword(self, user, newPassword):
|
|
try:
|
|
self.__data[user] = pbkdf2_sha512.hash(newPassword)
|
|
self.saveToFile()
|
|
|
|
except:
|
|
raise CommandException("This user does not exist !")
|
|
|
|
def checkUserPassword(self, user, password):
|
|
try:
|
|
if pbkdf2_sha512.verify(password, self.__data[user]):
|
|
return True
|
|
|
|
else:
|
|
return False
|
|
|
|
except:
|
|
# We do not throw any error here in order not to inform about the existence of this user
|
|
return False
|
|
|
|
def getUsersList(self):
|
|
return list(self.__data.keys())
|