Created
October 20, 2014 20:19
-
-
Save alejandrobernardis/2b939fc2f6c539454169 to your computer and use it in GitHub Desktop.
Tokenizer :/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python2.7 | |
| # -*- coding: utf-8 -*- | |
| # Copyright (c) 2014 Asumi Kamikaze Inc. | |
| # Licensed under the MIT License. | |
| # Author: Alejandro M. Bernardis | |
| # Email: alejandro (dot) bernardis (at) asumikamikaze (dot) com | |
| # Created: 20/Oct/2014 12:22 | |
| import base64 | |
| import string | |
| import hashlib | |
| import datetime | |
| from random import choice | |
| DEFAULT_LENGTH = 64 | |
| SECURE_LENGTH = 256 | |
| def x_to_b64(func): | |
| def wraps(*args, **kwargs): | |
| return base64.urlsafe_b64encode(func(*args, **kwargs)) | |
| return wraps | |
| def x_to_sha256(func): | |
| def wraps(*args, **kwargs): | |
| data, length = func(*args, **kwargs) | |
| h = hashlib.sha256() | |
| h.update(data.encode()) | |
| s = h.hexdigest() | |
| if length or 'length' in kwargs: | |
| return s[:int(kwargs.get('length', length))] | |
| return s | |
| return wraps | |
| def string_random_choice(length=DEFAULT_LENGTH): | |
| h = string.ascii_letters + string.digits + string.punctuation \ | |
| + datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S%f') | |
| return ''.join([choice(h) for _ in xrange(length)]) | |
| def secret_key(length=DEFAULT_LENGTH): | |
| return string_random_choice(length) | |
| @x_to_sha256 | |
| def activation_key(data, length=DEFAULT_LENGTH): | |
| return '%s%s' % (data, string_random_choice(SECURE_LENGTH)), length | |
| @x_to_sha256 | |
| def token(length=DEFAULT_LENGTH): | |
| return string_random_choice(SECURE_LENGTH), length | |
| @x_to_sha256 | |
| def user_token(data, length=DEFAULT_LENGTH): | |
| return data, length | |
| @x_to_b64 | |
| def b64secret_key(length=DEFAULT_LENGTH): | |
| return string_random_choice(length) | |
| @x_to_b64 | |
| def b64activation_key(username, email, length=DEFAULT_LENGTH): | |
| return activation_key(username, email, length) | |
| @x_to_b64 | |
| def b64token(length=DEFAULT_LENGTH): | |
| return token(length) | |
| @x_to_b64 | |
| def b64user_token(data, length=DEFAULT_LENGTH): | |
| return user_token(data, length) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment