コード例 #1
0
ファイル: views.py プロジェクト: umdsp/romeu
def reset_password(request, reset_password_key=None):
    
    try:
        vprk=ValidPasswordResetKey.objects.get(
                                        reset_password_key=reset_password_key)    
    except:
        msg = _("The password reset key is invalid")
        messages.error(request, msg)
        return HttpResponseRedirect(reverse('accounts_login'))
    if request.method == 'POST':
        form = PasswordResetForm(request.POST)
        if form.is_valid():
            vprk.user.set_password(form.cleaned_data['password1'])
            vprk.user.save()
            vprk.delete()
            logout(request)
            msg = _("Your password has been reset. Please login with your new password.")
            messages.success(request, msg)
            return HttpResponseRedirect(reverse('accounts_login'))            
        else:
            return render_to_response('accounts/reset-password.html',
                                      RequestContext(request,
                                    {'form': form,
                                     'reset_password_key': reset_password_key}))  
        
    return render_to_response('accounts/reset-password.html',
                              RequestContext(request,
                                    {'form': PasswordResetForm(),
                                    'reset_password_key': reset_password_key}))
コード例 #2
0
def reset_password(request):
    feedback = {'status': None, 'data': None}
    if request.method == 'POST':
        print(request.POST)
        form = PasswordResetForm(request.POST)
        if form.is_valid():
            old_Password = form.cleaned_data['old_password']
            new_Password = form.cleaned_data['new_password']
            confirm_New_Password = form.cleaned_data['confirm_new_password']
            if (new_Password == confirm_New_Password
                ) and request.user.check_password(old_Password):
                request.user.set_password(new_Password)
                request.user.save()
                feedback['status'] = 'OK'
                feedback['data'] = "Password has been reset successfully."
            else:
                feedback['status'] = 'FAIL'
                feedback[
                    'data'] = "An Error occurred. Password change unsuccessful."
        else:
            feedback['status'] = 'FAIL'
            feedback[
                'data'] = "An Error occurred. Password change unsuccessful."
            feedback['form'] = 'invalid'

    return HttpResponse(json.dumps(feedback), content_type="application/json")
コード例 #3
0
ファイル: app.py プロジェクト: lijielife/stockhawk
def settings():
    loggedin_user = get_user()
    user, allplayers, leaders = get_leaderboard(loggedin_user)
    form = PasswordResetForm(request.form)
    deleteform = DeleteAccountForm(request.form)
    title = "{}'s account settings".format(user.name)

    if request.method == 'POST' and form.validate():
        if form.old_password.data == user.password:
            flash("Your password has been reset.")
            user.password = form.new_password.data
            db.session.commit()
            password_reset_email(user)
            return redirect(url_for('user'))
        else:
            flash("Your old password was incorrect. Please try again.")
            return redirect(url_for('settings'))

    elif request.method == 'POST' and not form.validate():
        flash("Something went wrong; please try again.")
        return redirect(url_for('settings'))

    else:
        return render_template('settings.html',
                               title=title,
                               loggedin_user=loggedin_user,
                               user=user,
                               form=form,
                               deleteform=deleteform)
コード例 #4
0
ファイル: views.py プロジェクト: ThanHuuTuan/monitor
 def put(self):
     data = ImmutableMultiDict(request.json)
     reset_password_form = PasswordResetForm(data, csrf_enabled=False)
     if reset_password_form.validate():
         reset_password_form.save()
         return {"status": "success", "message": "Password reset done"}
     return reset_password_form.errors
コード例 #5
0
def reset_password():
    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="your_id@your_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('reset_password'))
        else:
            flash('No such user')
            return redirect(url_for('reset_password'))
    flash(u'Enter your email or username')
    return render_template('reset_password.html', form=form)
コード例 #6
0
ファイル: views.py プロジェクト: homoludens/EventMap
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 not in system")
          
        if user:
          if user.email:
            s = URLSafeSerializer('12fe454t')
            key = s.dumps([user.username, user.email])
            #s.loads('WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo')
            
            msg = Message("Password reset", sender="*****@*****.**", recipients=[user.email])
            msg.html = "<b>testing</b> \
                        #<a href='http://127.0.0.1:5000/passwordreset/" + key + "'>http://127.0.0.1:5000/passwordreset/" + key + "</a>"

            print msg.html
            mail.send(msg)
            
            flash('Email sent to: ' + user.email)
            return redirect(url_for('resetpassword'))
          else:
            flash('No such user')
            return redirect(url_for('resetpassword'))
        else:
            flash('No such user')
            return redirect(url_for('resetpassword'))

    return render_template('reset_password.html', form=form)
コード例 #7
0
ファイル: views.py プロジェクト: umdsp/romeu
def reset_password(request, reset_password_key=None):

    try:
        vprk = ValidPasswordResetKey.objects.get(
            reset_password_key=reset_password_key)
    except:
        msg = _("The password reset key is invalid")
        messages.error(request, msg)
        return HttpResponseRedirect(reverse('accounts_login'))
    if request.method == 'POST':
        form = PasswordResetForm(request.POST)
        if form.is_valid():
            vprk.user.set_password(form.cleaned_data['password1'])
            vprk.user.save()
            vprk.delete()
            logout(request)
            msg = _(
                "Your password has been reset. Please login with your new password."
            )
            messages.success(request, msg)
            return HttpResponseRedirect(reverse('accounts_login'))
        else:
            return render_to_response(
                'accounts/reset-password.html',
                RequestContext(request, {
                    'form': form,
                    'reset_password_key': reset_password_key
                }))

    return render_to_response(
        'accounts/reset-password.html',
        RequestContext(request, {
            'form': PasswordResetForm(),
            'reset_password_key': reset_password_key
        }))
コード例 #8
0
ファイル: views.py プロジェクト: Widdershin/flaskCamel
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="your_id@your_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)
コード例 #9
0
ファイル: app.py プロジェクト: TonyGu423/stockhawk
def settings():
    loggedin_user = get_user()
    user, allplayers, leaders = get_leaderboard(loggedin_user)
    form = PasswordResetForm(request.form)
    deleteform = DeleteAccountForm(request.form)
    title = "{}'s account settings".format(user.name)

    if request.method == "POST" and form.validate():
        if form.old_password.data == user.password:
            flash("Your password has been reset.")
            user.password = form.new_password.data
            db.session.commit()
            password_reset_email(user)
            return redirect(url_for("user"))
        else:
            flash("Your old password was incorrect. Please try again.")
            return redirect(url_for("settings"))

    elif request.method == "POST" and not form.validate():
        flash("Something went wrong; please try again.")
        return redirect(url_for("settings"))

    else:
        return render_template(
            "settings.html", title=title, loggedin_user=loggedin_user, user=user, form=form, deleteform=deleteform
        )
コード例 #10
0
ファイル: views.py プロジェクト: kevana/ummbNet
def reset_pw():
    '''Route to reset a user's password.'''
    form = PasswordResetForm()
    if form.validate_on_submit():
        username = form.username.data
        user = User.query.filter_by(username=username).first()
        reset_password_start(user=user)
        return render_template('user/reset_password.html', sent=True, user=None)
    return render_template('user/reset_password.html', form=form, user=None)
コード例 #11
0
ファイル: views.py プロジェクト: ZyqGitHub1/raspberry_cloud
def password_reset(token):
	form = PasswordResetForm()
	if form.validate_on_submit():
		user = User.query.filter_by(email=form.email.data).first()
		if user is None:
			flash('The eamil was not found.')
		if user.reset_password(token, form.password.data):
			flash('Your password has been updated.')
		return render_template('auth/trans.html')
	return render_template('auth/reset_password.html', form=form)
コード例 #12
0
ファイル: views.py プロジェクト: zhangyage/mytest
def password_reset(token):
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetForm()
    if form.validate_on_submit():
        if User.reset_password(token, form.password.data):
            db.session.commit()
            flash('Your password has been updated.')
            return redirect(url_for('auth.login'))
        else:
            return redirect(url_for('main.index'))
    return render_template('auth/reset_password.html', form=form)
コード例 #13
0
ファイル: views.py プロジェクト: danielthiel/FlaskFactoryBone
def password_reset():
    # import worker
    if g.user is not None and g.user.is_authenticated():
        return redirect(request.args.get('next') or url_for('index'))
    form = PasswordResetForm()
    if form.validate_on_submit():
        user = form.get_user()
        if user:
            flash(u'Aktuell kann kein Passwort zuruckgesetzt werden.')
            # worker.reset_password_for_user(user)
        else:
            flash(u'Diese Email konnte im System nicht gefunden werden.')
    return render_template('user/pwreset.html', form=form)
コード例 #14
0
def password_reset(token):
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user.reset_password(token, form.new_password.data):
            flash('your password has been updated')
            return redirect(url_for('auth.login'))
        else:
            flash('invalid token')
            return redirect(url_for('main.index'))
    return render_template('auth/reset_password.html', form=form)
コード例 #15
0
def password_reset(token):
    form = PasswordResetForm()
    if form.validate_on_submit():
        user = UserDB.query.filter_by(email=form.email.data).first()
        if user is None:
            return redirect(url_for('index'))
        else:
            user.pwdhash = generate_password_hash(request.form['password'])
            db.session.commit()
            flash('Your password has been updated.')
            return redirect(url_for('login'))

    return render_template('password_reset.html', form=form)
コード例 #16
0
ファイル: views.py プロジェクト: nikhila05/pietrack
def password_reset(request, to_email):
    from_email = '*****@*****.**'
    to_email_dict = {'email': to_email}
    token_generator = default_token_generator
    email_template_name = 'email/reset_email.html'
    subject_template_name = 'email/reset_subject.txt'
    form = PasswordResetForm(to_email_dict)
    if form.is_valid():
        opts = {
            'use_https': request.is_secure(),
            'from_email': from_email,
            'email_template_name': email_template_name,
            'subject_template_name': subject_template_name,
            'request': request}
        form.save(**opts)
コード例 #17
0
ファイル: win_views.py プロジェクト: NobodyWHU/QianXun-1
def window_password_reset(request):
    window_password_form = PasswordResetForm(request.POST)
    if window_password_form.is_valid():
        window_password_dict = window_password_form.cleaned_data
        try:
            window_model = window.get_by_username(window_password_dict)  # verify user's authority
            window.update_password(window_model, window_password_dict)
            verify_code_model = request.verify_code_meta['verify_code_model']
            verify_code_model.delete()
            return json_response_from_object(OK, CODE_MESSAGE.get(OK))
        except ObjectDoesNotExist:
            verify_code_model = request.verify_code_meta['verify_code_model']
            verify_code_model.delete()
            return json_response(USER_NOT_EXIST, CODE_MESSAGE.get(USER_NOT_EXIST))
    else:
        return json_response(PARAM_REQUIRED, window_password_form.errors)
コード例 #18
0
ファイル: main.py プロジェクト: WycliffeMuchumi/Techome
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    user = User.verify_reset_token(token)
    if user is None:
        flash('That token is invalid or expired', 'warning')
        return redirect(url_for('reset_request'))
    form = PasswordResetForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
        user.password = hashed_password
        # commiting changes made to the user's password
        db.session.commit()
        flash('Your password has been reset successfully,You can now login to your account!', 'success')
        return redirect(url_for('login'))
    return render_template('reset_token.html', title='Reset Password', form=form)
コード例 #19
0
def account():
    args["title"] = "My Account"
    args["reset_form"] = PasswordResetForm()
    if args["reset_form"].validate_on_submit():
        username = session["user"]
        old_pwd = args["reset_form"].old_password.data
        if UserController.validate_pwd(username, old_pwd):
            new_pwd = args["reset_form"].new_password.data
            if UserController.reset_pwd(username, new_pwd):
                flash(
                    "Your password has been changed Successfully! Please login again to continue.",
                    "success")
                UserController.end_user_session()
                return redirect(url_for("login"))
            new_pwd = None
            flash(
                "An error occurred while resetting your password! Please try again.",
                "danger")
            return redirect(url_for("account"))
        old_pwd = None
        flash(
            "Your old password does not match our records. Please try again.",
            "danger")
        return redirect(url_for("account"))
    return display_page('account')
コード例 #20
0
ファイル: views.py プロジェクト: SeongUkYun/tokansyo
    def get_context_data(self, **kwargs):
        context = super(MemberEditView, self).get_context_data(**kwargs)
        member = Member.objects.get(auth_user=self.request.user)
        context['member'] = member
        context['form'] = MemberForm(instance=member)
        context['reset_form'] = PasswordResetForm()

        return context
コード例 #21
0
def password_reset(request, uid, token):
    user = User.objects.get(id=urlsafe_base64_decode(uid))

    if request.method == "POST":
        form = PasswordResetForm(request.POST)

        if form.is_valid() and default_token_generator.check_token(
                user, token):
            cd = form.cleaned_data
            user.set_password(cd['password1'])
            user.save()

            url = reverse('login')
            message = 'You have changed your password. You can sign in with your new password now.'
            return success(request, url, message)

        else:
            form.errors['__all__'] = form.error_class(
                ['Invalid or expired token.'])

    else:
        form = PasswordResetForm()

    return render(request, 'password_reset_form.html', {
        'form': form,
        'user': user,
    })
コード例 #22
0
ファイル: views.py プロジェクト: allevitan/olinbartering
def resetPassword(request):
	if request.method == 'POST':
		form = PasswordResetForm(request.POST)
		if form.is_valid():
			cleaned_data = form.clean()
			email = cleaned_data['emailAddress']
			user = User.objects.get(email = email)
			newpassword = generate_password(12)
			user.set_password(newpassword)
			user.save()
			subject = "Password Reset"
			message = "New Password: " + newpassword
			send_mail(subject, message, '*****@*****.**', [email], fail_silently=False)
			return HttpResponseRedirect('successful/')
	else:
		form = PasswordResetForm()
	
	return render(request, 'resetPassword.html', {'form': form})
コード例 #23
0
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    user = User.verify_reset_token(token)
    if user is None:
        flash('That is an invalid or expired token', 'warning')
        return redirect(url_for('reset_request'))
    form = PasswordResetForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user.password = hashed_password
        db.session.commit()
        flash('Your password has been updated, please login', 'success')
        return redirect(url_for('login'))
    return render_template('admin/reset_token.html',
                           title='Reset Password',
                           form=form)
コード例 #24
0
ファイル: routes.py プロジェクト: TechQuity/milk2
def passwordreset():
  form = PasswordResetForm()

   
  if request.method == 'POST':
    if form.validate() == False:
      return render_template('passwordreset.html', form=form)
    else:   
      test = User.query.filter_by(Members_Email = form.Members_Email.data).first()
      test.Members_Passhash = update_password(form.Members_Password.data)
      usertempdelete = UserReset.query.filter_by(Members_Email = form.Members_Email.data).first()
      db.session.add(test)
      db.session.delete(usertempdelete)
      db.session.commit()
      return redirect(url_for('profile'))
                 
  elif request.method == 'GET':
    return render_template('passwordreset.html', form=form)  
コード例 #25
0
def entity_add_user(request, entity_id):
    entity = get_object_or_404(Entity, pk=entity_id)
    if request.POST:
        form = AddUserForm(request.POST)
        if form.is_valid():
            #Lookup or create user, add to entity
            email = form.cleaned_data['email']
            form.cleaned_data['username'] = email[:30]
            del form.cleaned_data['email']
            user, created = User.objects.get_or_create(email=email, defaults=form.cleaned_data)
            if created:
                reset_form = PasswordResetForm({'email':user.email})
                reset_form.is_valid()
                reset_form.save(email_template_name="registration/new_account.html", subject=_("Account created on %s"))
            assign('change_entity', user, entity)
            return HttpResponseRedirect(reverse('show_user',args=[user.pk]))
    else:
        form = AddUserForm()
    return render_to_response('scorecard_processor/entity/add_user.html', {'object':entity,'form':form}, RequestContext(request))
コード例 #26
0
ファイル: views.py プロジェクト: crmtoolboxgit/nxtlvl
def password_reset(request):
	"""
	Password reset view
	"""
	if request.method=="POST":
		form = PasswordResetForm(request.POST)
		if form.is_valid():
			form.save()
			return HttpResponseRedirect('/password_reset_done/')
	else:
		form = PasswordResetForm()
	return TemplateResponse(
		request,
		'reset.html',
		{
			'form': form,
			'next': '/password_reset_done/'
		}
		)
コード例 #27
0
def forgot_password():
    form = PasswordResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        try:
            if user:
                # when both password are same
                if form.new_password.data == form.confirm_password.data:
                    hash_password = generate_password_hash(
                        form.confirm_password.data, method='sha256')
                    user.password = hash_password
                    db.session.commit()
                    flash("Password reset sucessfully!.")
                    # return '<h1>'+ 'Password is reset' +'</h1>'
                else:
                    flash("Password not match!.")
        except Exception as e:
            flash("There is no user for this Email.")

    return render_template("forgot_password.html", form=form)
コード例 #28
0
ファイル: views.py プロジェクト: mingyuec/Grumblr
def reset_password_form(request, uidb64, token):
    context = {'validlink': False}
    try:
        # decode the uid in the url
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user and default_token_generator.check_token(user, token):
        context['validlink'] = True
    if request.method == 'GET':
        if context['validlink'] == False:
            return render(request,
                          'grumblr/password_reset/password_reset_form.html',
                          context)
        # if there is no exception and the token is the same as we calculated, render password reset form
        context['form'] = PasswordResetForm()
        # context['form'] = PasswordResetForm(initial={'username':user.username})
        return render(request,
                      'grumblr/password_reset/password_reset_form.html',
                      context)
    # if user post their new passwords

    form = PasswordResetForm(request.POST)
    # form.fields["username"].initial = user.username
    context['form'] = form

    # Validates the form.
    if not form.is_valid():
        return render(request,
                      'grumblr/password_reset/password_reset_form.html',
                      context)
    # reset password
    user.set_password(form.cleaned_data['new_password'])
    # set the user to be active
    user.is_active = True
    # save it
    user.save()
    return render(request,
                  'grumblr/password_reset/password_reset_complete.html')
コード例 #29
0
def profile_password(request):
    customer = Customer.objects.get(user=request.user)
    if request.method == 'POST':
        form = PasswordResetForm(request.POST)
        if not form.is_valid():
            return render(request, 'info_profile_password.html', {
                'customer': customer,
                'form': form
            })
        old_password = form.cleaned_data.get('old_password')
        user = customer.user
        if not check_password(old_password, user.password,
                              preferred='default'):
            form.add_error('old_password',
                           'password doesn\'t match with previous password')
            return render(request, 'info_profile_password.html', {
                'customer': customer,
                'form': form
            })
        password = form.cleaned_data.get('password')
        user.password = make_password(password)
        user.save()
        customer.save()
    return render(request, 'info_profile_password.html', {
        'customer': customer,
        'form': PasswordResetForm()
    })
コード例 #30
0
def reset_password(token):
    form = PasswordResetForm()
    if form.validate_on_submit():
        payload = {'token': form.token.data, 'password': form.password.data}
        response = post(env('API_DRF_HOST') + '/reset_password/', data=payload)
        if response.status_code == 200:
            data = json.loads(response.text)
            session['email'] = data['email']
            session['auth_token'] = data['auth_token']
            flash('Password reset successful!')
            return redirect(url_for('index'))
        else:
            flash('Password reset failed. Please try again.')
            return redirect(url_for('request_password_reset'))

    if token:
        response = get(env('API_DRF_HOST') + '/reset_password/' + token)
        if response.status_code == 200:
            form = PasswordResetForm(token=token)
            return render_template('reset_password.html', form=form)
    flash('Password reset failed. Please try again.')
    return redirect(url_for('request_reset_password'))
コード例 #31
0
def reset(token):
    email = None
    try:
        s = get_url_serializer(current_app)
        email = s.loads(token, salt='recovery-key')
    except:
        abort(404)

    form = PasswordResetForm()

    if form.validate_on_submit():
        user = User.query.filter_by(email=email).first_or_404()
        user.update_password(form.password.data)
        try:
            commit(db.session)
        except:
            send_error_email()
            flash('There has been an error')
            return redirect(url_for('auth.forgot_password'))
        flash('Password updated')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset.html', form=form)
コード例 #32
0
ファイル: views.py プロジェクト: hnassif/scrollege
def reset_password(request):
    feedback = {'status':None, 'data':None}
    if request.method == 'POST':
        print(request.POST)
        form = PasswordResetForm(request.POST)
        if form.is_valid():
            old_Password=form.cleaned_data['old_password']
            new_Password=form.cleaned_data['new_password']
            confirm_New_Password=form.cleaned_data['confirm_new_password']
            if (new_Password == confirm_New_Password) and request.user.check_password(old_Password):
                request.user.set_password(new_Password)
                request.user.save()
                feedback['status']='OK'
                feedback['data']="Password has been reset successfully."
            else:
                feedback['status']='FAIL'
                feedback['data']="An Error occurred. Password change unsuccessful."
        else:
            feedback['status']='FAIL'
            feedback['data']="An Error occurred. Password change unsuccessful."
            feedback['form'] = 'invalid'

    return HttpResponse(json.dumps(feedback),content_type="application/json")
コード例 #33
0
def auth_reset_password(request, template='auth/reset.html'):
    ''' View to allow users to reset their password.  This view takes a GET/POST variable
        of a UUID which was previously e-mailed to the User requesting a password reset.  
        If the UUID is valid, then display a PasswordResetForm allowing them to select
        a new password ''' 
    from forms import PasswordResetForm
    from atrinsic.base.models import User
    from atrinsic.util.backend import UserBackend
    from django.contrib.auth.models import AnonymousUser
    
    reset_auth = request.REQUEST.get('reset_auth', None)
    reset = get_object_or_404(UserPasswordReset, reset=reset_auth)

    if request.method == 'POST':
        form = PasswordResetForm(request.POST)

        if form.is_valid():
            reset.user.set_password(form.cleaned_data['password'])
            reset.user.save()

            user = authenticate(email=reset.user.email, password=form.cleaned_data['password'])
            if user:    
                login(request, user)
    
                if request.session.get("organization_id", None):
                    del request.session["organization_id"]
                    
                reset.delete()
                return HttpResponseRedirect(reverse('auth_choice'))
                
    else:
        form = PasswordResetForm()

    return render_to_response(template, {
                'form' : form,
                'reset_auth' : reset_auth,
           }, context_instance = RequestContext(request))
コード例 #34
0
ファイル: app.py プロジェクト: adt123/metpetdb_interface
def reset_password(token):
    form = PasswordResetForm()
    if form.validate_on_submit():
        payload = {'token': form.token.data,
                   'password': form.password.data}
        response = post(env('API_HOST') + '/reset-password/', data=payload)
        if response.status_code == 200:
            data = json.loads(response.text)
            session['email'] = data['email']
            session['api_key'] = data['api_key']
            flash('Password reset successful!')
            return redirect(url_for('search'))
        else:
            flash('Password reset failed. Please try again.')
            return redirect(url_for('request_reset_password'))

    if token:
        response = get(env('API_HOST') + '/reset-password/' + token)
        if response.status_code == 200:
            form = PasswordResetForm(token=token)
            return render_template('reset_password.html', form=form)

    flash('Password reset failed. Please try again.')
    return redirect(url_for('request_reset_password'))
コード例 #35
0
ファイル: views.py プロジェクト: rogeriofalcone/anaf
def password_reset(request, response_format='html'):
    "Password_reset sends the email with the new password"

    if request.POST:
        form = PasswordResetForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('password_reset_done'))
    else:
        form = PasswordResetForm()

    return render_to_response('core/password_reset_form',
                              {'form': form},
                              context_instance=RequestContext(request),
                              response_format=response_format)
コード例 #36
0
def password_reset(request):
    """
	Password reset view
	"""
    if request.method == "POST":
        form = PasswordResetForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/password_reset_done/')
    else:
        form = PasswordResetForm()
    return TemplateResponse(request, 'reset.html', {
        'form': form,
        'next': '/password_reset_done/'
    })
コード例 #37
0
ファイル: views.py プロジェクト: maungshine/school-app
def resetPassword(token, type):
    if current_user.is_authenticated:
        if current_user.type == 'admin':
            return redirect(url_for('main.index'))
        return redirect(url_for('student.studentIndex'))
    user = User.verify_reset_token(token)
    if user is None:
        flash('Invalid or expired token', 'warning')
        return redirect(url_for('main.pwResetRequest'))
    form = PasswordResetForm()
    if request.method == 'POST':
        if form.validate_on_submit:
            pw_hash = bcrypt.generate_password_hash(
                form.password.data).decode('utf-8')
            user.password = pw_hash
            db.session.commit()
            flash('Your account password has been updated.', 'success')
            if user.type == 'admin':
                return redirect(url_for('main.adminlogin'))
            return redirect(url_for('student.studentlogin'))
    return render_template('reset_password.html', form=form, type=type)
コード例 #38
0
ファイル: Eclectic.py プロジェクト: Cassandra-Fu/electic
def forget():
    form_reset = PasswordResetForm()
    form_forget = ForgetPasswordForm()
    if form_forget.validate_on_submit():
        user_email = form_forget.email.data
        user_list = dat_loader.load_data("Users")["data"]
        customer_list = []
        for x in user_list:
            if isinstance(x, Customer):
                customer_list.append(x)
        for x in customer_list:
            if x.email == user_email:
                p_token = Pass_token(x.get_id())
                m1 = Mail()
                m1.content = f"""
        <!DOCTYPE html>
        <html lang="en">
          <body>
            <pre>
              Dear {x.get_name()},
        
              You have requested to reset your password for your Eclectic account. Copy or paste the link below to your
              browser or click on the link to reset your password. The link will expire after 2 hours.
              <a href="{p_token.get_link()}">{p_token.get_link()}</a>
        
              Warmest regards,
              Eclectic Support Team
            </pre>
          </body>
        </html>
        """
                m1.subject = "Eclectic Password Reset Link"
                m1.send(x.email)
                new_list = dat_loader.load_data("Tokens")["data"]
                new_list.append(p_token)
                dat_loader.write_data("Tokens", new_list, False)
        return redirect("/login/")
    elif request.args.get("auth") is None and not is_authenticated(request):
        return render_template("home/forget_password.html", form=form_forget)
    elif form_reset.validate_on_submit():
        user_id = int(form_reset.id.data)
        new_pass = form_reset.password1.data
        confirm_pass = form_reset.password2.data
        if new_pass == confirm_pass:
            user_list = dat_loader.load_data("Users")["data"]
            for x in user_list:
                if x.get_id() == user_id:
                    x.Change_password(new_pass)
                    dat_loader.write_data("Users", user_list, False)
                    return redirect("/login/")
            auth_token = request.args.get("auth")
            token_list = dat_loader.load_data("Tokens")["data"]
            for x in token_list:
                trial = x.use(auth_token)
                if trial is None:
                    pass
                else:
                    form_reset.id.data = trial
                    dat_loader.write_data("Tokens", token_list, False)
        else:
            return abort(400)
    elif not is_authenticated(request):
        auth_token = request.args.get("auth")
        token_list = dat_loader.load_data("Tokens")["data"]
        for x in token_list:
            trial = x.use(auth_token)
            if trial is None:
                pass
            else:
                form_reset.id.data = trial
                return render_template("home/new_password.html",
                                       form=form_reset)
        return redirect("/login/")