示例#1
0
def forgot_password(request):
    session = DBSession()
    matchdict = request.matchdict

    if (request.logged_in):
        request.session.flash(_("You are already logged in and therefore cannot request a new password."))
        return HTTPFound(location = route_url("home", request))

    login_url = route_url('login', request)
    referrer = request.url
    if (referrer == login_url):
        referrer = '/' # never use the login form itself as came_from
    
    came_from = request.params.get('came_from', referrer)

    fs = None

    if 'submitted' in request.params:
        fs = ForgotPasswordFieldSet().bind(User, session = session, data = request.params or None)
        valid_user = User.checkEmail(fs.username.value, fs.email.value)

        if (not valid_user):
            request.session.flash(_("E-mail and password combination do not match."))
            return HTTPFound(location = route_url("home", request))

        #user = User.getByEmail(fs.email.value)

        token = str(time.time())

        # Generate salt
        for x in xrange(0, 10):
            token += str(random.randint(0, 100))
        token = hashlib.sha256(token).hexdigest()

        fp = ForgotPassword(token = token)
        fp.user_id = valid_user.id
        session.add(fp)

        valid_user.user_type = User.FORGOT_PASSWORD
        session.add(valid_user)

        # Import smtplib for the actual sending function
        import smtplib
        
        # Import the email modules we'll need
        from email.mime.text import MIMEText

        text = """Please go to the following link to reset your password:

http://fluidnexus.net/reset_password/%s

If you have any questions please reply to this e-mail.

Best,

fluidnexus.net""" % token
        msg = MIMEText(text)
        msg["Subject"] = "Forgotten password for %s" % (fs.email.value)
        msg["From"] = "*****@*****.**"
        msg["To"] = fs.email.value
        s = smtplib.SMTP("localhost")
        s.sendmail("*****@*****.**", [fs.email.value], msg.as_string())
        s.quit()

        request.session.flash(_("Please check your e-mail for the link to reset your password."))
        return HTTPFound(location = route_url("home", request))

    if (fs is None):
        fs = ForgotPasswordFieldSet().bind(User, session = session)
    form = fs.render()
    return dict(form = form, title = _("Forgot your password?"))