Coverage for tcprocd/user.py: 100.00%

Shortcuts on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

40 statements  

1"""tcprocd user.""" 

2from __future__ import unicode_literals, print_function, absolute_import 

3import hashlib 

4import logging 

5 

6 

7logger = logging.getLogger(__name__) 

8 

9 

10def make_password(password): 

11 """Hash the given password and return it.""" 

12 h = hashlib.new('sha512') 

13 h.update(password.encode()) 

14 return h.hexdigest() 

15 

16 

17class User(object): 

18 """ 

19 An object to store credentials and permissions. 

20 

21 :param username: :class:`str` - Username of this user. 

22 :param password: :class:`str` - Password hash of this user. 

23 :param admin: :class:`bool` - Whether this user is an admin. (Default: ``False``) 

24 """ 

25 

26 def __init__(self, username, password=None, admin=False, user=None, group=None): 

27 """Initialize user.""" 

28 self.username = username 

29 self.password = password 

30 self.admin = admin 

31 self.user = user 

32 self.group = group 

33 

34 def __str__(self): 

35 """Format the object as string.""" 

36 return self.username 

37 

38 def __repr__(self): 

39 """Return string representation of the object.""" 

40 return '<{} {}>'.format(self.__class__.__name__, str(self)) 

41 

42 def __eq__(self, other): 

43 """Compare the given object to this one and return ``True`` if they are equal.""" 

44 if not isinstance(other, self.__class__): 

45 return False 

46 return other.username == self.username 

47 

48 def __ne__(self, other): 

49 """Compare the given object to this one and return ``True`` if they are *NOT* equal.""" 

50 return not self.__eq__(other) 

51 

52 def __hash__(self): 

53 """Build and return a unique hash for this object.""" 

54 return hash((self.__class__.__name__, self.username)) 

55 

56 def as_dict(self): 

57 """Return a compact :class:`dict` to re-create the user object.""" 

58 d = {"username": self.username} 

59 

60 if self.password is not None: 

61 d['password'] = self.password 

62 

63 if self.admin: 

64 d['admin'] = True 

65 

66 return d 

67 

68 def set_password(self, raw_password): 

69 """ 

70 Hash the given password and store it. 

71 

72 :param raw_password: :class:`str` - The password to hash and store 

73 """ 

74 password = make_password(raw_password) 

75 self.password = password 

76 

77 def check_password(self, raw_password): 

78 """ 

79 Hash the given password and compare it to the users password. 

80 

81 :param raw_password: :class:`str` - The password to compare. 

82 :return: :class:`bool` - Whether the password matches. 

83 """ 

84 if self.password is None: 

85 return False 

86 password = make_password(raw_password) 

87 return password == self.password