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
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
1"""tcprocd user."""
2from __future__ import unicode_literals, print_function, absolute_import
3import hashlib
4import logging
7logger = logging.getLogger(__name__)
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()
17class User(object):
18 """
19 An object to store credentials and permissions.
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 """
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
34 def __str__(self):
35 """Format the object as string."""
36 return self.username
38 def __repr__(self):
39 """Return string representation of the object."""
40 return '<{} {}>'.format(self.__class__.__name__, str(self))
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
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)
52 def __hash__(self):
53 """Build and return a unique hash for this object."""
54 return hash((self.__class__.__name__, self.username))
56 def as_dict(self):
57 """Return a compact :class:`dict` to re-create the user object."""
58 d = {"username": self.username}
60 if self.password is not None:
61 d['password'] = self.password
63 if self.admin:
64 d['admin'] = True
66 return d
68 def set_password(self, raw_password):
69 """
70 Hash the given password and store it.
72 :param raw_password: :class:`str` - The password to hash and store
73 """
74 password = make_password(raw_password)
75 self.password = password
77 def check_password(self, raw_password):
78 """
79 Hash the given password and compare it to the users password.
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