14 |
14 |
# You should have received a copy of the GNU Affero General Public License
|
15 |
15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
16 |
16 |
|
|
17 |
import base64
|
|
18 |
from Crypto.Cipher import AES
|
17 |
19 |
|
18 |
20 |
from django.db import models
|
19 |
|
from jsonfield import JSONField
|
|
21 |
from django.conf import settings
|
20 |
22 |
from django.utils.translation import ugettext_lazy as _
|
21 |
23 |
|
|
24 |
from jsonfield import JSONField
|
|
25 |
|
|
26 |
from mandayejs.mandaye.utils import get_password_field
|
|
27 |
|
22 |
28 |
|
23 |
29 |
class UserCredentials(models.Model):
|
24 |
30 |
user = models.ForeignKey('auth.User')
|
... | ... | |
33 |
39 |
or self.user.email \
|
34 |
40 |
or self.user.username
|
35 |
41 |
|
36 |
|
def to_login_info(self):
|
|
42 |
def save(self, *args, **kwargs):
|
|
43 |
self.encrypt()
|
|
44 |
super(UserCredentials, self).save(*args, **kwargs)
|
|
45 |
|
|
46 |
def _get_secret_key(self):
|
|
47 |
"""Return secret key under 32 characters
|
|
48 |
"""
|
|
49 |
return settings.SECRET_KEY[0:-(len(settings.SECRET_KEY)-32)]
|
|
50 |
|
|
51 |
def _get_cipher(self):
|
|
52 |
"""Return cipher object
|
|
53 |
"""
|
|
54 |
return AES.new(self._get_secret_key(), AES.MODE_CFB, "0000000000000000")
|
|
55 |
|
|
56 |
def encrypt(self,):
|
|
57 |
"""Encrypt password
|
|
58 |
"""
|
|
59 |
password_field_name = get_password_field()
|
|
60 |
cipher = self._get_cipher()
|
|
61 |
self.locators[password_field_name] = \
|
|
62 |
base64.b64encode(cipher.encrypt(
|
|
63 |
self.locators.get(password_field_name,'')
|
|
64 |
))
|
|
65 |
|
|
66 |
return self.locators
|
|
67 |
|
|
68 |
def decrypt(self,):
|
|
69 |
"""Decrypt password
|
|
70 |
"""
|
|
71 |
password_field_name = get_password_field()
|
|
72 |
cipher = self._get_cipher()
|
|
73 |
self.locators[password_field_name] = \
|
|
74 |
cipher.decrypt(
|
|
75 |
base64.b64decode(
|
|
76 |
self.locators.get(password_field_name,'')
|
|
77 |
))
|
|
78 |
|
|
79 |
return self.locators
|
|
80 |
|
|
81 |
def to_login_info(self, decrypt=False):
|
|
82 |
if decrypt:
|
|
83 |
self.decrypt()
|
37 |
84 |
return {'#'+k : v for k,v in self.locators.items() }
|
38 |
85 |
|