本文整理汇总了Python中webapp2_extras.security.generate_random_string函数的典型用法代码示例。如果您正苦于以下问题:Python generate_random_string函数的具体用法?Python generate_random_string怎么用?Python generate_random_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了generate_random_string函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: create
def create(cls, user, subject, token=None):
"""Creates a new token for the given user, if any.
:param user:
User unique ID, or None if no user is to be associated with the
created token.
:param subject:
The subject of the key. Currently have:
- 'auth'
- 'verify_email'
- 'password_reset'
- 'access'
:param token:
Optionally an existing token may be provided.
If None, a random token will be generated.
:returns:
The newly created :class:`UserToken`.
"""
if user is not None:
user = str( user )
if token is None:
if subject == 'access':
# We use 16 uppercase alphanumeric characters for access
# keys
pool = map( chr, range( 65, 91 ) )
pool.extend( [ str( x ) for x in range( 0, 10 ) ] )
token = security.generate_random_string( length=16, pool=pool )
else:
token = security.generate_random_string(entropy=128)
key = cls.get_key( user, subject, token )
entity = cls( key=key, user=user, subject=subject, token=token )
entity.put( )
return entity
开发者ID:rggibson,项目名称:Authtopus,代码行数:34,代码来源:models.py
示例2: create
def create(cls, user, subject, token=None):
if subject == cls.SUBJECT_BEARER:
user = str(user)
token = token or security.generate_random_string(entropy=128)
# Bearer tokens must be unique on their own, without a user scope.
key = cls.get_key("", subject, token)
entity = cls(
key=key,
user=user,
subject=subject,
token=token,
refresh_token=security.generate_random_string(entropy=128),
)
# Refresh tokens must be unique
ok = cls.unique_model.create("%s.refresh_token:%s" % (cls.__name__, entity.refresh_token))
if ok:
entity.put()
else:
logging.warning("Unable to create a unique user token for user %s", user)
entity = None
else:
entity = super(UserToken, cls).create(user, subject, token)
return entity
开发者ID:akolchin,项目名称:appengine-endpoints-auth-example,代码行数:26,代码来源:models.py
示例3: email_change_request
def email_change_request( self, email ):
# request an email address to be modified. Create a rollback option.
result = 'cannot_remove'
emailCurrent = self.enki_user.email
userId = self.enki_user.key.id()
if email != '' and enki.libuser.exist_EnkiUser( email ):
# if the new email matches an existing verified user email, reject it
if emailCurrent == email:
result = 'same'
else:
result = ERROR_EMAIL_IN_USE # Note: send an email to emailcurrent regardless to prevent email checking (see below)
else:
if email == '':
# if the user erased the email, and they can log in through auth, store "removed" in the email field, so it isn't overwritten by an auth login with a verified email
if self.enki_user.auth_ids_provider:
self.enki_user.email = 'removed'
self.enki_user.put()
result = 'removed'
else:
return result
else:
# email the new, unverified address with a link to allow the user to verify the email
tokenEntity = EnkiModelTokenVerify.get_by_user_id_email_type( userId, email, 'emailchange' )
if tokenEntity:
# if a verify token for the same new email address and user already exists, use its token
token = tokenEntity.token
else:
# otherwise create a new token
token = security.generate_random_string( entropy = 256 )
emailToken = EnkiModelTokenVerify( token = token, email = email, user_id = userId, type = 'emailchange' )
emailToken.put()
link = enki.libutil.get_local_url( 'emailchangeconfirm', { 'verifytoken': token })
self.send_email( email, MSG.SEND_EMAIL_EMAIL_CHANGE_CONFIRM_SUBJECT(), MSG.SEND_EMAIL_EMAIL_CHANGE_CONFIRM_BODY( link, email ))
result = 'change'
if emailCurrent and emailCurrent != 'removed' and result != 'same':
# email the current, verified address in case they want to undo the change (useful if account has been hacked)
# skip this step if the current email is empty (case if user logged in with auth id without email with e.g. Steam) or "removed".
# If the email is already in use, mask the fact to prevent email checking.
tokenEntity = enki.libuser.get_EmailRollbackToken_by_user_id_email( userId, emailCurrent )
if tokenEntity:
# if the old email is already in the archive, use its token
token = tokenEntity.token
else:
# otherwise create a new token
token = security.generate_random_string( entropy = 256 )
emailOldToken = EnkiModelTokenEmailRollback( token = token, email = emailCurrent, user_id = userId )
emailOldToken.put()
if result == ERROR_EMAIL_IN_USE:
self.add_debugmessage( '''Comment - whether the email is available or not, the feedback through both the UI AND EMAIL is identical to prevent email checking.''' )
link = enki.libutil.get_local_url( 'emailrollback', { 'rollbacktoken': token } )
self.send_email( emailCurrent, MSG.SEND_EMAIL_EMAIL_CHANGE_UNDO_SUBJECT(), MSG.SEND_EMAIL_EMAIL_CHANGE_UNDO_BODY( link, emailCurrent ))
return result
开发者ID:juliettef,项目名称:enkiWS,代码行数:52,代码来源:handlerbase.py
示例4: dispatch
def dispatch(self):
"""Wraps the dispatch method to add session handling."""
self.session_store = sessions.get_store(request=self.request)
self.decorator = decorator
# Add the user's credentials to the decorator if we have them.
if self.me:
self.decorator.credentials = self.decorator._storage_class(
model=self.decorator._credentials_class,
key_name='user:{}'.format(self.me.user_id()),
property_name=self.decorator._credentials_property_name).get()
else:
# Create a session ID for the session if it does not have one already.
# This is used to create an opaque string that can be passed to the OAuth2
# authentication server via the 'state' parameter.
if not self.session.get('sid'):
self.session['sid'] = security.generate_random_string(entropy=128)
# Store the state for the session user in a parameter on the flow.
# We only need to do this if we're not logged in.
self.decorator._create_flow(self)
session_user = SessionUser(self.session['sid'])
logging.info(self.decorator.flow.params)
self.decorator.flow.params['state'] = appengine._build_state_value(
self, session_user)
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response)
开发者ID:grow,项目名称:webreview,代码行数:30,代码来源:handlers.py
示例5: create_user
def create_user(cls, username=None, raw_password=None, email=None):
"""
Create a Login instance, but method NOT PUT Login TO DB
You must run _.put() manually after creating the instance.
:param username:
username string
:param raw_password:
raw_password string
:param email:
emal (optional)
:return:
Login instance or None
"""
logging.info('LoginClass:create_user() => Start creating user')
if not(username and raw_password):
logging.error('LoginClass:create_user() => username or raw_password is empty, return None')
return None
salt = security.generate_random_string(length=30)
logging.info('LoginClass:create_user() => Making salt for password hash ... < %s >' % salt)
pw_hash = security.generate_password_hash(raw_password, pepper=PEPPER)
logging.info('LoginClass:create_user() => Generatin password hash ... < %s >' % pw_hash)
u = Login()
u.populate(username=username,
pw_hash=pw_hash,
email=email)
logging.info('LoginClass:create_user() => Make and return Login instance')
return u
开发者ID:yurasid,项目名称:CS253-final-wiki,代码行数:31,代码来源:user_model.py
示例6: job_quote
def job_quote(url, to_address, from_address, object_id):
"""
Get a quote for job by creating it in test mode. Objects do not have the
original file information contained on them, so we require the url.
I am told that they will not have a way to query the price for a job before
creating it for some time, so this is the most reasonable way.
The next most reasonable way might be to encode their pricing structure in
code and just calculate it locally.
"""
logging.info("original object ID: %s", object_id);
logging.info("passed in url: %s", url);
original_obj = get_object(object_id)
# re-create the object in test mode
name = "mirror:{}:{}".format(object_id, generate_random_string(8))
logging.info("original object: %s", original_obj);
test_obj = create_object(name, url, original_obj["setting"]["id"], test=True) # this might need a file argument? , 'file': ''}
# create a job for the object
test_job = create_job(name, to_address, from_address, test_obj["id"], test=True)
# get the price of the job
return float(test_job["price"])
开发者ID:aaronhesse,项目名称:mailmypdf,代码行数:26,代码来源:lob.py
示例7: __init__
def __init__(self, *args, **kwargs):
super(BaseApp, self).__init__(*args, **kwargs)
# If we're unit testing, use the same one every time for consistent results.
if Config().is_testing:
secret = "notasecret"
else:
# Check that we have a secret key for generating tokens.
try:
secret = keymaster.get("token_secret")
except keymaster.KeymasterError:
logging.warning("Found no token secret, generating one.")
secret = security.generate_random_string(entropy=128)
keymaster.Keymaster.encrypt("token_secret", secret)
# Configure webapp2.
my_config = {
"webapp2_extras.auth": {
"user_model": "membership.Membership",
"user_attributes": ["first_name", "last_name", "email"]
},
"webapp2_extras.sessions": {
"secret_key": secret
}
}
self.config = webapp2.Config(my_config)
开发者ID:hackerdojo,项目名称:hd-signup,代码行数:27,代码来源:project_handler.py
示例8: create
def create(cls, user, subject, token=None, expiration=None, delete_past_tokens=False):
"""Creates a new token for the given user.
:param user:
User unique ID.
:param subject:
The subject of the key. Examples:
- 'auth'
- 'signup'
:param token:
Optionally an existing token may be provided.
If None, a random token will be generated.
:returns:
The newly created :class:`UserToken`.
"""
user = str(user)
token = token or security.generate_random_string(entropy=128)
key = cls.get_key(user, subject, token)
if delete_past_tokens:
ndb.delete_multi(cls.query(cls.user == user, cls.subject == subject).iter(keys_only=True))
entity = cls(key=key, user=user, subject=subject, token=token, expiration=expiration)
entity.put()
return entity
开发者ID:HackIllinois,项目名称:infrastructure-2016,代码行数:27,代码来源:models.py
示例9: get
def get(self):
# Get the parameters that Meraki sends to us.
base_grant_url = self.request.get("base_grant_url")
user_continue_url = self.request.get("user_continue_url")
if (not base_grant_url or not user_continue_url):
token = self.request.cookies.get("grant_token")
if not token:
# We should really only be getting here through the Meraki AP, so if
# we're not, just send us back to the main website.
logging.debug("Redirecting to main website.")
self.redirect("http://www.hackerdojo.com")
return
# Otherwise, we're good to go.
logging.info("Got existing session: %s" % (token))
response = self.render("templates/splash.html", login_url="/grant")
self.response.out.write(response)
return
# Save them to memcache.
token = security.generate_random_string(12)
memcache.set(token, [base_grant_url, user_continue_url])
self.response.set_cookie("grant_token", token)
logging.debug("Saving access token: %s" % (token))
# Hide the parameters.
redirect_url = self._remove_params(["base_grant_url", "user_continue_url"])
self.redirect(redirect_url)
开发者ID:hackerdojo,项目名称:hd-wifi,代码行数:29,代码来源:main.py
示例10: create
def create(cls, user, subject, token=None):
user = str(user)
token = token or security.generate_random_string(entropy=128)
key_name = "%s.%s.%s" %(user,subject,token)
new_entity = cls(key_name=key_name, user=user, subject=subject, token=token)
new_entity.put()
return new_entity
开发者ID:JishnuM,项目名称:Demeetr,代码行数:7,代码来源:demeetr.py
示例11: create
def create(cls, user, subject, token=None):
"""Fetches a user token."""
token = token or security.generate_random_string(entropy=64)
key = cls.get_key(user, subject, token)
entity = cls(key=key, user=user, subject=subject, token=token)
entity.put()
return entity
开发者ID:Docalytics,项目名称:webapp-improved,代码行数:7,代码来源:models.py
示例12: _create
def _create(cls,**kwargs):
assert 'email' in kwargs, 'No email supplied'
new_hash = cls(token_hash=security.generate_random_string(length=cls._default_hash_length,pool=security.ALPHANUMERIC))
new_hash.populate(**kwargs)
new_hash.put()
return new_hash
开发者ID:xlfe,项目名称:sharehousegame,代码行数:8,代码来源:email.py
示例13: log_in_session_token_create
def log_in_session_token_create( self, user ):
# generate authentication token and add it to the db and the session
token = security.generate_random_string( entropy = 128 )
authtoken = EnkiModelTokenAuth( token = token, user_id = user.key.id() )
authtoken.put()
self.session[ 'auth_token' ] = token
self.session[ 'user_id' ] = user.key.id()
self.just_logged_in = True
开发者ID:juliettef,项目名称:enkiWS,代码行数:8,代码来源:handlerbase.py
示例14: test_generate_random_string
def test_generate_random_string(self):
self.assertRaises(ValueError, security.generate_random_string, None)
self.assertRaises(ValueError, security.generate_random_string, 0)
self.assertRaises(ValueError, security.generate_random_string, -1)
self.assertRaises(ValueError, security.generate_random_string, 1, 1)
token = security.generate_random_string(16)
self.assertTrue(re.match(r'^\w{16}$', token) is not None)
token = security.generate_random_string(32)
self.assertTrue(re.match(r'^\w{32}$', token) is not None)
token = security.generate_random_string(64)
self.assertTrue(re.match(r'^\w{64}$', token) is not None)
token = security.generate_random_string(128)
self.assertTrue(re.match(r'^\w{128}$', token) is not None)
开发者ID:AgentJay,项目名称:webapp-improved,代码行数:17,代码来源:extras_security_test.py
示例15: __init__
def __init__(self, user, subject, token=None, expires=60 * 60 * 24):
self.user = str(user)
self.subject = subject
if token:
self.token = token
else:
self.token = security.generate_random_string(entropy=128)
self.key = "%s.%s.%s" % (self.user, self.subject, self.token)
开发者ID:hackerdojo,项目名称:hd-signup,代码行数:8,代码来源:membership.py
示例16: save
def save(cls, user, name):
app = App(
user_id=user.key.id(),
name=name,
lower=name.lower(),
token=security.generate_random_string(length=30)
).put()
return app
开发者ID:IuryAlves,项目名称:magicSurface,代码行数:8,代码来源:model.py
示例17: post
def post(self):
email = self.request.get('email')
logging.info('Reset password for email: %s', email)
errors = []
messages = []
data = {
'page_title': 'Reset Password',
'errors': errors,
'messages': messages
}
if not email:
errors.append(
'You forgot to enter an email address.'
)
else:
user = User.user_from_email(email)
if not user:
errors.append(
'There is no account for this email address. Please check '
'that you typed in the correct email address.'
)
data['email'] = email
else:
expire = datetime.datetime.now()
expire += datetime.timedelta(hours=1)
code = generate_random_string(length=30)
user.pass_reset_code = code
user.pass_reset_expire = expire
user.put()
subject = 'HMPC: request to change password'
logging.info('generated verify code: %s' % code)
body = (
'This is an automated email form HMPC.\n\n'
'Please click the following link (or paste it into the '
'browser address bar) to change your password. This code '
'is valid for only one hour.\n\n'
'When you reset your password, you will be redirected to '
'the login page to login.\n\n'
'http://prelude-hmpc.appspot.com/password/%s\n'
)
mail.send_mail(
'[email protected]',
email,
subject,
body % code
)
msg = (
'An email has been sent to the following email address: %s.'
' Follow the instructions in the email to change your '
'password.'
)
messages.append(msg % email)
self.render('reset.html', **data)
开发者ID:PreludeAndFugue,项目名称:prelude-hmpc,代码行数:58,代码来源:user_admin.py
示例18: get_session_secret
def get_session_secret():
try:
return str(secrets.get('session'))
except KeyError:
# Make a new session key -- only happens once per hostname!
logging.warning('creating new session key!')
session_key = security.generate_random_string(entropy=256)
secrets.put('session', session_key)
return session_key
开发者ID:Kashomon,项目名称:test-infra,代码行数:9,代码来源:view_base.py
示例19: _generate_csrf_token
def _generate_csrf_token(self, _time=None):
"""Creates a new random token that can be safely used as a URL param.
Token would normally be stored in a user session and passed as 'state'
parameter during OAuth 2.0 authorization step.
"""
now = str(_time or long(time.time()))
secret = security.generate_random_string(30, pool=security.ASCII_PRINTABLE)
token = self.OAUTH2_CSRF_DELIMITER.join([secret, now])
return base64.urlsafe_b64encode(token)
开发者ID:yashrajsingh,项目名称:equilibrium-googleclouddeveloperchallenge2013,代码行数:10,代码来源:handler.py
示例20: create
def create(cls, email, password):
conflicts = User.fetchUser(email)
if conflicts:
return False
newUser = User()
newUser.email = email
newUser.passwordSalt = security.generate_random_string(entropy=64)
newUser.hashedPassword = security.hash_password(password, 'sha1', newUser.passwordSalt, passwordPepper)
newUser.creationDate = datetime.datetime.now()
return newUser.put()
开发者ID:RobJohnstone,项目名称:timeTracker,代码行数:10,代码来源:user.py
注:本文中的webapp2_extras.security.generate_random_string函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论