Login

User activation codes without additional database tables or fields

Author:
badzong
Posted:
October 23, 2012
Language:
Python
Version:
1.4
Tags:
user account activation
Score:
0 (after 0 ratings)

UserAuthCode generates an authentication code for Django user objects. This code can be used to verify the user's email address and to activate his account. Unlike other solutions there's no need add any tables or fields to your database.

Current version is hosted on GitHub. There's also an example how to use it in your Django project.

 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
class UserAuthCode(object):
    def __init__(self, secret, salt_len=8, hash=hashlib.sha256):
        self.secret = secret
        self.salt_len = salt_len
        self.hash = hash

    def salt(self):
        s = ''
        for i in range(self.salt_len):
            s += random.choice(string.letters + string.digits)

        return s

    def digest(self, user, salt):
        # Use username, email and date_joined to generate digest
        auth_message = ''.join((self.secret, user.username, user.email,
            str(user.date_joined), salt))
        md = self.hash()
        md.update(auth_message)

        return base64.urlsafe_b64encode(md.digest()).rstrip('=')

    def auth_code(self, user):
        salt = self.salt()
        digest = self.digest(user, salt)

        return salt + digest

    def is_valid(self, user, auth_code):
        salt = auth_code[:self.salt_len]
        digest = auth_code[self.salt_len:]
 
        # CAVEAT: Make sure UserAuthCode cannot be used to reactivate locked
        # profiles.
        if user.last_login != user.date_joined:
            return False

        return digest == self.digest(user, salt)

More like this

  1. Google Account authentication by Hangya 4 years, 11 months ago
  2. Using manager methods by ubernostrum 8 years, 5 months ago
  3. Active Directory Authentication Backend (with User object updating) by mroose 3 years, 8 months ago
  4. Reset / Send account details email by Ciantic 4 years, 12 months ago
  5. StrictAuthentication - Auto log-out inactive users by yeago 6 years, 10 months ago

Comments

Please login first before commenting.