~sirn/fanboi2

ref: a68873a108d20a6a49a1b6caf374bfb2cf6a94fe fanboi2/fanboi2/services/identity.py -rw-r--r-- 1.1 KiB
a68873a1Kridsada Thanabulpong Coding style cleanups and setup pre-commit hooks (#42) 3 years ago
                                                                                
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
import string
import random


STRINGS = string.ascii_letters + string.digits + "+/."


class IdentityService(object):
    """Identity service provides a service for querying an identity
    for a user given by a payload from the database or generate a new
    one if not already exists.
    """

    def __init__(self, redis_conn, ident_size):
        self.redis_conn = redis_conn
        self.ident_size = ident_size

    def _get_key(self, **kwargs):
        return "services.identity:%s" % (
            (",".join("%s=%s" % (k, v) for k, v in sorted(kwargs.items()))),
        )

    def identity_for(self, **kwargs):
        """Query the identity for user matching :param:`kwargs` payload
        or generate a new one if not exists.

        :param payload: Payload to identify this rate limit.
        """
        key = self._get_key(**kwargs)
        ident = self.redis_conn.get(key)

        if ident is not None:
            return ident.decode("utf-8")

        ident = "".join(random.choice(STRINGS) for x in range(self.ident_size))
        self.redis_conn.setnx(key, ident)
        self.redis_conn.expire(key, 86400)
        return ident