def forgot_password(): """Return forgot password page upon GET request. If POST, attempt to send user password reset or return respective error. """ if request.method == 'GET': return {} form = ForgotPasswordForm(request.form, prefix='forgot_password') if form.validate(): email = form.email.data user_obj = get_user(username=email) if user_obj: user_obj.verification_key = security.random_string(20) user_obj.save() reset_link = "http://{0}{1}".format( request.host, web_url_for('reset_password', verification_key=user_obj.verification_key)) mails.send_mail(to_addr=email, mail=mails.FORGOT_PASSWORD, reset_link=reset_link) status.push_status_message('Reset email sent to {0}'.format(email)) else: status.push_status_message( 'Email {email} not found'.format(email=email)) forms.push_errors_to_status(form.errors) return auth_login(forgot_password_form=form)
def reset_password(auth, **kwargs): if auth.logged_in: return auth_logout(redirect_url=request.url) verification_key = kwargs['verification_key'] form = ResetPasswordForm(request.form) user_obj = get_user(verification_key=verification_key) if not user_obj: error_data = { 'message_short': 'Invalid url.', 'message_long': 'The verification key in the URL is invalid or ' 'has expired.' } raise HTTPError(400, data=error_data) if request.method == 'POST' and form.validate(): # new random verification key, allows CAS to authenticate the user w/o password one time only. user_obj.verification_key = security.random_string(20) user_obj.set_password(form.password.data) user_obj.save() status.push_status_message('Password reset', 'success') # Redirect to CAS and authenticate the user with a verification key. return redirect( cas.get_login_url(web_url_for('user_account', _absolute=True), auto=True, username=user_obj.username, verification_key=user_obj.verification_key)) forms.push_errors_to_status(form.errors) return { 'verification_key': verification_key, }
def form_valid(self, form): email = form.cleaned_data.get('emails') user = get_user(email) if user is None or user.pk != self.kwargs.get('guid'): return HttpResponse( '{} with id "{}" and email "{}" not found.'.format( self.context_object_name.title(), self.kwargs.get('guid'), email), status=409) reset_abs_url = furl(DOMAIN) user.verification_key = random_string(20) user.save() reset_abs_url.path.add( ('resetpassword/{}'.format(user.verification_key))) send_mail(subject='Reset OSF Password', message='Follow this link to reset your password: {}'.format( reset_abs_url.url), from_email=SUPPORT_EMAIL, recipient_list=[email]) update_admin_log(user_id=self.request.user.id, object_id=user.pk, object_repr='User', message='Emailed user {} a reset link.'.format( user.pk), action_flag=USER_EMAILED) return super(ResetPasswordView, self).form_valid(form)
def forgot_password(): """Return forgot password page upon GET request. If POST, attempt to send user password reset or return respective error. """ if request.method == 'GET': return {} form = ForgotPasswordForm(request.form, prefix='forgot_password') if form.validate(): email = form.email.data user_obj = get_user(email=email) if user_obj: user_obj.verification_key = security.random_string(20) user_obj.save() reset_link = "http://{0}{1}".format( request.host, web_url_for('reset_password', verification_key=user_obj.verification_key)) mails.send_mail(to_addr=email, mail=mails.FORGOT_PASSWORD, reset_link=reset_link) status.push_status_message( 'An email with instructions on how to reset the password for the ' 'account associated with {0} has been sent. If you do not receive ' 'an email and believe you should have please ' 'contact OSF Support.'.format(email)) forms.push_errors_to_status(form.errors) return auth_login(forgot_password_form=form)
def forgot_password(): form = ForgotPasswordForm(request.form, prefix='forgot_password') if form.validate(): email = form.email.data user_obj = get_user(username=email) if user_obj: user_obj.verification_key = security.random_string(20) user_obj.save() reset_link = "http://{0}{1}".format( request.host, web_url_for( 'reset_password', verification_key=user_obj.verification_key ) ) mails.send_mail( to_addr=email, mail=mails.FORGOT_PASSWORD, reset_link=reset_link ) status.push_status_message('Reset email sent to {0}'.format(email)) else: status.push_status_message('Email {email} not found'.format(email=email)) forms.push_errors_to_status(form.errors) return auth_login(forgot_password_form=form)
def form_valid(self, form): email = form.cleaned_data.get('emails') user = get_user(email) if user is None or user.pk != self.kwargs.get('guid'): raise AttributeError reset_abs_url = furl(DOMAIN) user.verification_key = random_string(20) user.save() reset_abs_url.path.add(('resetpassword/{}'.format(user.verification_key))) send_mail( subject='Reset OSF Password', message='Follow this link to reset your password: {}'.format( reset_abs_url.url ), from_email=SUPPORT_EMAIL, recipient_list=[email] ) update_admin_log( user_id=self.request.user.id, object_id=user.pk, object_repr='User', message='Emailed user {} a reset link.'.format(user.pk), action_flag=USER_EMAILED ) return super(ResetPasswordView, self).form_valid(form)
def reset_password(auth, **kwargs): if auth.logged_in: return auth_logout(redirect_url=request.url) verification_key = kwargs['verification_key'] form = ResetPasswordForm(request.form) user_obj = get_user(verification_key=verification_key) if not user_obj: error_data = {'message_short': 'Invalid url.', 'message_long': 'The verification key in the URL is invalid or ' 'has expired.'} raise HTTPError(400, data=error_data) if request.method == 'POST' and form.validate(): # new random verification key, allows CAS to authenticate the user w/o password one time only. user_obj.verification_key = security.random_string(20) user_obj.set_password(form.password.data) user_obj.save() status.push_status_message('Password reset', 'success') # Redirect to CAS and authenticate the user with a verification key. return redirect(cas.get_login_url( web_url_for('user_account', _absolute=True), auto=True, username=user_obj.username, verification_key=user_obj.verification_key )) forms.push_errors_to_status(form.errors) return { 'verification_key': verification_key, }
def forgot_password_post(): """Attempt to send user password reset or return respective error. """ form = ForgotPasswordForm(request.form, prefix='forgot_password') if form.validate(): email = form.email.data user_obj = get_user(email=email) if user_obj: user_obj.verification_key = security.random_string(20) user_obj.save() reset_link = "http://{0}{1}".format( request.host, web_url_for( 'reset_password', verification_key=user_obj.verification_key ) ) mails.send_mail( to_addr=email, mail=mails.FORGOT_PASSWORD, reset_link=reset_link ) status.push_status_message( ('An email with instructions on how to reset the password ' 'for the account associated with {0} has been sent. If you ' 'do not receive an email and believe you should have please ' 'contact OSF Support.').format(email), 'success') forms.push_errors_to_status(form.errors) return auth_login(forgot_password_form=form)
def forgot_password_post(): """Attempt to send user password reset or return respective error. """ form = ForgotPasswordForm(request.form, prefix='forgot_password') if form.validate(): email = form.email.data user_obj = get_user(email=email) if user_obj: user_obj.verification_key = security.random_string(20) user_obj.save() reset_link = "http://{0}{1}".format( request.host, web_url_for('reset_password', verification_key=user_obj.verification_key)) mails.send_mail(to_addr=email, mail=mails.FORGOT_PASSWORD, reset_link=reset_link) status.push_status_message(( 'If there is an OSF account associated with {0}, an email with instructions on how to reset ' 'the OSF password has been sent to {0}. If you do not receive an email and believe you should ' 'have, please contact OSF Support. ').format(email), 'success') forms.push_errors_to_status(form.errors) return auth_login(forgot_password_form=form)
def confirm_email_get(token, auth=None, **kwargs): """View for email confirmation links. Authenticates and redirects to user settings page if confirmation is successful, otherwise shows an "Expired Link" error. methods: GET """ user = User.load(kwargs['uid']) is_merge = 'confirm_merge' in request.args is_initial_confirmation = not user.date_confirmed if user is None: raise HTTPError(http.NOT_FOUND) if auth and auth.user and (auth.user._id == user._id or auth.user._id == user.merged_by._id): if not is_merge: # determine if the user registered through a campaign campaign = campaigns.campaign_for_user(user) if campaign: return redirect( campaigns.campaign_url_for(campaign) ) status.push_status_message(language.WELCOME_MESSAGE, 'default', jumbotron=True) # Go to dashboard return redirect(web_url_for('dashboard')) status.push_status_message(language.MERGE_COMPLETE, 'success') return redirect(web_url_for('user_account')) try: user.confirm_email(token, merge=is_merge) except exceptions.EmailConfirmTokenError as e: raise HTTPError(http.BAD_REQUEST, data={ 'message_short': e.message_short, 'message_long': e.message_long }) if is_initial_confirmation: user.date_last_login = datetime.datetime.utcnow() user.save() # Send out our welcome message mails.send_mail( to_addr=user.username, mail=mails.WELCOME, mimetype='html', user=user ) # Redirect to CAS and authenticate the user with a verification key. user.verification_key = security.random_string(20) user.save() return redirect(cas.get_login_url( request.url, auto=True, username=user.username, verification_key=user.verification_key ))
def confirm_email_get(token, auth=None, **kwargs): """View for email confirmation links. Authenticates and redirects to user settings page if confirmation is successful, otherwise shows an "Expired Link" error. methods: GET """ user = User.load(kwargs['uid']) is_merge = 'confirm_merge' in request.args is_initial_confirmation = not user.date_confirmed if user is None: raise HTTPError(http.NOT_FOUND) if auth and auth.user and (auth.user._id == user._id or auth.user._id == user.merged_by._id): if not is_merge: # determine if the user registered through a campaign campaign = campaigns.campaign_for_user(user) if campaign: return redirect(campaigns.campaign_url_for(campaign)) status.push_status_message(language.WELCOME_MESSAGE, 'default', jumbotron=True) # Go to dashboard return redirect(web_url_for('dashboard')) status.push_status_message(language.MERGE_COMPLETE, 'success') return redirect(web_url_for('user_account')) try: user.confirm_email(token, merge=is_merge) except exceptions.EmailConfirmTokenError as e: raise HTTPError(http.BAD_REQUEST, data={ 'message_short': e.message_short, 'message_long': e.message_long }) if is_initial_confirmation: user.date_last_login = datetime.datetime.utcnow() user.save() # Send out our welcome message mails.send_mail(to_addr=user.username, mail=mails.WELCOME, mimetype='html', user=user) # Redirect to CAS and authenticate the user with a verification key. user.verification_key = security.random_string(20) user.save() return redirect( cas.get_login_url(request.url, auto=True, username=user.username, verification_key=user.verification_key))
def claim_user_form(auth, **kwargs): """View for rendering the set password page for a claimed user. Must have ``token`` as a querystring argument. Renders the set password form, validates it, and sets the user's password. """ uid, pid = kwargs['uid'], kwargs['pid'] token = request.form.get('token') or request.args.get('token') # If user is logged in, redirect to 're-enter password' page if auth.logged_in: return redirect( web_url_for('claim_user_registered', uid=uid, pid=pid, token=token)) user = User.load(uid) # The unregistered user # user ID is invalid. Unregistered user is not in database if not user: raise HTTPError(http.BAD_REQUEST) # If claim token not valid, redirect to registration page if not verify_claim_token(user, token, pid): return redirect(web_url_for('auth_login')) unclaimed_record = user.unclaimed_records[pid] user.fullname = unclaimed_record['name'] user.update_guessed_names() # The email can be the original referrer email if no claimer email has been specified. claimer_email = unclaimed_record.get( 'claimer_email') or unclaimed_record.get('email') form = SetEmailAndPasswordForm(request.form, token=token) if request.method == 'POST': if form.validate(): username, password = claimer_email, form.password.data user.register(username=username, password=password) # Clear unclaimed records user.unclaimed_records = {} user.verification_key = security.random_string(20) user.save() # Authenticate user and redirect to project page node = Node.load(pid) status.push_status_message( language.CLAIMED_CONTRIBUTOR.format(node=node), kind='success', trust=True) # Redirect to CAS and authenticate the user with a verification key. return redirect( cas.get_login_url(web_url_for('user_profile', _absolute=True), auto=True, username=user.username, verification_key=user.verification_key)) else: forms.push_errors_to_status(form.errors) return { 'firstname': user.given_name, 'email': claimer_email if claimer_email else '', 'fullname': user.fullname, 'form': forms.utils.jsonify(form) if is_json_request() else form, }
def setUp(self): super(TestForgotAndResetPasswordViews, self).setUp() self.user = AuthUserFactory() self.key = random_string(20) # manually set verifification key self.user.verification_key = self.key self.user.save() self.url = web_url_for('reset_password', verification_key=self.key)
def setUp(self): super(TestForgotAndResetPasswordViews, self).setUp() self.user = AuthUserFactory() self.key = random_string(20) # manually set verifification key self.user.verification_key = self.key self.user.save() self.url = web_url_for("reset_password", verification_key=self.key)
def claim_user_form(auth, **kwargs): """View for rendering the set password page for a claimed user. Must have ``token`` as a querystring argument. Renders the set password form, validates it, and sets the user's password. """ uid, pid = kwargs['uid'], kwargs['pid'] token = request.form.get('token') or request.args.get('token') # If user is logged in, redirect to 're-enter password' page if auth.logged_in: return redirect(web_url_for('claim_user_registered', uid=uid, pid=pid, token=token)) user = User.load(uid) # The unregistered user # user ID is invalid. Unregistered user is not in database if not user: raise HTTPError(http.BAD_REQUEST) # If claim token not valid, redirect to registration page if not verify_claim_token(user, token, pid): return redirect(web_url_for('auth_login')) unclaimed_record = user.unclaimed_records[pid] user.fullname = unclaimed_record['name'] user.update_guessed_names() # The email can be the original referrer email if no claimer email has been specified. claimer_email = unclaimed_record.get('claimer_email') or unclaimed_record.get('email') form = SetEmailAndPasswordForm(request.form, token=token) if request.method == 'POST': if form.validate(): username, password = claimer_email, form.password.data user.register(username=username, password=password) # Clear unclaimed records user.unclaimed_records = {} user.verification_key = security.random_string(20) user.save() # Authenticate user and redirect to project page node = Node.load(pid) status.push_status_message(language.CLAIMED_CONTRIBUTOR.format(node=node), kind='success', trust=True) # Redirect to CAS and authenticate the user with a verification key. return redirect(cas.get_login_url( web_url_for('user_profile', _absolute=True), auto=True, username=user.username, verification_key=user.verification_key )) else: forms.push_errors_to_status(form.errors) return { 'firstname': user.given_name, 'email': claimer_email if claimer_email else '', 'fullname': user.fullname, 'form': forms.utils.jsonify(form) if is_json_request() else form, }
def create_fake_user(): email = fake.email() name = fake.name() parsed = utils.impute_names(name) user = UserFactory.build(username=email, fullname=name, is_registered=True, is_claimed=True, verification_key=security.random_string(15), date_registered=fake.date_time(), emails=[email], **parsed ) user.set_password('faker123') user.save() logger.info('Created user: {0} <{1}>'.format(user.fullname, user.username)) return user
def create_fake_user(): email = fake.email() name = fake.name() parsed = impute_names(name) user = UserFactory(username=email, fullname=name, is_registered=True, is_claimed=True, verification_key=security.random_string(15), date_registered=fake.date_time(), emails=[email], **parsed) user.set_password('faker123') user.save() return user
def create_fake_user(): email = fake.email() name = fake.name() parsed = utils.impute_names(name) user = UserFactory.build(username=email, fullname=name, is_registered=True, is_claimed=True, verification_key=security.random_string(15), date_registered=fake.date_time(), emails=[email], **parsed) user.set_password('faker123') user.save() logger.info('Created user: {0} <{1}>'.format(user.fullname, user.username)) return user
def confirm_email_get(**kwargs): """View for email confirmation links. Authenticates and redirects to user settings page if confirmation is successful, otherwise shows an "Expired Link" error. methods: GET """ user = User.load(kwargs['uid']) is_initial_confirmation = not user.date_confirmed is_merge = 'confirm_merge' in request.args token = kwargs['token'] if user is None: raise HTTPError(http.NOT_FOUND) try: user.confirm_email(token, merge=is_merge) except exceptions.EmailConfirmTokenError as e: raise HTTPError(http.BAD_REQUEST, data={ 'message_short': e.message_short, 'message_long': e.message_long }) if is_initial_confirmation: user.date_last_login = datetime.datetime.utcnow() user.save() # Go to settings page status.push_status_message(language.WELCOME_MESSAGE, 'success') redirect_url = web_url_for('user_profile', _absolute=True) else: redirect_url = web_url_for('user_account', _absolute=True) if is_merge: status.push_status_message(language.MERGE_COMPLETE, 'success') else: status.push_status_message(language.CONFIRMED_EMAIL, 'success') # Redirect to CAS and authenticate the user with a verification key. user.verification_key = security.random_string(20) user.save() return redirect(cas.get_login_url( redirect_url, auto=True, username=user.username, verification_key=user.verification_key ))
def confirm_email_get(**kwargs): """View for email confirmation links. Authenticates and redirects to user settings page if confirmation is successful, otherwise shows an "Expired Link" error. methods: GET """ user = User.load(kwargs['uid']) is_initial_confirmation = not user.date_confirmed is_merge = 'confirm_merge' in request.args token = kwargs['token'] if user is None: raise HTTPError(http.NOT_FOUND) try: user.confirm_email(token, merge=is_merge) except exceptions.EmailConfirmTokenError as e: raise HTTPError(http.BAD_REQUEST, data={ 'message_short': e.message_short, 'message_long': e.message_long }) if is_initial_confirmation: user.date_last_login = datetime.datetime.utcnow() user.save() # Go to settings page status.push_status_message(language.WELCOME_MESSAGE, 'success') redirect_url = web_url_for('user_profile', _absolute=True) else: redirect_url = web_url_for('user_account', _absolute=True) if is_merge: status.push_status_message(language.MERGE_COMPLETE, 'success') else: status.push_status_message(language.CONFIRMED_EMAIL, 'success') # Redirect to CAS and authenticate the user with a verification key. user.verification_key = security.random_string(20) user.save() return redirect(cas.get_login_url( redirect_url, auto=True, username=user.username, verification_key=user.verification_key ))
def create_fake_user(): email = fake.email() name = fake.name() parsed = impute_names(name) user = UserFactory( username=email, fullname=name, is_registered=True, is_claimed=True, verification_key=security.random_string(15), date_registered=fake.date_time(), emails=[email], **parsed ) user.set_password('faker123') user.save() return user
def form_valid(self, form): email = form.cleaned_data.get('emails') user = get_user(email) if user is None: raise TypeError reset_abs_url = furl(DOMAIN) user.verification_key = random_string(20) user.save() reset_abs_url.path.add( ('resetpassword/{}'.format(user.verification_key))) send_mail(subject='Reset OSF Password', message='Follow this link to reset your password: {}'.format( reset_abs_url.url), from_email=SUPPORT_EMAIL, recipient_list=[email]) return super(ResetPasswordView, self).form_valid(form)
def generate_verification_key(verification_type=None): """ Generate a one-time verification key with an optional expiration time. The type of the verification key determines the expiration time defined in `website.settings.EXPIRATION_TIME_DICT`. :param verification_type: None, verify, confirm or claim :return: a string or a dictionary """ token = security.random_string(30) # v1 with only the token if not verification_type: return token # v2 with a token and the expiration time expires = timezone.now() + dt.timedelta(minutes=settings.EXPIRATION_TIME_DICT[verification_type]) return { 'token': token, 'expires': expires, }
def get_or_create_user(fullname, address, is_spam): """Get or create user by email address. """ user = User.find(Q('username', 'iexact', address)) user = user[0] if user.count() else None user_created = False if user is None: password = str(uuid.uuid4()) user = User.create_confirmed(address, password, fullname) user.verification_key = security.random_string(20) # Flag as potential spam account if Mailgun detected spam if is_spam: user.system_tags.append('is_spam') user.save() user_created = True return user, user_created
def generate_verification_key(verification_type=None): """ Generate a one-time verification key with an optional expiration time. The type of the verification key determines the expiration time defined in `website.settings.EXPIRATION_TIME_DICT`. :param verification_type: None, verify, confirm or claim :return: a string or a dictionary """ token = security.random_string(30) # v1 with only the token if not verification_type: return token # v2 with a token and the expiration time expires = timezone.now() + dt.timedelta(minutes=settings.EXPIRATION_TIME_DICT[verification_type]) return { 'token': token, 'expires': expires, }
def get_or_create_user(fullname, address, is_spam): """Get or create user by email address. """ user = User.find(Q('username', 'iexact', address)) user = user[0] if user.count() else None user_created = False if user is None: password = str(uuid.uuid4()) user = User.create_confirmed(address, password, fullname) user.verification_key = security.random_string(20) # Flag as potential spam account if Mailgun detected spam if is_spam: user.system_tags.append('is_spam') user.save() user_created = True return user, user_created
def get_or_create_user(fullname, address, is_spam): """Get or create user by email address. :param str fullname: User full name :param str address: User email address :param bool is_spam: User flagged as potential spam :return: Tuple of (user, created) """ user = get_user(email=address) if user: return user, False else: password = str(uuid.uuid4()) user = User.create_confirmed(address, password, fullname) user.verification_key = security.random_string(20) if is_spam: user.system_tags.append('is_spam') user.save() return user, True
def form_valid(self, form): email = form.cleaned_data.get('emails') user = get_user(email) if user is None: raise TypeError reset_abs_url = furl(DOMAIN) user.verification_key = random_string(20) user.save() reset_abs_url.path.add(('resetpassword/{}'.format(user.verification_key))) send_mail( subject='Reset OSF Password', message='Follow this link to reset your password: {}'.format( reset_abs_url.url ), from_email=SUPPORT_EMAIL, recipient_list=[email] ) return super(ResetPasswordView, self).form_valid(form)
def get_or_create_user(fullname, address, is_spam): """Get or create user by email address. :param str fullname: User full name :param str address: User email address :param bool is_spam: User flagged as potential spam :return: Tuple of (user, created) """ try: user = User.find_one(Q('username', 'iexact', address)) return user, False except ModularOdmException: password = str(uuid.uuid4()) user = User.create_confirmed(address, password, fullname) user.verification_key = security.random_string(20) if is_spam: user.system_tags.append('is_spam') user.save() return user, True
def get_or_create_user(fullname, address, is_spam=False): """Get or create user by email address. :param str fullname: User full name :param str address: User email address :param bool is_spam: User flagged as potential spam :return: Tuple of (user, created) """ user = get_user(email=address) if user: return user, False else: from website import security # Avoid circular imports password = str(uuid.uuid4()) user = User.create_confirmed(address, password, fullname) user.verification_key = security.random_string(20) if is_spam: user.system_tags.append('is_spam') return user, True
def get_or_create_user(fullname, address, is_spam): """Get or create user by email address. :param str fullname: User full name :param str address: User email address :param bool is_spam: User flagged as potential spam :return: Tuple of (user, created) """ try: user = User.find_one(Q('username', 'iexact', address)) return user, False except ModularOdmException: password = str(uuid.uuid4()) user = User.create_confirmed(address, password, fullname) user.verification_key = security.random_string(20) if is_spam: user.system_tags.append('is_spam') user.save() return user, True
def forgot_password_post(): """Attempt to send user password reset or return respective error. """ form = ForgotPasswordForm(request.form, prefix='forgot_password') if form.validate(): email = form.email.data status_message = ('If there is an OSF account associated with {0}, an email with instructions on how to reset ' 'the OSF password has been sent to {0}. If you do not receive an email and believe you ' 'should have, please contact OSF Support. ').format(email) user_obj = get_user(email=email) if user_obj: #TODO: Remove this rate limiting and replace it with something that doesn't write to the User model now = datetime.datetime.utcnow() last_attempt = user_obj.forgot_password_last_post or now - datetime.timedelta(seconds=FORGOT_PASSWORD_MINIMUM_TIME) user_obj.forgot_password_last_post = now time_since_last_attempt = now - last_attempt if time_since_last_attempt.seconds >= FORGOT_PASSWORD_MINIMUM_TIME: user_obj.verification_key = security.random_string(20) user_obj.save() reset_link = "http://{0}{1}".format( request.host, web_url_for( 'reset_password', verification_key=user_obj.verification_key ) ) mails.send_mail( to_addr=email, mail=mails.FORGOT_PASSWORD, reset_link=reset_link ) status.push_status_message(status_message, 'success') else: user_obj.save() status.push_status_message('You have recently requested to change your password. Please wait a little ' 'while before trying again.', 'error') else: status.push_status_message(status_message, 'success') forms.push_errors_to_status(form.errors) return auth_login(forgot_password_form=form)
def forgot_password_post(): """Attempt to send user password reset or return respective error. """ form = ForgotPasswordForm(request.form, prefix='forgot_password') if form.validate(): email = form.email.data status_message = ( 'If there is an OSF account associated with {0}, an email with instructions on how to reset ' 'the OSF password has been sent to {0}. If you do not receive an email and believe you ' 'should have, please contact OSF Support. ').format(email) user_obj = get_user(email=email) if user_obj: if throttle_period_expired(user_obj.email_last_sent, settings.SEND_EMAIL_THROTTLE): user_obj.verification_key = security.random_string(20) user_obj.email_last_sent = datetime.datetime.utcnow() user_obj.save() reset_link = furl.urljoin( settings.DOMAIN, web_url_for('reset_password', verification_key=user_obj.verification_key)) mails.send_mail(to_addr=email, mail=mails.FORGOT_PASSWORD, reset_link=reset_link) status.push_status_message(status_message, kind='success', trust=False) else: status.push_status_message( 'You have recently requested to change your password. Please wait a little ' 'while before trying again.', kind='error', trust=False) else: status.push_status_message(status_message, kind='success', trust=False) forms.push_errors_to_status(form.errors) return auth_login(forgot_password_form=form)
def box_oauth_start(auth, **kwargs): user = auth.user # Store the node ID on the session in order to get the correct redirect URL # upon finishing the flow nid = kwargs.get('nid') or kwargs.get('pid') node = Node.load(nid) if node and not node.is_contributor(user): raise HTTPError(http.FORBIDDEN) csrf_token = security.random_string(10) session.data['box_oauth_state'] = csrf_token if nid: session.data['box_auth_nid'] = nid # Handle if user has already authorized box if user.has_addon('box') and user.get_addon('box').has_auth: return redirect(web_url_for('user_addons')) return redirect(get_auth_flow(csrf_token))
def forgot_password_post(): """Attempt to send user password reset or return respective error. """ form = ForgotPasswordForm(request.form, prefix='forgot_password') if form.validate(): email = form.email.data status_message = ( 'If there is an OSF account associated with {0}, an email with instructions on how to reset ' 'the OSF password has been sent to {0}. If you do not receive an email and believe you ' 'should have, please contact OSF Support. ').format(email) user_obj = get_user(email=email) if user_obj: #TODO: Remove this rate limiting and replace it with something that doesn't write to the User model now = datetime.datetime.utcnow() last_attempt = user_obj.forgot_password_last_post or now - datetime.timedelta( seconds=FORGOT_PASSWORD_MINIMUM_TIME) user_obj.forgot_password_last_post = now time_since_last_attempt = now - last_attempt if time_since_last_attempt.seconds >= FORGOT_PASSWORD_MINIMUM_TIME: user_obj.verification_key = security.random_string(20) user_obj.save() reset_link = "http://{0}{1}".format( request.host, web_url_for('reset_password', verification_key=user_obj.verification_key)) mails.send_mail(to_addr=email, mail=mails.FORGOT_PASSWORD, reset_link=reset_link) status.push_status_message(status_message, 'success') else: user_obj.save() status.push_status_message( 'You have recently requested to change your password. Please wait a little ' 'while before trying again.', 'error') else: status.push_status_message(status_message, 'success') forms.push_errors_to_status(form.errors) return auth_login(forgot_password_form=form)
def box_oauth_start(auth, **kwargs): user = auth.user # Store the node ID on the session in order to get the correct redirect URL # upon finishing the flow nid = kwargs.get('nid') or kwargs.get('pid') node = Node.load(nid) if node and not node.is_contributor(user): raise HTTPError(http.FORBIDDEN) csrf_token = security.random_string(10) session.data['box_oauth_state'] = csrf_token if nid: session.data['box_auth_nid'] = nid # Handle if user has already authorized box if user.has_addon('box') and user.get_addon('box').has_auth: return redirect(web_url_for('user_addons')) return redirect(get_auth_flow(csrf_token))
def forgot_password_post(): """Attempt to send user password reset or return respective error. """ form = ForgotPasswordForm(request.form, prefix='forgot_password') if form.validate(): email = form.email.data status_message = ('If there is an OSF account associated with {0}, an email with instructions on how to reset ' 'the OSF password has been sent to {0}. If you do not receive an email and believe you ' 'should have, please contact OSF Support. ').format(email) user_obj = get_user(email=email) if user_obj: if throttle_period_expired(user_obj.email_last_sent, settings.SEND_EMAIL_THROTTLE): user_obj.verification_key = security.random_string(20) user_obj.email_last_sent = datetime.datetime.utcnow() user_obj.save() reset_link = furl.urljoin( settings.DOMAIN, web_url_for( 'reset_password', verification_key=user_obj.verification_key ) ) mails.send_mail( to_addr=email, mail=mails.FORGOT_PASSWORD, reset_link=reset_link ) status.push_status_message(status_message, kind='success', trust=False) else: status.push_status_message('You have recently requested to change your password. Please wait a little ' 'while before trying again.', kind='error', trust=False) else: status.push_status_message(status_message, kind='success', trust=False) forms.push_errors_to_status(form.errors) return auth_login(forgot_password_form=form)
def generate_claim_token(): return security.random_string(30)
def test_random_string(): s = security.random_string(length=30) assert_true(isinstance(s, basestring)) assert_equal(len(s), 30) s2 = security.random_string(30) assert_not_equal(s, s2)
def generate_token_id(): return random_string(length=70)
def generate_client_secret(): return random_string(length=40)
def generate_client_secret(): return random_string(length=40)
def generate_token_id(): return random_string(length=70)
def generate_claim_token(): return security.random_string(30)