本文整理汇总了Python中itsdangerous.URLSafeSerializer类的典型用法代码示例。如果您正苦于以下问题:Python URLSafeSerializer类的具体用法?Python URLSafeSerializer怎么用?Python URLSafeSerializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了URLSafeSerializer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute
def execute(self, payload):
# 1. Extract user id from payload
key = self._settings['cookie_secret']
s = URLSafeSerializer(key)
uid = None
try:
uid = ObjectId(s.loads(payload))
except BadSignature:
raise tornado.web.HTTPError(400)
db = self._settings['db']
# 2. Determine if user exists and is in unconfirmed state
user = yield db.users.find_one({ '_id': uid, 'status': UserStatus.unconfirmed })
if not user:
raise tornado.web.HTTPError(410)
# 3. Set user status to active
yield db.users.update({ '_id': uid}, { '$set': { 'status': UserStatus.active } })
# 4. Determine lifespan of new session
lifespan = self._settings['session_lifespan']
# 5. Insert new session
now = datetime.utcnow()
sessionId = yield db.sessions.insert({ 'userId': uid,
'created': now,
'persistentCookie': True,
'expires': now + timedelta(days=lifespan) })
return EmailVerificationResult(user, sessionId, lifespan)
示例2: confirm
def confirm(payload=None):
''' This is where user creation lives, for now...
'''
# TODO: Get this out of here!
form = ConfirmForm()
if request.method == 'GET':
s = URLSafeSerializer(app.config['SECRET_KEY'])
try:
user_id = s.loads(payload)
except BadSignature:
abort(404)
user = User.objects.get(id=user_id)
if not user.registered:
user.activate()
flash("Your email has been verified.")
AdminAlertEmail(subject="Confirmed user: %s" % user.email, body="User %s has confirmed their email address." % user.email).send()
session["user_id"] = user_id # TODO: Why is this here?
return render_template("confirm.html", form=form)
else:
return redirect(url_for("root.index"))
if form.validate_on_submit():
user = User.objects.get(id=session["user_id"])
user.password = generate_password_hash(form.password.data)
user.registered = True
RegistrationEmail(user.email).send()
AdminAlertEmail(subject="Registered user: %s" % user.email, body="User %s has finished registration." % user.email).send()
user.save()
login_user(user)
return redirect(url_for("root.index"))
return render_template("confirm.html", form=form)
示例3: login_as_user
def login_as_user(id):
s = URLSafeSerializer(app.config['SECRET_KEY'])
payload = {"id": id, "stamp": time.time()}
token = s.dumps(payload)
pieces = [app.config["LIME_URL"], 'trowel', token]
url = '/'.join(piece.strip('/') for piece in pieces)
return redirect(url)
示例4: send_confirmmail_to_unregistered_users
def send_confirmmail_to_unregistered_users(items):
"""Send a confirmation email for external signups(email only)
Args:
item: The item, which was just inserted into the database
"""
for item in items:
if 'user' not in item:
event = current_app.data.find_one(
'events', None,
**{current_app.config['ID_FIELD']: item['event']})
title = event.get('title_en') or event.get('title_de')
s = URLSafeSerializer(get_token_secret())
token = s.dumps(str(item['_id']))
if current_app.config.get('SERVER_NAME') is None:
current_app.logger.warning("SERVER_NAME is not set. E-Mail "
"links will not work!")
confirm_link = url_for('emails.on_confirm_email', token=token,
_external=True)
mail([item['email']],
'Registration for %s' % title,
current_app.config['CONFIRM_EMAIL_TEXT'].format(
title=title,
link=confirm_link))
示例5: resetpassword
def resetpassword():
form = PasswordResetForm()
if form.validate_on_submit():
if form.username.data:
user = Users.query.filter_by(username=form.username.data).first()
elif form.email.data:
user = Users.query.filter_by(email=form.email.data).first()
else:
flash("Username or password doesn't exists")
if user:
if user.email:
s = URLSafeSerializer('serliaizer_code')
key = s.dumps([user.username, user.email])
msg = Message("Password reset", sender="[email protected]_host.com", recipients=[user.email])
msg.html = "<b>Click on this link to reset your password.</b> \
#<a href='http://127.0.0.1:5000/passwordreset/ \
" + key + "'>http://127.0.0.1:5000/passwordreset/ \
" + key + "</a>"
send_async_email(msg)
flash('Email sent to: ' + user.email)
return redirect(url_for('resetpassword'))
else:
flash('No such user')
return redirect(url_for('resetpassword'))
flash(u'Enter your email or username')
return render_template('reset_password.html', form=form)
示例6: create_reset_link
def create_reset_link(user):
l = "http://localhost:5001/reset/"
s = URLSafeSerializer("hacker-bees")
token = s.dumps(user.id)
l += token
user.reset_time = datetime.today()
return l
示例7: register
def register():
form = RegisterUserForm()
if form.validate_on_submit():
user = User.create(
username=form.data['username'],
email=form.data['email'],
password=form.data['password'],
remote_addr=request.remote_addr,
)
s = URLSafeSerializer(current_app.secret_key)
token = s.dumps(user.id)
send_registration_email.delay(user, token)
flash(
gettext(
'Sent verification email to {email}'.format(
email=user.email
)
),
'success'
)
return redirect(url_for('index'))
return render_template('register.html', form=form)
示例8: resend_activation_email
def resend_activation_email(email_to_activate):
"""
Function to resend the activation email
"""
#check local database
loc_db_user = AdsUserRecord.query.filter(AdsUserRecord.username==email_to_activate) #@UndefinedVariable
#get the user object
user_rec = loc_db_user.first()
if user_rec:
#create an itsdangerous object to sign the verification email
itsd = URLSafeSerializer(config.ACCOUNT_VERIFICATION_SECRET)
#send the confirmation email
act_code = itsd.dumps(email_to_activate)
message_html = """<h3>Dear %(name)s %(lastname)s, thank you for registering to the NASA ADS</h3>
<p>Your activation code is <strong>%(code)s</strong></p>
<p>To activate your account, please click <a href="%(act_url)s">here</a></p>
<p>If the link doesn't work, please copy the following URL and paste it in your browser:<br/>%(act_url)s</p>
<p>Please do not replay to this email: to contact us please use our <a href="%(feedb_url)s">feedback form</a></p>
<p>Regards,<br/>The ADS team</p>
""" % {'name':user_rec.firstname, 'lastname':user_rec.lastname, 'code':act_code,
'act_url': '%s%s?id=%s' % (config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for('user.activate'), act_code),
'feedb_url' : '%s%s'%(config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for('feedback.feedback'))
}
try:
send_email_to_user(u"NASA ADS Account confirmation required", message_html, [email_to_activate])
except:
app.logger.error('Failed to re-send confirmation email for user creation')
return False, 'There are some technical problems: please try later.', 'error'
return True, 'A new email with the activation code has been sent to your email address.', 'success'
else:
app.logger.error('Tried to re-send confirmation email for user creation for user not yet created or not stored in the DB. Email used %s' % email_to_activate)
return False, 'The user with the given email does not exist', 'error'
示例9: get_context_data
def get_context_data(self, **kwargs):
context = super(AlbumView, self).get_context_data(**kwargs)
serializer = URLSafeSerializer(settings.SECRET_KEY)
token = serializer.dumps({'album_id': self.object.id})
context['token'] = token
context['album'] = self.object
return context
示例10: new_task
def new_task(app_id):
# Check if the request has an arg:
try:
app = db.session.query(model.App).get(app_id)
if app is None:
raise NotFound
if request.args.get('offset'):
offset = int(request.args.get('offset'))
else:
offset = 0
user_id = None if current_user.is_anonymous() else current_user.id
user_ip = request.remote_addr if current_user.is_anonymous() else None
task = sched.new_task(app_id, user_id, user_ip, offset)
# If there is a task for the user, return it
if task:
s = URLSafeSerializer(current_app.config.get('SECRET_KEY'))
r = make_response(json.dumps(task.dictize()))
r.mimetype = "application/json"
cookie_id = 'task_run_for_task_id_%s' % task.id
r.set_cookie(cookie_id, s.dumps(task.dictize()))
return r
else:
return Response(json.dumps({}), mimetype="application/json")
except Exception as e:
return error.format_exception(e, target='app', action='GET')
示例11: generate_jwt
def generate_jwt(claims, lifetime=None, expires=None, not_before=None):
"""
Generate a JSON Web Token.
- **exp** (*IntDate*) -- The UTC expiry date and time of the token, in number of seconds from 1970-01-01T0:0:0Z UTC.
- **iat** (*IntDate*) -- The UTC date and time at which the token was generated.
- **nbf** (*IntDate*) -- The UTC valid-from date and time of the token.
- **jti** (*str*) -- A unique identifier for the token.
"""
claims = dict(claims)
now = datetime.utcnow()
claims['iat'] = timegm(now.utctimetuple())
claims['nbf'] = timegm((not_before or now).utctimetuple())
claims['jti'] = urlsafe_b64encode(urandom(128))
if lifetime:
claims['exp'] = timegm((now + lifetime).utctimetuple())
elif expires:
claims['exp'] = timegm(expires.utctimetuple())
signer = URLSafeSerializer(SECRET_KEY)
return signer.dumps(claims)
示例12: save
def save(self, *args, **kwargs):
from itsdangerous import URLSafeSerializer
s = URLSafeSerializer(SECRET_KEY)
x = datetime.now()
self.ss_id = s.dumps(str(x))
if self.pk is None:
super(Question, self).save(self, *args, **kwargs)
示例13: _update_object
def _update_object(self, obj):
"""Validate the task_run object and update it with user id or ip."""
s = URLSafeSerializer(current_app.config.get('SECRET_KEY'))
# Get the cookie with the task signed for the current task_run
cookie_id = 'task_run_for_task_id_%s' % obj.task_id
task_cookie = request.cookies.get(cookie_id)
if task_cookie is None:
raise Unauthorized("Missing task cookie for posting"
" a valid task_run")
# Load the real task from the DB
task_cookie = s.loads(task_cookie)
task = db.session.query(model.Task).get(task_cookie['id'])
if ((task is None) or (task.id != obj.task_id)): # pragma: no cover
raise Forbidden('Invalid task_id')
if (task.app_id != obj.app_id):
raise Forbidden('Invalid app_id')
if not current_user.is_anonymous():
obj.user = current_user
else:
obj.user_ip = request.remote_addr
# Check if this task_run has already been posted
task_run = db.session.query(model.TaskRun)\
.filter_by(app_id=obj.app_id)\
.filter_by(task_id=obj.task_id)\
.filter_by(user=obj.user)\
.filter_by(user_ip=obj.user_ip)\
.first()
if task_run is not None:
raise Forbidden('You have already posted this task_run')
示例14: reset_request
def reset_request(self, **kw):
user = model.provider.query(app_model.User, filters=dict(email_address=kw['email_address']))[1][0]
password_frag = user.password[0:4]
serializer = URLSafeSerializer(tg.config['beaker.session.secret'])
serialized_data = serializer.dumps(dict(request_date=datetime.utcnow().strftime('%m/%d/%Y %H:%M'),
email_address=kw['email_address'], password_frag=password_frag))
password_reset_link = tg.url(self.mount_point + "/change_password/", params=dict(data=serialized_data),
qualified=True)
reset_password_config = tg.config.get('_pluggable_resetpassword_config')
mail_body = reset_password_config.get('mail_body', _('''
We've received a request to reset the password for this account.
Please click this link to reset your password:
%(password_reset_link)s
If you no longer wish to make the above change, or if you did not initiate this request, please disregard and/or delete this e-mail.
'''))
email_data = {'sender': tg.config['resetpassword.email_sender'],
'subject': reset_password_config.get('mail_subject', _('Password reset request')),
'body': mail_body,
'rich': reset_password_config.get('mail_rich', '')}
tg.hooks.notify('resetpassword.on_request', args=(user, email_data, password_reset_link))
email_data['body'] = email_data['body'] % dict(password_reset_link=password_reset_link)
email_data['rich'] = email_data['rich'] % dict(password_reset_link=password_reset_link)
send_email(user.email_address, **email_data)
flash(_('Password reset request sent'))
return plug_redirect('resetpassword', '/')
示例15: confirm_invite
def confirm_invite(request, volunteer_campaign_id):
serializer = URLSafeSerializer(settings.SECRET_KEY)
try:
volunteer_campaign_id = serializer.loads(volunteer_campaign_id)
except BadSignature as e:
raise Http404(str(e))
volunteer_campaign = get_object_or_404(VolunteerCampaign, pk=volunteer_campaign_id)
if request.user.is_authenticated() and volunteer_campaign.volunteer != request.user.volunteer:
raise Http404('Invitation was sent to other volunteer.')
response = log_user_in(request, volunteer_campaign.volunteer.user)
if response is not None:
return response
if request.method == 'POST':
if request.POST.get('action') == 'accept':
volunteer_campaign.accepted = True
get_adapter().send_mail('emails/volunteer_accept', volunteer_campaign.organisation.user.email, {
'volunteer': volunteer_campaign.volunteer,
})
else:
volunteer_campaign.accepted = False
volunteer_campaign.save()
return redirect('volunteer_profile')
return render(request, 'volunteers/confirm.html', {
'organisation': volunteer_campaign.organisation,
})