Beispiel #1
0
def submit_login():
    """
    attempt to log in
    @return: requested page or home page
    """
    if request.form['submit'] == "Login":
        login_form = EmailPasswordForm(request.form)
        if login_form.validate_on_submit():
            registered_user = User.get(login_form.login_email.data)
            if registered_user is None or registered_user.password is None:
                flash('Username is invalid', 'error')
                return render_template('login.html',
                                       loginform=login_form,
                                       forgotpw=ForgotPasswordForm())
            if not registered_user.check_password(login_form.password.data):
                flash('Password is invalid', 'error')
                return render_template('login.html',
                                       loginform=login_form,
                                       forgotpw=ForgotPasswordForm())
            login_user(registered_user)
            return redirect(request.args.get('next') or url_for('index'))
        else:
            return render_template('login.html',
                                   loginform=login_form,
                                   forgotpw=ForgotPasswordForm())
Beispiel #2
0
def forgot(request): 
    """Sends a password reset link to a user's validated email address. If 
    the email address isn't validated, do nothing (?) 
    """
    # This doesn't make sense if the user is logged in
    if not request.user.is_anonymous():
        return HttpResponseRedirect('/')

    if request.method == 'POST': 
        User = get_user_model()
        
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            
            try: 
                user = User.objects.get(email=email, 
                                        userdata__email_verified=True)
                if getattr(user, 'social_auth', None) and user.social_auth.exists():
                    send_social_auth_provider_login_email(request, user)
                else:
                    send_password_reset_email(request, user)
                    
            except User.DoesNotExist:
                pass
            
            return render(request, 'accounts/forgot/wait_for_email.html')
    else:
        form = ForgotPasswordForm()

    c = {
        'form': form,
    }
    return render(request, 'accounts/forgot/forgot.html', c)
Beispiel #3
0
def forgot_password():
    form = ForgotPasswordForm(request.form)
    if form.validate_on_submit():
        # generating a random token to send to the user email
        user_email = form.email.data
        try:
            print("here")
            user = User.query.filter_by(email=user_email).one()
            verification_code = verification_code = ''.join([ random.choice(
                                    string.ascii_uppercase +
                                    string.ascii_lowercase +
                                    string.digits) for _ in range(1,48) ])


            msg = Message('MSTS Password Reset',
                              sender="*****@*****.**",
                              recipients=[user_email],
                              )
            msg.html = render_template('users/forgot_password_email.html',verification_code = verification_code)
            try:
                mail.send(msg)
            except socket.error as e:
                print("Message not successfully sent")

        except MultipleResultsFound as e:
            pass
        except NoResultFound as e:
            pass


        flash("If this email address has a registered account, we have sent an email with instructions on how to recover your account.","alert-success")
    print(form.errors)
    return render_template('users/forgot_password.html',form=form)
Beispiel #4
0
def forgotPassword():
    form = ForgotPasswordForm()
    if form.validate_on_submit():
        connection = sqlite3.connect('data/site.db')
        cur = connection.cursor()
        for row in cur.execute("SELECT username, password from user_data"):
            if form.username.data == row[0]:
                flash(
                    "A new password has been sent to your email so you can reset your password !"
                )
                resetPassword = generateRandomPassword()
                salt = bcrypt.gensalt()
                newResetPassword = bcrypt.hashpw(resetPassword.encode(), salt)
                username = form.username.data
                cur.execute("Update user_data set password=? where username=?",
                            (newResetPassword, username))
                connection.commit()
                cur.close()
                msg = Message('Forgot Password from Jean-Francois Website',
                              recipients=[form.username.data])
                msg.body = "Your password has been reset. Your new password is now : " + resetPassword + "\nYou can change your password with it."
                mail.send(msg)
                return redirect('/login')
        flash("There is no account associated with that email. ")
        return redirect('/forgotPassword')
    return render_template('forgotPassword.html', form=form)
Beispiel #5
0
def reset_password(request):
    if request.method == 'POST':
        form = ForgotPasswordForm(request.POST)
        data = {'message': str(), 'error': str()}
        if form.is_valid():
            user = User.objects.filter(email=request.POST['email'])
            data['form'] = ForgotPasswordForm()
            if len(user) > 0:
                user = user[0]
                user.set_password(request.POST['password'])
                user.save()
                auth_user = authenticate(identification=request.POST['email'],
                                         password=request.POST['password'])
                if auth_user is not None:
                    login(request, auth_user)
                    return redirect('home')
                else:
                    data['error'] = 'Invalid login'
            else:
                data['error'] = 'Invalid user.'
        else:
            data['error'] = 'Passwords must match.'
        if data['error'] == str():
            del data['error']
        if data['message'] == str():
            del data['message']
        return render(request, 'forgot_password.jade', data)
    return render(request, 'forgot_password.jade', dict())
Beispiel #6
0
 def post(self):
     data = ImmutableMultiDict(request.json)
     forgot_password_form = ForgotPasswordForm(data, csrf_enabled=False)
     if forgot_password_form.validate():
         instance = User.query.filter(User.email == data['email']).first()
         forgot_password_form.send_mail(instance)
         return {"status": "success"}
     return forgot_password_form.errors
def forgot():
    form = ForgotPasswordForm(request.form)

    if request.method == "POST" and form.validate():
        s = Signer(app.config['SECRET_KEY'])
        token = s.sign(request.form['email'])

        send_password_reset(form.get_user(), token)
        return redirect('/forgot_confirmation')

    return render_template("forgot.html", form=form)
Beispiel #8
0
def forgot_password(request):
    """If the user forgot his password, he can have a new one."""

    if request.method == "POST":
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            data = form.data
            username = data["username"]
            usr = get_object_or_404(User, username=username)

            # Generate a valid token during one hour.

            uuid_token = str(uuid.uuid4())
            date_end = datetime.now() + timedelta(
                days=0, hours=1, minutes=0, seconds=0)
            token = TokenForgotPassword(user=usr,
                                        token=uuid_token,
                                        date_end=date_end)
            token.save()

            # send email
            subject = _(u"{} - Mot de passe oublié").format(
                settings.ZDS_APP['site']['abbr'])
            from_email = "{} <{}>".format(
                settings.ZDS_APP['site']['litteral_name'],
                settings.ZDS_APP['site']['email_noreply'])
            message_html = get_template(
                "email/forgot_password/confirm.html").render(
                    Context({
                        "username":
                        usr.username,
                        "url":
                        settings.ZDS_APP['site']['url'] +
                        token.get_absolute_url()
                    }))
            message_txt = get_template(
                "email/forgot_password/confirm.txt").render(
                    Context({
                        "username":
                        usr.username,
                        "url":
                        settings.ZDS_APP['site']['url'] +
                        token.get_absolute_url()
                    }))
            msg = EmailMultiAlternatives(subject, message_txt, from_email,
                                         [usr.email])
            msg.attach_alternative(message_html, "text/html")
            msg.send()
            return render_template("member/forgot_password/success.html")
        else:
            return render_template("member/forgot_password/index.html",
                                   {"form": form})
    form = ForgotPasswordForm()
    return render_template("member/forgot_password/index.html", {"form": form})
Beispiel #9
0
def forgot():
    form = ForgotPasswordForm(request.form)

    if request.method == "POST" and form.validate():
        s = Signer(app.config['SECRET_KEY'])
        token = s.sign(request.form['email'])

        send_password_reset(form.get_user(), token)
        return redirect('/forgot_confirmation')

    return render_template("forgot.html", form=form)
Beispiel #10
0
def forgot():
    form = ForgotPasswordForm()
    if form.validate_on_submit():
        try:
            user = User.get(User.email == form.email.data)
        except User.DoesNotExist:
            flash('No account with that email was found.')
            return redirect(url_for('forgot'))
        send_recovery_email(form.email.data)
        flash('A recovery link will be sent to your email.')
        return redirect(url_for('index'))
    else:
        return render_template('forgot.html', form=form)
Beispiel #11
0
def forgot_password_form():
    form = ForgotPasswordForm()
    if current_user.is_authenticated:  # Making sure the user is not logged in.
        return redirect(url_for('home'))
    if form.validate_on_submit():
        user = find_user(form.username.data)  # Checking if the user exists.
        if user:
            send_password_reset_email(user)
            flash(
                'Check your email for the instructions to reset your password!',
                'success')
            return redirect(url_for('password_reset_response'))
    return render_template("ForgotPassword.html", form=form)
Beispiel #12
0
def forgot_password(user):
    if current_user.is_authenticated:
        return redirect(url_for('main'))
    user_object = db.session.query(relations.User).filter_by(id=user).first()
    question = user_object.question
    password= ""
    form = ForgotPasswordForm()
    if form.validate_on_submit():
        if user and user_object.answer==form.answer.data:
            password= user_object.password
            return render_template('forgot_password.html', form=form, password=password, question=question)
        flash("Invalid Answer")
        return redirect(url_for('forgot_password', user=user))
    return render_template('forgot_password.html', form=form, password=password,  question=question)
Beispiel #13
0
def forgot_passwd():
    form = ForgotPasswordForm(request.form)
    if form.validate_on_submit():
        user = request.form['email']
        if User.query.filter_by(email=user).first():
            q = User.query.filter_by(email=user).first()
            forgot_password(user, q.password)
            return redirect(request.args.get("next") or url_for("login"))
        else:
            flash('Username not found')
            return redirect(request.args.get("next") or url_for("login"))
    return render_template("forgot_passwd.html",
        title="Forgot Password",
        form=form)
Beispiel #14
0
def forgot_passwd():
    form = ForgotPasswordForm(request.form)
    if form.validate_on_submit():
        user = request.form['email']
        if User.query.filter_by(email=user).first():
            q = User.query.filter_by(email=user).first()
            forgot_password(user, q.password)
            return redirect(request.args.get("next") or url_for("login"))
        else:
            flash('Username not found')
            return redirect(request.args.get("next") or url_for("login"))
    return render_template("forgot_passwd.html",
                           title="Forgot Password",
                           form=form)
Beispiel #15
0
def forgot_password(request):
    form = ForgotPasswordForm()
    if request.method == 'POST':
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            et = EmailTool()
            et.send([email], "your new password is:sss")
            messages.add_message(
                request, messages.SUCCESS,
                '%s:Your password has been emailed to you!' % username)
            return redirect('login')
    return render_to_response('forgot_password.html', {'form': form},
                              context_instance=RequestContext(request))
Beispiel #16
0
def forgot_password():
    form = ForgotPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        
        serialized_token = get_serialized_token(user, 'reset')
        send_reset_password_email(user, serialized_token)
        flash(msgs['SEND_RESET_EMAIL'])
        return redirect(url_for('.login'))
    
    for field in form.errors:
        flash('<strong>' + field.capitalize() + '</strong>' + ': ' + form.errors[field][0], 'error')
    
    login_link = '<p>Remembered your password? <a href="' + url_for('.login') + '">Click here to log in.</a></p>'
    return render_template('forgot_password.html', form=form, login=login_link)
Beispiel #17
0
def forgot():
    form = ForgotPasswordForm()
    if form.validate_on_submit() or request.method == 'POST':
        cursor = db.cursor()
        sql = """SELECT * FROM USER WHERE U_id = '%s' AND Email = '%s'""" \
              % (form.user_id.data, form.email.data)
        cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()

        # ID Chcek
        if len(result) is 1:
            session['forgot_user'] = form.user_id.data
            return redirect(url_for('reset'))

    return render_template('forgot.html', form=form)
Beispiel #18
0
def forgot_passwd():

	meta = Metaindex.query.order_by(Metaindex.id.desc()).first()
	form = ForgotPasswordForm(request.form)
	if form.validate_on_submit():
		user = request.form['email']
		if User.query.filter_by(email=user).first():
			q = User.query.filter_by(email=user).first()
			forgot_password(user, q.password)
			return redirect(request.args.get("next") or url_for("login"))
		else:
			flash('Usuario no enconstrado')
			return redirect(request.args.get("next") or url_for("login"))
	return render_template ("forgot_passwd.html",
		title="Recuperacion de contrase&ntide;a",
		form=form)
def forgot_passwd():
    form = ForgotPasswordForm(request.form)
    if form.validate_on_submit():
        user = request.form['email']
        if User.query.filter_by(email=user).first():
            q = User.query.filter_by(email=user).first()
            login_user(q)
            user = g.user
            # forgot_password(user, q.password)
            app.logger.debug('ready to change the password')
            return redirect(request.args.get("next") or url_for("new_pass"))
        else:
            flash('Username not found', 'error')
            # return redirect(request.args.get("next") or url_for("login"))
    return render_template("forgot_passwd.html",
                           title="Forgot Password",
                           form=form)
Beispiel #20
0
def forgot_password():
    forgot_form = ForgotPasswordForm(request.form)
    error = None
    if request.method == 'POST':
        if forgot_form.validate() and recaptcha_check(request.form["g-recaptcha-response"]):
            user = User.get(email=forgot_form.email.data)
            if user is not None:
                if user.forgot_password():
                    link = url_for("common_views.change_password", user_id=user.user_id, secret=user.forgot_secret, _external=True)
                    current_app.logger.info(link)
                    mail = mail_handler.Mail(user.email, link)
                    mail.send()
                    return redirect(url_for("common_views.index"))
            else:
                error = "A user with this email does not exist!"
        else:
            error = "Please enter email address and prove you are not a robot!"
    return render_template("forgot.html", forgot_form=forgot_form, error=error)
Beispiel #21
0
def forgot_password():
    form = ForgotPasswordForm()
    if form.validate_on_submit():
        #MySQL Integration
        cur = mysql.connection.cursor()
        result = cur.execute("SELECT password FROM users WHERE email = %s", [form.email.data])
        if result > 0:
            newPassword = str(uuid.uuid4())
            cur.execute("UPDATE users SET password = %s WHERE email = %s", (sha256_crypt.hash(str(newPassword)), form.email.data))
            mysql.connection.commit()
            msg = Message('Reset my codon.io password!', recipients = [form.email.data])
            msg.body = "Here is your new password: "******"We sent the required information to your email adress!", msg_type_to_color["success"])
        else:
            cur.close()
            flash("Email not found!", msg_type_to_color["error"])
    return render_template("forgot_password.html", form=form)
Beispiel #22
0
def forgot_password():
    """Forgot password"""

    form = ForgotPasswordForm()
    if form.validate_on_submit():
        user = User.query.get(form.email.data)
        if user is None:
            flash('Email does not exist')
        else:

            temp_password = str(uuid.uuid4())[:8]
            user.password = bcrypt.generate_password_hash(temp_password)
            db.session.add(user)
            db.session.commit()

            send_forgot_password_email(user, temp_password)

            return redirect(url_for("index"))

    return render_template("forgot_password.html", form=form)
Beispiel #23
0
def forgot_password():
    form = ForgotPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            s = get_url_serializer(current_app)
            token = s.dumps(user.email, salt='recovery-key')
            context = {
                'first_name': user.first_name,
                'token': token
            }
            print(url_for('auth.reset', token=token, _external=True))
            send_email(
                recipients=[user.email],
                subject='Password Reset',
                template_name='password_reset',
                **context
            )
        flash('Email with link to reset password has been sent')
        return redirect(url_for('auth.login'))
    return render_template('auth/forgot_password.html', form=form)
Beispiel #24
0
def forgotPassword(request):
    messages = []
    if request.method == 'POST':
        
        forgotPasswordForm = ForgotPasswordForm(request.POST)
        if forgotPasswordForm.is_valid():
            try:
                user= User.objects.get(username= forgotPasswordForm.cleaned_data['username'])
                print user 
                print user.email
                messages.append('user found, forgot password email to be sent')
#                send_mail('Subject here', 'Here is the message.', '*****@*****.**',
#                          ['*****@*****.**'], fail_silently=False)
                forgotPasswordForm = ForgotPasswordForm()
                return render(request,'ForgotPassword.html',{'forgotPasswordForm':forgotPasswordForm,'messages':messages})
            except User.DoesNotExist:
                messages.append('user not found')
                forgotPasswordForm = ForgotPasswordForm()
                return render(request,'ForgotPassword.html',{'forgotPasswordForm':forgotPasswordForm,'messages':messages})

        else:
            messages.append('invalid form')
            forgotPasswordForm = ForgotPasswordForm()
            return render(request,'ForgotPassword.html',{'forgotPasswordForm':forgotPasswordForm,'messages':messages})
            
    else: 
        forgotPasswordForm = ForgotPasswordForm()
        return render(request, 'ForgotPassword.html', {'forgotPasswordForm':forgotPasswordForm,'messages':messages})
Beispiel #25
0
def forgot_password():
    forgot_form = ForgotPasswordForm(request.form)
    error = None
    if request.method == 'POST':
        if forgot_form.validate() and recaptcha_check(
                request.form["g-recaptcha-response"]):
            user = User.get(email=forgot_form.email.data)
            if user is not None:
                if user.forgot_password():
                    link = url_for("common_views.change_password",
                                   user_id=user.user_id,
                                   secret=user.forgot_secret,
                                   _external=True)
                    current_app.logger.info(link)
                    mail = mail_handler.Mail(user.email, link)
                    mail.send()
                    return redirect(url_for("common_views.index"))
            else:
                error = "A user with this email does not exist!"
        else:
            error = "Please enter email address and prove you are not a robot!"
    return render_template("forgot.html", forgot_form=forgot_form, error=error)
Beispiel #26
0
def reset():
    """
    send reset password email to specified user email
    @return: refreshed page indicating success or failure
    """
    form = ForgotPasswordForm()
    if form.validate_on_submit():
        user = User.get(form.forgot_email.data)
        subject = "Password reset requested"
        token = ts.dumps(user.id, salt='recover-key')
        recover_url = url_for('reset_with_token', token=token, _external=True)
        html = render_template('recover.html', recover_url=recover_url)
        msg = Message(subject,
                      sender=config.MAIL_USERNAME,
                      recipients=[user.id])
        msg.body = html
        mail.send(msg)
        flash('Password reset email sent to ' + user.id)
        return redirect(url_for('login'))
    return render_template('login.html',
                           loginform=EmailPasswordForm(),
                           forgotpw=ForgotPasswordForm())
Beispiel #27
0
def forgot_password():
    if current_user.is_authenticated:
        return render_view(url_for('latest'),
                           redirect=True,
                           message=_('SESSIONS_MSG_ALREADY_SIGNED_IN'))

    form = ForgotPasswordForm()

    if form.is_submitted():
        try:
            if not form.validate():
                raise Exception(_('ERROR_INVALID_SUBMISSION'))

            if not verify_captcha():
                raise Exception(_('SESSIONS_ERROR_UNFINISHED_CHALLENGE_LBL'))

            email = form.email.data

            user = User.find_by_email(email)

            if not user:
                raise Exception(_('SESSIONS_ERROR_MAIL_NOT_FOUND',
                                  email=email))

            user.generate_reset_password()

            flash(_('SESSIONS_PASSWORD_RESET', email=email))

            # send reset password email
            send_email('reset_password', user)

            return render_view(url_for('sessions.forgot_password'),
                               redirect=True)

        except Exception as e:
            flash(e.message, 'error')

    return render_view('admin/sessions/forgot_password.html', form=form)
Beispiel #28
0
def forgot_password(request):
    ''' if the user forgot their password
    renders ForgotPasswordForm, or processes it if a POST request
    '''
    if request.method == 'POST':
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            # Does the user in the email field even exist?
            try:
                user = User.objects.get(username=data['username'])
                profile = UserProfile.objects.get(user=user)
            except User.DoesNotExist:
                return HttpResponseRedirect(reverse('main_page'))
            # Ok, they do. Send them an email
            reset_string = random_string()
            profile.password_reset_stub = reset_string
            profile.save()
            reset_link = '%s%s?rid=%s&uid=%s' % (_hostname(),
                                                 reverse('reset_password'),
                                                 reset_string, str(profile.id))
            email_body = render_message(
                'mongologin/static/emails/forgot_password.txt', locals())

            send_email(email_to=user.username,
                       email_body=email_body,
                       email_subject="Reset your password")
            messages.add_message(
                request, messages.SUCCESS,
                "An email has been sent to you with instructions on resetting your password."
            )
            return HttpResponseRedirect(reverse('main_page'))
    else:
        form = ForgotPasswordForm()

    return render_to_response('forgot_password.html',
                              locals(),
                              context_instance=RequestContext(request))
Beispiel #29
0
def forgot_password( request ):
    ''' if the user forgot their password
    renders ForgotPasswordForm, or processes it if a POST request
    '''
    if request.method == 'POST':
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            # Does the user in the email field even exist?
            try:
                user = User.objects.get(username=data['username'])
                profile = UserProfile.objects.get(user=user)
            except User.DoesNotExist:
                return HttpResponseRedirect( reverse('main_page') )
            # Ok, they do. Send them an email
            reset_string = random_string()
            profile.password_reset_stub = reset_string
            profile.save()
            reset_link = '%s%s?rid=%s&uid=%s'%(
                    _hostname(),
                    reverse( 'reset_password' ),
                    reset_string,
                    str(profile.id)
            )
            email_body = render_message(
                'mongologin/static/emails/forgot_password.txt',
                locals()
            )

            send_email( email_to=user.username, email_body=email_body, email_subject="Reset your password" )
            messages.add_message( request, messages.SUCCESS, "An email has been sent to you with instructions on resetting your password." )
            return HttpResponseRedirect( reverse('main_page') )
    else:
        form = ForgotPasswordForm()

    return render_to_response( 'forgot_password.html',
                               locals(),
                               context_instance=RequestContext(request) )
Beispiel #30
0
def forgot_password(request):
    """If the user forgot his password, he can have a new one."""

    if request.method == "POST":
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            data = form.data
            username = data["username"]
            usr = get_object_or_404(User, username=username)

            # Generate a valid token during one hour.

            uuidToken = str(uuid.uuid4())
            date_end = datetime.now() + timedelta(days=0, hours=1, minutes=0,
                                                  seconds=0)
            token = TokenForgotPassword(user=usr, token=uuidToken,
                                        date_end=date_end)
            token.save()

            # send email

            subject = "ZDS - Mot de passe oublié"
            from_email = "Zeste de Savoir <{0}>".format(settings.MAIL_NOREPLY)
            message_html = get_template("email/forgot_password/confirm.html").render(Context(
                {"username": usr.username, "url": settings.SITE_URL + token.get_absolute_url()}))
            message_txt = get_template("email/forgot_password/confirm.txt") .render(Context(
                {"username": usr.username, "url": settings.SITE_URL + token.get_absolute_url()}))
            msg = EmailMultiAlternatives(subject, message_txt, from_email,
                                         [usr.email])
            msg.attach_alternative(message_html, "text/html")
            msg.send()
            return render_template("member/forgot_password/success.html")
        else:
            return render_template("member/forgot_password/index.html",
                                   {"form": form})
    form = ForgotPasswordForm()
    return render_template("member/forgot_password/index.html", {"form": form})
Beispiel #31
0
def forgot_password(request):
    FORM_TITLE = _('Password Recovery')
    main = get_renderer(BASE_TEMPLATE).implementation()
    localizer = get_localizer(request)
    forgot_password_form = ForgotPasswordForm.get_form(localizer)

    if request.method == 'POST':
        if 'btn_cancel' in request.POST:
            return HTTPFound(location=request.route_path('users.login'))

        controls = request.POST.items()
        try:
            appstruct = forgot_password_form.validate(controls)
        except deform.ValidationFailure, e:
            return {'content':e.render(),
                    'main':main,
                    'general_stuff':{'form_title':FORM_TITLE},
                    'user':get_logged_user(request),
                    }

        del(appstruct['__LOCALE__'])
        try:
            user = request.rel_db_session.query(users.User).filter_by(username=appstruct['username']).one()
        except NoResultFound:
            request.session.flash(_("Username doesn't exist."))
            return {'content':forgot_password_form.render(appstruct),
                    'main':main,
                    'general_stuff':{'form_title':FORM_TITLE},
                    'user':get_logged_user(request),
                    }

        account = users.AccountRecovery(user)
        request.rel_db_session.add(account)

        try:
            request.rel_db_session.commit()
        except:
            request.rel_db_session.rollback()
            request.session.flash(_('Problems occured when trying to redefine the user password. Please try again.'))
            return {'content':forgot_password_form.render(appstruct),
                    'main':main,
                    'general_stuff':{'form_title':FORM_TITLE},
                    'user':get_logged_user(request),
                    }
        else:
            AccountRecoveryManager.send_recovery_mail(user, request)

        request.session.flash(_('You will receive an email with instructions on how to reset your account password.'))
        return HTTPFound(location=request.route_path('users.forgot_password'))
Beispiel #32
0
def reset_password():
    form = ForgotPasswordForm()

    try:
        user = User.query.filter_by(email=form.email.data)[-1]
        pwd = md5(str(datetime.now()) + form.email.data).hexdigest()[0:5]
        user.password = sha512(pwd)
        db.session.commit()

        email_tp = render_template('user/mail/forgot.html',
                                   user=user.serialize(),
                                   new_pwd=pwd)
        send_mail("Forgot Password", [user.email], email_tp)
        flash(dictionary()["new_password_sent"], "success")
    except:
        flash(dictionary()["couldnt_find_user"], "danger")
        return render_template("user/forgot_password.html", form=form)

    return redirect(url_for('user.reset_password'))
Beispiel #33
0
def forgot_password():
    form = ForgotPasswordForm()
    if request.method == 'GET':
        return render_template('forgot_password.html', form=form)
    if request.method == 'POST':
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None:
            temppass = ''.join(
                random.choice(string.ascii_uppercase + string.digits)
                for _ in range(24))
            user.pwdhash = generate_password_hash(temppass)
            db.session.commit()
            msg = Message('ArchHacks - Password Reset',
                          sender='*****@*****.**',
                          recipients=[form.email.data])
            msg.body = "Your temporary ArchHacks password is: archhacksrulez."
            msg.html = "<p>Your temporary ArchHacks password is: " + temppass + "</p><p>Go to <a href='http://archhacks.io/signin'>ArchHacks App Signin</a> to log in.</p>"
            mail.send(msg)
        return render_template('forgot_password.html', email=form.email.data)
Beispiel #34
0
def reset_password():
    form = ForgotPasswordForm()

    try:
        user = User.query.filter_by(email=form.email.data)[-1]
        pwd = md5(str(datetime.now()) + form.email.data).hexdigest()[0:5]
        user.password = sha512(pwd)
        db.session.commit()

        email_tp = render_template('account/mail/forgot.html',
                                   user=user.serialize(),
                                   new_pwd=pwd)
        send_mail("Forgot Password", [user.email], email_tp)
        flash("A new password has been sent to you! Please check you inbox!",
              "success")
    except Exception as e:
        flash("We couldnt find any user with the informed email address",
              "danger")

        return render_template("account/forgot_password.html", form=form)

    return redirect("account/signin")
Beispiel #35
0
def forgot_password():
    form = ForgotPasswordForm()
    return render_template('user/forgot_password.html', form=form)
Beispiel #36
0
def forgot_password(request, forgot_key=None):
    if request.method == 'POST':
        user = User.objects.filter(email=request.POST['email'])
        if len(user) > 0:
            email = user[0].email
            data = '{0}&{1}'.format(
                email,
                (datetime.datetime.now() +
                 datetime.timedelta(hours=24)).strftime('%d-%m-%Y %H:%M:%S'))
            sha = hashlib.sha256()
            sha.update(data)
            hash_key = base64.b64encode(sha.digest())
            forgot_key = obfuscate('{0}#{1}'.format(data, hash_key))
            if settings.DEBUG:
                message = 'http://localhost:8000/forgot_password/{0}/'.format(
                    forgot_key)
            else:
                message = 'http://www.equallo.com/forgot_password/{0}/'.format(
                    forgot_key)

            message_html = open(
                r'/home/equallo/eq/src/equ/equ/equ_common/static/files/forgot_password_email.html'
            ).read()
            #message_html = open(r'/home/nicolas/git/equ_project/equ_project/src/equ/equ/equ_common/static/files/forgot_password_email.html').read()

            message_html = message_html.replace('{{message}}', message)
            message_text = 'Forgot your password?\n\nPlease click the following link to set a new one.\n\n{0}'.format(
                message)
            send_email = EmailMultiAlternatives('Password reset', message_text,
                                                settings.DEFAULT_FROM_EMAIL,
                                                [email])
            send_email.attach_alternative(message_html, 'text/html')
            send_email.send(fail_silently=False)
        else:
            request.session['message'] = 'User not found'
    elif request.method == 'GET':
        try:
            link = deobfuscate(forgot_key)
            parts = link.split('#')
            sha = hashlib.sha256()
            sha.update(parts[0])
            hashing = base64.b64encode(sha.digest())
            if hashing == parts[1]:
                data = parts[0].split('&')
                if datetime.datetime.strptime(
                        data[1],
                        '%d-%m-%Y %H:%M:%S') >= datetime.datetime.now():
                    user = User.objects.filter(email=data[0])
                    if len(user) > 0:
                        form = ForgotPasswordForm(initial={'email': data[0]})
                        return render(request, 'forgot_password.jade',
                                      {'form': form})
                    else:
                        request.session[
                            'message'] = 'Key to reset password not valid.'
                else:
                    request.session[
                        'message'] = 'Expired password recovery link.'
            else:
                request.session[
                    'message'] = 'Corrupted password recovery link.'
        except Exception as e:
            request.session['message'] = 'Corrupted password recovery link.'
    return redirect('login')
Beispiel #37
0
def forgot_password(request):
    """Form for requesting a PasswordResetToken for a specified account.
    Accepts email or username. Keeps for each user at most one token at a time 
    in the database. Also, it saves FakeTokens to obfuscate an account's existence
    whilst at the same time forcing a 5 minutes gap between the sending of two
    tokens for the same account."""
    
    if request.user.is_authenticated():
        return not_logged_out_routine(request)
    
    if request.method == 'POST':
        
        form = ForgotPasswordForm(request.POST)
        if form.is_valid():
            
            identifier = form.cleaned_data['identifier']
            
            user = None # do we need this here? -- Probably.
            
            try:
                
                # Form input could be an email or a username
                if looks_like_email(identifier):
                    user = CustomUser.objects.get(email=identifier)
                else:
                    user = CustomUser.objects.get(username=identifier)
                
                # At this point, we do have a user object.
                
                try:
                    # Between sending two tokens for the same user, a certain period should pass (--> settings)
                    previous_token = PasswordResetToken.objects.get(user=user)
                    if previous_token.blocks_new():
                        messages.error(request, 'You need to wait between sending two tokens for the same account.')
                        return redirect('accounts:forgot_password')
                    
                    # Only one token per user in the database; and we are about to create a new one.
                    else:
                        previous_token.delete()

                except PasswordResetToken.DoesNotExist:
                    # Fair enough.
                    pass
                
                # Alright, create the new token and send it.

                token = PasswordResetToken(user=user)
                token.save()
                request.session['token_value'] = token.value

                # EXTEND: send email

            except CustomUser.DoesNotExist:
                # No such user, therefor no email or token. But we do want a FakeToken.
                # See models.FakeToken or the docstring here for explanation why we do this FakeToken thing.
                try:
                    # Clear all previous FakeTokens.
                    
                    # No difference between email or username here:
                    previous_token = FakeToken.objects.get(user_identifier=identifier)
                    if previous_token.blocks_new() == True:
                        messages.error(request, 'You need to wait between sending two tokens for the same account.')
                        return redirect('accounts:forgot_password')
                    else:
                        previous_token.delete()

                except FakeToken.DoesNotExist:
                    pass
                
                ft = FakeToken(user_identifier=identifier)
                ft.save()
                request.session['token_value'] = None
            
            # we want to tell the user whether he had stated a username or an
            # email address; and we want to tell him which of both he stated
            if looks_like_email(identifier):
                request.session['token_email'] = identifier
                request.session['token_username'] = None
            else:
                request.session['token_email'] = None
                request.session['token_username'] = identifier

            return redirect('accounts:token_sent')
    
    else:
        form = ForgotPasswordForm
    
    return render(request, 'accounts/forgot_password.html', {
        'form':form
    })
Beispiel #38
0
def auth_login(request, template='auth/login.html', next='/'):
    ''' View for the main user authentication system.  Display a LoginForm to
        validate credentials, and optionally accept a ForgotPasswordForm to
        allow users to reset their password.'''
    from forms import LoginForm,ForgotPasswordForm
    from atrinsic.base.models import User
    
    form = LoginForm()
    forgotform = ForgotPasswordForm()
    user = None
    error = None

    next = request.REQUEST.get('next',next)

    if request.method == "POST":
        form = LoginForm(request.POST)
        forgotform = ForgotPasswordForm(request.POST)
        forgot_email = request.POST.get('forgot_email', None)


        if forgotform.is_valid() and forgotform.cleaned_data['forgot_email'] is not None:
            u = User.objects.get(email=forgotform.cleaned_data['forgot_email'])
            reset_auth = uuid.uuid4()

            UserPasswordReset.objects.filter(user=u).delete()
            UserPasswordReset.objects.create(user=u, reset=reset_auth)

            send_mail('Password Reset', """\nHello, You have requested your password be reset.  To confirm your account and\n reset your password, please click on the link below:\n\n%s/accounts/reset?reset_auth=%s\n\n """ % (settings.SITE_URL, reset_auth), settings.SITE_CONTACT, [ u.email ], fail_silently=True)

            return render_to_response('auth/reset.html', {}, context_instance = RequestContext(request))

        elif form.is_valid():
            user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password'])

            if user is not None:
                if user.is_active:
                    login(request, user)
                    request.session["next"] = next
                    if request.session.get("organization_id",None):
                        del request.session["organization_id"]
                    return HttpResponseRedirect(reverse('auth_choice'))
                else:
                    error = "Account disabled"
            else:
                error = "Invalid Login"
        else:
            error = "Invalid Login"

    if request.GET.get("newhome",None)=="1":
        return render_to_response("notlogged/home.html",{
            'form':form,
            'error':error,
            'next' : next,
            'forgotform' : forgotform,
            }, context_instance=RequestContext(request))
    
    return render_to_response("auth/login2.html",{
    'form':form,
    'error':error,
    'next' : next,
    'forgotform' : forgotform,
    }, context_instance=RequestContext(request))
Beispiel #39
0
def forgot_password():
    form = ForgotPasswordForm()
    return render_template("account/forgot_password.html", form=form)
Beispiel #40
0
def login():
    """ load the login page """
    return render_template('login.html',
                           loginform=EmailPasswordForm(),
                           forgotpw=ForgotPasswordForm())
Beispiel #41
0
def forgot_password(request):
	FORGOT_PASSWORD_TEMPLATE = "core/forgot_password.html"
	
	if request.method == "GET":
		next_page = request.GET.get("next", "")
	else:
		next_page = ""
	
	if request.method != "POST":
		forgot_password_form = ForgotPasswordForm()
	else:
		forgot_password_form = ForgotPasswordForm(request.POST)
	
	if forgot_password_form.is_valid():
		username_or_email = forgot_password_form.cleaned_data["username_or_email"]
		
		try:
			if username_or_email.count("@") > 0:
				username = ""
				email = username_or_email
				user = User.objects.get(email=username_or_email)
			else:
				username = username_or_email
				email = ""
				user = User.objects.get(username=username_or_email)
		except:
			# No username could be found.
			return render_to_response(FORGOT_PASSWORD_TEMPLATE, {
				"not_found": True,
				"form": forgot_password_form,
				"next": next_page,
				"username": username,
				"email": email
			})
		
		username = user.username
		email = user.email
		
		# Username/email could be found (success).
		
		# Reset the password.
		new_random_password = UserManager().make_random_password()
		user.set_password(new_random_password)
		user.save()
		
		# Load a template for the message body and render it (to a string).
		email_body_template = loader.get_template("core/password_reset.html")
		template_context = Context({
			"first_name": user.first_name,
			"last_name": user.last_name,
			"username": user.username,
			"password": new_random_password,
			"login_url": "http://localhost:8000/login/"
		})
		
		# Email the user with the new password.
		user.email_user("EpiC Account Password Reset", email_body_template.render(template_context))
		
		# Display the page confirming to the user that their password was reset.
		return render_to_response(FORGOT_PASSWORD_TEMPLATE, {
			"username": username,
			"email": email,
			"next": next_page
		})
	
	# No GET or POST data, so display the form (for the first time).
	return render_to_response(FORGOT_PASSWORD_TEMPLATE, {
		"form": forgot_password_form,
		"next": next_page
	})