Socialify

Folder ..

Viewing tokens.py
45 lines (35 loc) • 1.5 KB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import os

from Crypto.Cipher import AES
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from dotenv import load_dotenv
from six import text_type

load_dotenv()

class AccountActivationTokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            text_type(user.pk) + text_type(timestamp) +
            text_type(user.is_active)
        )

class EmailChangeTokenGenerator():
    def encrypt(self, email):
        auth_string = os.getenv('AUTHORIZATION_STRING')
        key = auth_string.encode('utf-8')[0:16]
        cipher = AES.new(key, AES.MODE_CFB, key)
        return cipher.encrypt(email.encode('utf-8')).hex()

    
    def decrypt(self, token):
        auth_string = os.getenv('AUTHORIZATION_STRING')
        key = auth_string.encode('utf-8')[0:16]
        cipher = AES.new(key, AES.MODE_CFB, key)
        return cipher.decrypt(bytes.fromhex(token)).decode('utf-8')


class CaptchaTokenGenerator():
    def encrypt(self, captcha_string):
        auth_string = os.getenv('AUTHORIZATION_STRING')
        key = auth_string.encode('utf-8')[0:16]
        cipher = AES.new(key, AES.MODE_CFB, key)
        return cipher.encrypt(captcha_string.encode('utf-8')).hex()

    def decrypt(self, token):
        auth_string = os.getenv('AUTHORIZATION_STRING')
        key = auth_string.encode('utf-8')[0:16]
        cipher = AES.new(key, AES.MODE_CFB, key)
        return cipher.decrypt(bytes.fromhex(token)).decode('utf-8')

account_activation_token = AccountActivationTokenGenerator()