示例#1
0
def reset_password(request):
    session = DBSession()
    matchdict = request.matchdict
    token = matchdict["token"]

    forgotPassword = ForgotPassword.getByToken(token)
    if (not forgotPassword):
        request.session.flash(_("Reset password token not found in database."))
        return HTTPFound(location = route_url("home", request))

    if (request.logged_in):
        request.session.flash(_("You are already logged in and therefore cannot reset a 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)

    user = User.getByID(forgotPassword.user.id)

    fs = None
    
    if 'submitted' in request.params:
        fs = ResetPasswordFieldSet().bind(User, session = session, data = request.params or None)
        valid = fs.validate()
        if valid:
            user = User.getByID(request.params["user_id"])
            password = bcrypt.hashpw(fs.password1.value, bcrypt.gensalt())
            user.password = password
            user.user_type = User.NORMAL
            session.add(user)
            session.flush()

            session.query(ForgotPassword).filter(ForgotPassword.user_id == user.id).delete()

            request.session["username"] = user.username
            headers = remember(request, user.id)
            request.session.flash(_("You have successfully updated your password!"))
            return HTTPFound(location = route_url("home", request), headers = headers)

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