~launchpad-pqm/launchpad/devel

8687.15.18 by Karl Fogel
Add the copyright header block to files under lib/canonical/.
1
# Copyright 2009 Canonical Ltd.  This software is licensed under the
2
# GNU Affero General Public License version 3 (see the file LICENSE).
7516.2.4 by Julian Edwards
Refactor the generation of tokens in the oauth stuff.
3
4
"""Utility methods for random token generation."""
5
6
__metaclass__ = type
7
8
__all__ = [
9
    'create_token',
10
    'create_unique_token_for_table',
11
    ]
12
13
import random
14
7516.2.5 by Julian Edwards
More review comments from salgado
15
from zope.component import getUtility
16
14560.2.29 by Curtis Hovey
Restored lpstorm module name because it lp engineers know that name.
17
from lp.services.database.lpstorm import IMasterStore
7516.2.5 by Julian Edwards
More review comments from salgado
18
19
7516.2.4 by Julian Edwards
Refactor the generation of tokens in the oauth stuff.
20
def create_token(token_length):
21
    """Create a random token string.
22
23
    :param token_length: Specifies how long you want the token.
24
    """
7571.2.2 by Guilherme Salgado
Couple changes suggested by Celso
25
    # Since tokens are, in general, user-visible, vowels are not included
26
    # below to prevent them from having curse/offensive words.
7516.2.4 by Julian Edwards
Refactor the generation of tokens in the oauth stuff.
27
    characters = '0123456789bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ'
28
    token = ''.join(
29
        random.choice(characters) for count in range(token_length))
7571.2.1 by Guilherme Salgado
Tests for create_unique_token_for_table() plus some refactorings
30
    return unicode(token)
31
32
33
def create_unique_token_for_table(token_length, column):
7516.2.4 by Julian Edwards
Refactor the generation of tokens in the oauth stuff.
34
    """Create a new unique token in a table.
35
36
    Generates a token and makes sure it does not already exist in
37
    the table and column specified.
38
39
    :param token_length: The length for the token string
7571.2.2 by Guilherme Salgado
Couple changes suggested by Celso
40
    :param column: Database column where the token will be stored.
7516.2.4 by Julian Edwards
Refactor the generation of tokens in the oauth stuff.
41
42
    :return: A new token string
43
    """
7675.88.1 by Stuart Bishop
Work in progress from Montreal
44
    # Use the master Store to ensure no race conditions. 
45
    store = IMasterStore(column.cls)
7516.2.4 by Julian Edwards
Refactor the generation of tokens in the oauth stuff.
46
    token = create_token(token_length)
7571.2.1 by Guilherme Salgado
Tests for create_unique_token_for_table() plus some refactorings
47
    while store.find(column.cls, column==token).one() is not None:
7516.2.4 by Julian Edwards
Refactor the generation of tokens in the oauth stuff.
48
        token = create_token(token_length)
49
    return token