Beispiel #1
0
def add_user():
    from sagenb.notebook.misc import is_valid_username
    template_dict = {'admin': g.notebook.user_manager().user(g.username).is_admin(),
                     'username': g.username}
    if 'username' in request.values:
        username = request.values['username']
        if not is_valid_username(username):
            return render_template(os.path.join('html', 'settings', 'admin_add_user.html'),
                                   error='username_invalid', username=username, **template_dict)

        from random import choice
        import string
        chara = string.letters + string.digits
        password = ''.join([choice(chara) for i in range(8)])
        if username in g.notebook.user_manager().usernames():
            return render_template(os.path.join('html', 'settings', 'admin_add_user.html'),
                                   error='username_taken', username_input=username, **template_dict)
        g.notebook.user_manager().add_user(username, password, '', force=True)

        message = _('The temporary password for the new user <em>%(username)s</em> is <em>%(password)s</em>',
                          username=username, password=password)
        return current_app.message(message, cont='/adduser', title=_('New User'))
    else:
        return render_template(os.path.join('html', 'settings', 'admin_add_user.html'),
                               **template_dict)
Beispiel #2
0
def login(template_dict={}):
    from sagenb.misc.misc import SAGE_VERSION
    template_dict.update({
        'accounts': g.notebook.user_manager().get_accounts(),
        'recovery': g.notebook.conf()['email'],
        'next': request.values.get('next', ''),
        'sage_version': SAGE_VERSION,
        'openid': g.notebook.conf()['openid'],
        'username_error': False,
        'password_error': False
    })

    if request.method == 'POST':
        username = request.form['email']
        password = request.form['password']

        if username == 'COOKIESDISABLED':
            return _(
                "Please enable cookies or delete all Sage cookies and localhost cookies in your browser and try again."
            )

        # we only handle ascii usernames.
        from sagenb.notebook.misc import is_valid_username, is_valid_password
        if is_valid_username(username):
            try:
                U = g.notebook.user_manager().user(username)
            except (KeyError, LookupError):
                U = None
                template_dict['username_error'] = True
        else:
            U = None
            template_dict['username_error'] = True

        # It is critically important that it be impossible to login as the
        # pub, _sage_, or guest users.  This _sage_ user is a fake user that is used
        # internally by the notebook for the doc browser and other tasks.
        if username in ['_sage_', 'guest', 'pub']:
            U = None
            template_dict['username_error'] = True

        if U is None:
            pass
        elif (is_valid_password(password, username) and
              g.notebook.user_manager().check_password(username, password)):
            if U.is_suspended():
                #suspended
                return _("Your account is currently suspended")
            else:
                #Valid user, everything is okay
                session['username'] = username
                session.modified = True
                return redirect(
                    request.values.get('next', url_for('base.index')))
        else:
            template_dict['password_error'] = True

    response = current_app.make_response(
        render_template(os.path.join('html', 'login.html'), **template_dict))
    response.set_cookie('cookie_test_%s' % g.notebook.port, 'cookie_test')
    return response
Beispiel #3
0
def add_user():
    from sagenb.notebook.misc import is_valid_username
    from sagenb.misc.misc import SAGE_VERSION
    template_dict = {'admin': g.notebook.user_manager().user(g.username).is_admin(),
            'username': g.username, 'sage_version': SAGE_VERSION}
    if 'username' in request.values:
        if request.values['cancel']:
            return redirect(url_for('users'))
        username = request.values['username']
        if not is_valid_username(username):
            return render_template(os.path.join('html', 'settings', 'admin_add_user.html'),
                                   error='username_invalid', username_input=username, **template_dict)

        from random import choice
        import string
        chara = string.letters + string.digits
        password = ''.join([choice(chara) for i in range(8)])
        if username in g.notebook.user_manager().usernames():
            return render_template(os.path.join('html', 'settings', 'admin_add_user.html'),
                                   error='username_taken', username_input=username, **template_dict)
        g.notebook.user_manager().add_user(username, password, '', force=True)

        message = _('The temporary password for the new user <em>%(username)s</em> is <em>%(password)s</em>',
                          username=username, password=password)
        return current_app.message(message, cont='/adduser', title=_('New User'))
    else:
        return render_template(os.path.join('html', 'settings', 'admin_add_user.html'),
                               **template_dict)
Beispiel #4
0
def login(template_dict=None):
    if template_dict is None:
        template_dict = {}
    from sagenb.misc.misc import SAGE_VERSION
    template_dict.update({'accounts': g.notebook.user_manager().get_accounts(),
                          'recovery': g.notebook.conf()['email'],
                          'next': request.values.get('next', ''),
                          'sage_version': SAGE_VERSION,
                          'openid': g.notebook.conf()['openid'],
                          'username_error': False,
                          'password_error': False})

    if request.method == 'POST':
        username = request.form['email']
        password = request.form['password']

        if username == 'COOKIESDISABLED':
            return _("Please enable cookies or delete all Sage cookies and localhost cookies in your browser and try again.")

        # we only handle ascii usernames.
        from sagenb.notebook.misc import is_valid_username, is_valid_password
        if is_valid_username(username):
            try:
                U = g.notebook.user_manager().user(username)
            except (KeyError, LookupError):
                U = None
                template_dict['username_error'] = True
        else:
            U = None
            template_dict['username_error'] = True

        # It is critically important that it be impossible to login as the
        # pub, _sage_, or guest users.  This _sage_ user is a fake user that is used
        # internally by the notebook for the doc browser and other tasks.
        if username in ['_sage_', 'guest', 'pub']:
            U = None
            template_dict['username_error'] = True

        if U is None:
            pass
        elif (is_valid_password(password, username) and
              g.notebook.user_manager().check_password(username, password)):
            if U.is_suspended():
                #suspended
                return _("Your account is currently suspended")
            else:
                #Valid user, everything is okay
                session['username'] = username
                session.modified = True
                return redirect(request.values.get('next', url_for('base.index')))
        else:
            template_dict['password_error'] = True

    response = current_app.make_response(render_template(os.path.join('html', 'login.html'), **template_dict))
    response.set_cookie('cookie_test_%s'%g.notebook.port, 'cookie_test')
    return response
Beispiel #5
0
def set_profiles():
    if not g.notebook.conf()['openid']:
        return redirect(url_for('base.index'))
    if request.method == 'GET':
        if 'openid_response' in session:
            from sagenb.notebook.misc import valid_username_chars
            re_invalid_username_chars = re.compile('[^(%s)]' %
                                                   valid_username_chars)
            openid_resp = session['openid_response']
            if openid_resp.fullname is not None:
                openid_resp.fullname = re.sub(re_invalid_username_chars, '_',
                                              openid_resp.fullname)
            return render_template('html/accounts/openid_profile.html',
                                   resp=openid_resp)
        else:
            return redirect(url_for('base.index'))

    if request.method == 'POST':
        if 'openid_response' in session:
            parse_dict = {'resp': session['openid_response']}
        else:
            return redirect(url_for('base.index'))

        try:
            resp = session['openid_response']
            username = request.form.get('username')
            from sagenb.notebook.user import User
            from sagenb.notebook.misc import is_valid_username, is_valid_email
            if not is_valid_username(username):
                parse_dict['username_invalid'] = True
                raise ValueError
            if g.notebook.user_manager().user_exists(username):
                parse_dict['username_taken'] = True
                raise ValueError
            if not is_valid_email(request.form.get('email')):
                parse_dict['email_invalid'] = True
                raise ValueError
            try:
                new_user = User(username,
                                '',
                                email=resp.email,
                                account_type='user')
                g.notebook.user_manager().add_user_object(new_user)
            except ValueError:
                parse_dict['creation_error'] = True
                raise ValueError
            g.notebook.user_manager().create_new_openid(
                resp.identity_url, username)
            session['username'] = g.username = username
            session.modified = True
        except ValueError:
            return render_template('html/accounts/openid_profile.html',
                                   **parse_dict)
        return redirect(url_for('base.index'))
Beispiel #6
0
def set_profiles():
    if not g.notebook.conf()['openid']:
        return redirect(url_for('base.index'))
    if request.method == 'GET':
        if 'openid_response' in session:
            from sagenb.notebook.misc import valid_username_chars
            re_invalid_username_chars = re.compile('[^(%s)]' % valid_username_chars)
            openid_resp = session['openid_response']
            if openid_resp.fullname is not None:
                openid_resp.fullname = re.sub(re_invalid_username_chars, '_', openid_resp.fullname)
            return render_template('html/accounts/openid_profile.html', resp=openid_resp)
        else:
            return redirect(url_for('base.index'))


    if request.method == 'POST':
        if 'openid_response' in session:
            parse_dict = {'resp':session['openid_response']}
        else:
            return redirect(url_for('base.index'))

        try:
            resp = session['openid_response']
            username = request.form.get('username')
            from sagenb.notebook.user import User
            from sagenb.notebook.misc import is_valid_username, is_valid_email
            if not is_valid_username(username):
                parse_dict['username_invalid'] = True
                raise ValueError 
            if g.notebook.user_manager().user_exists(username):
                parse_dict['username_taken'] = True
                raise ValueError 
            if not is_valid_email(request.form.get('email')):
                parse_dict['email_invalid'] = True
                raise ValueError
            try: 
                new_user = User(username, '', email = resp.email, account_type='user') 
                g.notebook.user_manager().add_user_object(new_user)
            except ValueError:
                parse_dict['creation_error'] = True
                raise ValueError
            g.notebook.user_manager().create_new_openid(resp.identity_url, username)
            session['username'] = g.username = username
            session.modified = True
        except ValueError:
            return render_template('html/accounts/openid_profile.html', **parse_dict) 
        return redirect(url_for('base.index'))
Beispiel #7
0
def add_user():
    from sagenb.notebook.misc import is_valid_username
    from sagenb.misc.misc import SAGE_VERSION

    template_dict = {
        "admin": g.notebook.user_manager().user(g.username).is_admin(),
        "username": g.username,
        "sage_version": SAGE_VERSION,
    }
    if "username" in request.values:
        if request.values["cancel"]:
            return redirect(url_for("users"))
        username = request.values["username"]
        if not is_valid_username(username):
            return render_template(
                os.path.join("html", "settings", "admin_add_user.html"),
                error="username_invalid",
                username_input=username,
                **template_dict
            )

        from random import choice
        import string

        chara = string.letters + string.digits
        password = "".join([choice(chara) for i in range(8)])
        if username in g.notebook.user_manager().usernames():
            return render_template(
                os.path.join("html", "settings", "admin_add_user.html"),
                error="username_taken",
                username_input=username,
                **template_dict
            )
        g.notebook.user_manager().add_user(username, password, "", force=True)

        message = _(
            "The temporary password for the new user <em>%(username)s</em> is <em>%(password)s</em>",
            username=username,
            password=password,
        )
        return current_app.message(message, cont="/adduser", title=_("New User"))
    else:
        return render_template(os.path.join("html", "settings", "admin_add_user.html"), **template_dict)
Beispiel #8
0
def add_user():
    from sagenb.notebook.misc import is_valid_username

    username = request.values['username']
    password = random_password()

    if not is_valid_username(username):
        return encode_response({
            'error': _('<strong>Invalid username!</strong>')
        })

    if username in g.notebook.user_manager().usernames():
        return encode_response({
            'error': _('The username <strong>%(username)s</strong> is already taken!', username=username)
        })

    g.notebook.user_manager().add_user(username, password, '', force=True)
    return encode_response({
        'message': _('The temporary password for the new user <strong>%(username)s</strong> is <strong>%(password)s</strong>',
                      username=username, password=password)
    })
Beispiel #9
0
def add_user():
    from sagenb.notebook.misc import is_valid_username

    username = request.values['username']
    password = random_password()

    if not is_valid_username(username):
        return encode_response(
            {'error': _('<strong>Invalid username!</strong>')})

    if username in g.notebook.user_manager().usernames():
        return encode_response({
            'error':
            _('The username <strong>%(username)s</strong> is already taken!',
              username=username)
        })

    g.notebook.user_manager().add_user(username, password, '', force=True)
    return encode_response({
        'message':
        _('The temporary password for the new user <strong>%(username)s</strong> is <strong>%(password)s</strong>',
          username=username,
          password=password)
    })
Beispiel #10
0
def login(template_dict={}):
    from sagenb.misc.misc import SAGE_VERSION

    template_dict.update(
        {
            "accounts": g.notebook.user_manager().get_accounts(),
            "recovery": g.notebook.conf()["email"],
            "next": request.values.get("next", ""),
            "sage_version": SAGE_VERSION,
            "openid": g.notebook.conf()["openid"],
            "username_error": False,
            "password_error": False,
        }
    )

    if request.method == "POST":
        username = request.form["email"]
        password = request.form["password"]

        if username == "COOKIESDISABLED":
            return _(
                "Please enable cookies or delete all Sage cookies and localhost cookies in your browser and try again."
            )

        # we only handle ascii usernames.
        from sagenb.notebook.misc import is_valid_username, is_valid_password

        if is_valid_username(username):
            try:
                U = g.notebook.user_manager().user(username)
            except (KeyError, LookupError):
                U = None
                template_dict["username_error"] = True
        else:
            U = None
            template_dict["username_error"] = True

        # It is critically important that it be impossible to login as the
        # pub, _sage_, or guest users.  This _sage_ user is a fake user that is used
        # internally by the notebook for the doc browser and other tasks.
        if username in ["_sage_", "guest", "pub"]:
            U = None
            template_dict["username_error"] = True

        if U is None:
            pass
        elif is_valid_password(password, username) and g.notebook.user_manager().check_password(username, password):
            if U.is_suspended():
                # suspended
                return _("Your account is currently suspended")
            else:
                # Valid user, everything is okay
                session["username"] = username
                session.modified = True
                return redirect(request.values.get("next", url_for("base.index")))
        else:
            template_dict["password_error"] = True

    response = current_app.make_response(render_template(os.path.join("html", "login.html"), **template_dict))
    response.set_cookie("cookie_test_%s" % g.notebook.port, "cookie_test")
    return response
Beispiel #11
0
def register():
    if not g.notebook.user_manager().get_accounts():
        return redirect(url_for("base.index"))
    from sagenb.notebook.misc import is_valid_username, is_valid_password, is_valid_email, do_passwords_match
    from sagenb.notebook.challenge import challenge

    # VALIDATORS: is_valid_username, is_valid_password,
    # do_passwords_match, is_valid_email,
    # challenge.is_valid_response
    # INPUT NAMES: username, password, retype_password, email +
    # challenge fields

    # TEMPLATE VARIABLES: error, username, username_missing,
    # username_taken, username_invalid, password_missing,
    # password_invalid, passwords_dont_match,
    # retype_password_missing, email, email_missing,
    # email_invalid, email_address, challenge, challenge_html,
    # challenge_missing, challenge_invalid

    # PRE-VALIDATION setup and hooks.
    required = set(["username", "password"])
    empty = set()
    validated = set()

    # Template variables.  We use empty_form_dict for empty forms.
    empty_form_dict = {}
    template_dict = {}

    if g.notebook.conf()["email"]:
        required.add("email")
        empty_form_dict["email"] = True

    if g.notebook.conf()["challenge"]:
        required.add("challenge")
        empty_form_dict["challenge"] = True
        chal = challenge(g.notebook.conf(), is_secure=g.notebook.secure, remote_ip=request.environ["REMOTE_ADDR"])
        empty_form_dict["challenge_html"] = chal.html()

    template_dict.update(empty_form_dict)

    # VALIDATE FIELDS.

    # Username.  Later, we check if a user with this username
    # already exists.
    username = request.values.get("username", None)
    if username:
        if not is_valid_username(username):
            template_dict["username_invalid"] = True
        elif g.notebook.user_manager().user_exists(username):
            template_dict["username_taken"] = True
        else:
            template_dict["username"] = username
            validated.add("username")
    else:
        template_dict["username_missing"] = True
        empty.add("username")

    # Password.
    password = request.values.get("password", None)
    retype_password = request.values.get("retype_password", None)
    if password:
        if not is_valid_password(password, username):
            template_dict["password_invalid"] = True
        elif not do_passwords_match(password, retype_password):
            template_dict["passwords_dont_match"] = True
        else:
            validated.add("password")
    else:
        template_dict["password_missing"] = True
        empty.add("password")

    # Email address.
    email_address = ""
    if g.notebook.conf()["email"]:
        email_address = request.values.get("email", None)
        if email_address:
            if not is_valid_email(email_address):
                template_dict["email_invalid"] = True
            else:
                template_dict["email_address"] = email_address
                validated.add("email")
        else:
            template_dict["email_missing"] = True
            empty.add("email")

    # Challenge (e.g., reCAPTCHA).
    if g.notebook.conf()["challenge"]:
        status = chal.is_valid_response(req_args=request.values)
        if status.is_valid is True:
            validated.add("challenge")
        elif status.is_valid is False:
            err_code = status.error_code
            if err_code:
                template_dict["challenge_html"] = chal.html(error_code=err_code)
            else:
                template_dict["challenge_invalid"] = True
        else:
            template_dict["challenge_missing"] = True
            empty.add("challenge")

    # VALIDATE OVERALL.
    if empty == required:
        # All required fields are empty.  Not really an error.
        return render_template(os.path.join("html", "accounts", "registration.html"), **empty_form_dict)
    elif validated != required:
        # Error(s)!
        errors = len(required) - len(validated)
        template_dict["error"] = "E " if errors == 1 else "Es "
        return render_template(os.path.join("html", "accounts", "registration.html"), **template_dict)

    # Create an account, if username is unique.
    try:
        g.notebook.user_manager().add_user(username, password, email_address)
    except ValueError:
        template_dict["username_taken"] = True
        template_dict["error"] = "E "

        form = render_template(os.path.join("html", "accounts", "registration.html"), **template_dict)
        return HTMLResponse(stream=form)

    # XXX: Add logging support
    # log.msg("Created new user '%s'"%username)

    # POST-VALIDATION hooks.  All required fields should be valid.
    if g.notebook.conf()["email"]:
        from sagenb.notebook.smtpsend import send_mail
        from sagenb.notebook.register import make_key, build_msg

        # TODO: make this come from the server settings
        key = make_key()
        listenaddr = g.notebook.interface
        port = g.notebook.port
        fromaddr = "no-reply@%s" % listenaddr
        body = build_msg(key, username, listenaddr, port, g.notebook.secure)

        # Send a confirmation message to the user.
        try:
            send_mail(fromaddr, email_address, _("Sage Notebook Registration"), body)
            waiting[key] = username
        except ValueError:
            pass

    # Go to the login page.
    from sagenb.misc.misc import SAGE_VERSION

    template_dict = {
        "accounts": g.notebook.user_manager().get_accounts(),
        "welcome_user": username,
        "recovery": g.notebook.conf()["email"],
        "sage_version": SAGE_VERSION,
    }

    return render_template(os.path.join("html", "login.html"), **template_dict)
Beispiel #12
0
def set_profiles():
    if not g.notebook.conf()['openid']:
        return redirect(url_for('base.index'))

    from sagenb.notebook.challenge import challenge

    show_challenge = g.notebook.conf()['challenge']
    if show_challenge:
        chal = challenge(g.notebook.conf(),
                         is_secure=g.notebook.secure,
                         remote_ip=request.environ['REMOTE_ADDR'])

    if request.method == 'GET':
        if 'openid_response' in session:
            from sagenb.notebook.misc import valid_username_chars
            re_invalid_username_chars = re.compile('[^(%s)]' %
                                                   valid_username_chars)
            openid_resp = session['openid_response']
            if openid_resp.fullname is not None:
                openid_resp.fullname = re.sub(re_invalid_username_chars, '_',
                                              openid_resp.fullname)
            template_dict = {}
            if show_challenge:
                template_dict['challenge_html'] = chal.html()

            return render_template('html/accounts/openid_profile.html',
                                   resp=openid_resp,
                                   challenge=show_challenge,
                                   **template_dict)
        else:
            return redirect(url_for('base.index'))

    if request.method == 'POST':
        if 'openid_response' in session:
            parse_dict = {'resp': session['openid_response']}
        else:
            return redirect(url_for('base.index'))

        try:
            resp = session['openid_response']
            username = request.form.get('username')
            from sagenb.notebook.user import User
            from sagenb.notebook.misc import is_valid_username, is_valid_email

            if show_challenge:
                parse_dict['challenge'] = True
                status = chal.is_valid_response(req_args=request.values)
                if status.is_valid is True:
                    pass
                elif status.is_valid is False:
                    err_code = status.error_code
                    if err_code:
                        parse_dict['challenge_html'] = chal.html(
                            error_code=err_code)
                    else:
                        parse_dict['challenge_invalid'] = True
                    raise ValueError("Invalid challenge")
                else:
                    parse_dict['challenge_missing'] = True
                    raise ValueError("Missing challenge")

            if not is_valid_username(username):
                parse_dict['username_invalid'] = True
                raise ValueError("Invalid username")
            if g.notebook.user_manager().user_exists(username):
                parse_dict['username_taken'] = True
                raise ValueError("Pre-existing username")
            if not is_valid_email(request.form.get('email')):
                parse_dict['email_invalid'] = True
                raise ValueError("Invalid email")
            try:
                new_user = User(username,
                                '',
                                email=resp.email,
                                account_type='user')
                g.notebook.user_manager().add_user_object(new_user)
            except ValueError as msg:
                parse_dict['creation_error'] = True
                raise ValueError("Error in creating user\n%s" % msg)
            g.notebook.user_manager().create_new_openid(
                resp.identity_url, username)
            session['username'] = g.username = username
            session.modified = True
        except ValueError:
            return render_template('html/accounts/openid_profile.html',
                                   **parse_dict)
        return redirect(url_for('base.index'))
Beispiel #13
0
def set_profiles():
    if not g.notebook.conf()['openid']:
        return redirect(url_for('base.index'))

    from sagenb.notebook.challenge import challenge


    show_challenge=g.notebook.conf()['challenge']
    if show_challenge:
        chal = challenge(g.notebook.conf(),
                         is_secure = g.notebook.secure,
                         remote_ip = request.environ['REMOTE_ADDR'])

    if request.method == 'GET':
        if 'openid_response' in session:
            from sagenb.notebook.misc import valid_username_chars
            re_invalid_username_chars = re.compile('[^(%s)]' % valid_username_chars)
            openid_resp = session['openid_response']
            if openid_resp.fullname is not None:
                openid_resp.fullname = re.sub(re_invalid_username_chars, '_', openid_resp.fullname)
            template_dict={}
            if show_challenge:
                template_dict['challenge_html'] = chal.html()

            return render_template('html/accounts/openid_profile.html', resp=openid_resp, 
                                   challenge=show_challenge, **template_dict)
        else:
            return redirect(url_for('base.index'))


    if request.method == 'POST':
        if 'openid_response' in session:
            parse_dict = {'resp':session['openid_response']}
        else:
            return redirect(url_for('base.index'))

        try:
            resp = session['openid_response']
            username = request.form.get('username')
            from sagenb.notebook.user import User
            from sagenb.notebook.misc import is_valid_username, is_valid_email

            if show_challenge:
                parse_dict['challenge'] = True
                status = chal.is_valid_response(req_args = request.values)
                if status.is_valid is True:
                    pass
                elif status.is_valid is False:
                    err_code = status.error_code
                    if err_code:
                        parse_dict['challenge_html'] = chal.html(error_code = err_code)
                    else:
                        parse_dict['challenge_invalid'] = True
                    raise ValueError
                else:
                    parse_dict['challenge_missing'] = True
                    raise ValueError

            if not is_valid_username(username):
                parse_dict['username_invalid'] = True
                raise ValueError
            if g.notebook.user_manager().user_exists(username):
                parse_dict['username_taken'] = True
                raise ValueError
            if not is_valid_email(request.form.get('email')):
                parse_dict['email_invalid'] = True
                raise ValueError
            try:
                new_user = User(username, '', email = resp.email, account_type='user') 
                g.notebook.user_manager().add_user_object(new_user)
            except ValueError:
                parse_dict['creation_error'] = True
                raise ValueError
            g.notebook.user_manager().create_new_openid(resp.identity_url, username)
            session['username'] = g.username = username
            session.modified = True
        except ValueError:
            return render_template('html/accounts/openid_profile.html', **parse_dict)
        return redirect(url_for('base.index'))
Beispiel #14
0
def register():
    if not g.notebook.user_manager().get_accounts():
        return redirect(url_for('base.index'))
    from sagenb.notebook.misc import is_valid_username, is_valid_password, \
    is_valid_email, do_passwords_match
    from sagenb.notebook.challenge import challenge

    # VALIDATORS: is_valid_username, is_valid_password,
    # do_passwords_match, is_valid_email,
    # challenge.is_valid_response
    # INPUT NAMES: username, password, retype_password, email +
    # challenge fields

    # TEMPLATE VARIABLES: error, username, username_missing,
    # username_taken, username_invalid, password_missing,
    # password_invalid, passwords_dont_match,
    # retype_password_missing, email, email_missing,
    # email_invalid, email_address, challenge, challenge_html,
    # challenge_missing, challenge_invalid

    # PRE-VALIDATION setup and hooks.
    required = set(['username', 'password'])
    empty = set()
    validated = set()

    # Template variables.  We use empty_form_dict for empty forms.
    empty_form_dict = {}
    template_dict = {}

    if g.notebook.conf()['email']:
        required.add('email')
        empty_form_dict['email'] = True

    if g.notebook.conf()['challenge']:
        required.add('challenge')
        empty_form_dict['challenge'] = True
        chal = challenge(g.notebook.conf(),
                         is_secure=g.notebook.secure,
                         remote_ip=request.environ['REMOTE_ADDR'])
        empty_form_dict['challenge_html'] = chal.html()

    template_dict.update(empty_form_dict)

    # VALIDATE FIELDS.

    # Username.  Later, we check if a user with this username
    # already exists.
    username = request.values.get('username', None)
    if username:
        if not is_valid_username(username):
            template_dict['username_invalid'] = True
        elif g.notebook.user_manager().user_exists(username):
            template_dict['username_taken'] = True
        else:
            template_dict['username'] = username
            validated.add('username')
    else:
        template_dict['username_missing'] = True
        empty.add('username')

    # Password.
    password = request.values.get('password', None)
    retype_password = request.values.get('retype_password', None)
    if password:
        if not is_valid_password(password, username):
            template_dict['password_invalid'] = True
        elif not do_passwords_match(password, retype_password):
            template_dict['passwords_dont_match'] = True
        else:
            validated.add('password')
    else:
        template_dict['password_missing'] = True
        empty.add('password')

    # Email address.
    email_address = ''
    if g.notebook.conf()['email']:
        email_address = request.values.get('email', None)
        if email_address:
            if not is_valid_email(email_address):
                template_dict['email_invalid'] = True
            else:
                template_dict['email_address'] = email_address
                validated.add('email')
        else:
            template_dict['email_missing'] = True
            empty.add('email')

    # Challenge (e.g., reCAPTCHA).
    if g.notebook.conf()['challenge']:
        status = chal.is_valid_response(req_args=request.values)
        if status.is_valid is True:
            validated.add('challenge')
        elif status.is_valid is False:
            err_code = status.error_code
            if err_code:
                template_dict['challenge_html'] = chal.html(
                    error_code=err_code)
            else:
                template_dict['challenge_invalid'] = True
        else:
            template_dict['challenge_missing'] = True
            empty.add('challenge')

    # VALIDATE OVERALL.
    if empty == required:
        # All required fields are empty.  Not really an error.
        return render_template(
            os.path.join('html', 'accounts', 'registration.html'),
            **empty_form_dict)
    elif validated != required:
        # Error(s)!
        errors = len(required) - len(validated)
        template_dict['error'] = 'E ' if errors == 1 else 'Es '
        return render_template(
            os.path.join('html', 'accounts', 'registration.html'),
            **template_dict)

    # Create an account, if username is unique.
    try:
        g.notebook.user_manager().add_user(username, password, email_address)
    except ValueError:
        template_dict['username_taken'] = True
        template_dict['error'] = 'E '

        form = render_template(
            os.path.join('html', 'accounts', 'registration.html'),
            **template_dict)
        return HTMLResponse(stream=form)

    #XXX: Add logging support
    #log.msg("Created new user '%s'"%username)

    # POST-VALIDATION hooks.  All required fields should be valid.
    if g.notebook.conf()['email']:
        from sagenb.notebook.smtpsend import send_mail
        from sagenb.notebook.register import make_key, build_msg

        # TODO: make this come from the server settings
        key = make_key()
        listenaddr = g.notebook.interface
        port = g.notebook.port
        fromaddr = 'no-reply@%s' % listenaddr
        body = build_msg(key, username, listenaddr, port, g.notebook.secure)

        # Send a confirmation message to the user.
        try:
            send_mail(fromaddr, email_address, "Sage Notebook Registration",
                      body)
            waiting[key] = username
        except ValueError:
            pass

    # Go to the login page.
    from sagenb.misc.misc import SAGE_VERSION
    template_dict = {
        'accounts': g.notebook.user_manager().get_accounts(),
        'welcome_user': username,
        'recovery': g.notebook.conf()['email'],
        'sage_version': SAGE_VERSION
    }

    return render_template(os.path.join('html', 'login.html'), **template_dict)
Beispiel #15
0
def set_profiles():
    if not g.notebook.conf()["openid"]:
        return redirect(url_for("base.index"))

    from sagenb.notebook.challenge import challenge

    show_challenge = g.notebook.conf()["challenge"]
    if show_challenge:
        chal = challenge(g.notebook.conf(), is_secure=g.notebook.secure, remote_ip=request.environ["REMOTE_ADDR"])

    if request.method == "GET":
        if "openid_response" in session:
            from sagenb.notebook.misc import valid_username_chars

            re_invalid_username_chars = re.compile("[^(%s)]" % valid_username_chars)
            openid_resp = session["openid_response"]
            if openid_resp.fullname is not None:
                openid_resp.fullname = re.sub(re_invalid_username_chars, "_", openid_resp.fullname)
            template_dict = {}
            if show_challenge:
                template_dict["challenge_html"] = chal.html()

            return render_template(
                "html/accounts/openid_profile.html", resp=openid_resp, challenge=show_challenge, **template_dict
            )
        else:
            return redirect(url_for("base.index"))

    if request.method == "POST":
        if "openid_response" in session:
            parse_dict = {"resp": session["openid_response"]}
        else:
            return redirect(url_for("base.index"))

        try:
            resp = session["openid_response"]
            username = request.form.get("username")
            from sagenb.notebook.user import User
            from sagenb.notebook.misc import is_valid_username, is_valid_email

            if show_challenge:
                parse_dict["challenge"] = True
                status = chal.is_valid_response(req_args=request.values)
                if status.is_valid is True:
                    pass
                elif status.is_valid is False:
                    err_code = status.error_code
                    if err_code:
                        parse_dict["challenge_html"] = chal.html(error_code=err_code)
                    else:
                        parse_dict["challenge_invalid"] = True
                    raise ValueError
                else:
                    parse_dict["challenge_missing"] = True
                    raise ValueError

            if not is_valid_username(username):
                parse_dict["username_invalid"] = True
                raise ValueError
            if g.notebook.user_manager().user_exists(username):
                parse_dict["username_taken"] = True
                raise ValueError
            if not is_valid_email(request.form.get("email")):
                parse_dict["email_invalid"] = True
                raise ValueError
            try:
                new_user = User(username, "", email=resp.email, account_type="user")
                g.notebook.user_manager().add_user_object(new_user)
            except ValueError:
                parse_dict["creation_error"] = True
                raise ValueError
            g.notebook.user_manager().create_new_openid(resp.identity_url, username)
            session["username"] = g.username = username
            session.modified = True
        except ValueError:
            return render_template("html/accounts/openid_profile.html", **parse_dict)
        return redirect(url_for("base.index"))
Beispiel #16
0
def register():
    from sagenb.notebook.misc import is_valid_username, is_valid_password, \
    is_valid_email, do_passwords_match
    from sagenb.notebook.challenge import challenge

    # VALIDATORS: is_valid_username, is_valid_password,
    # do_passwords_match, is_valid_email,
    # challenge.is_valid_response
    # INPUT NAMES: username, password, retype_password, email +
    # challenge fields

    # TEMPLATE VARIABLES: error, username, username_missing,
    # username_taken, username_invalid, password_missing,
    # password_invalid, passwords_dont_match,
    # retype_password_missing, email, email_missing,
    # email_invalid, email_address, challenge, challenge_html,
    # challenge_missing, challenge_invalid

    # PRE-VALIDATION setup and hooks.
    required = set(['username', 'password'])
    empty = set()
    validated = set()

    # Template variables.  We use empty_form_dict for empty forms.
    empty_form_dict = {}
    template_dict = {}

    if g.notebook.conf()['email']:
        required.add('email')
        empty_form_dict['email'] = True

    if g.notebook.conf()['challenge']:
        required.add('challenge')
        empty_form_dict['challenge'] = True
        chal = challenge(g.notebook.conf(),
                         is_secure = g.notebook.secure,
                         remote_ip = request.environ['REMOTE_ADDR'])
        empty_form_dict['challenge_html'] = chal.html()

    template_dict.update(empty_form_dict)

    # VALIDATE FIELDS.

    # Username.  Later, we check if a user with this username
    # already exists.
    username = request.values.get('username', None)
    if username:
        if not is_valid_username(username):
            template_dict['username_invalid'] = True
        elif g.notebook.user_manager().user_exists(username):
            template_dict['username_taken'] = True
        else:
            template_dict['username'] = username
            validated.add('username')
    else:
        template_dict['username_missing'] = True
        empty.add('username')

    # Password.
    password = request.values.get('password', None)
    retype_password = request.values.get('retype_password', None)
    if password:
        if not is_valid_password(password, username):
            template_dict['password_invalid'] = True
        elif not do_passwords_match(password, retype_password):
            template_dict['passwords_dont_match'] = True
        else:
            validated.add('password')
    else:
        template_dict['password_missing'] = True
        empty.add('password')

    # Email address.
    email_address = ''
    if g.notebook.conf()['email']:
        email_address = request.args.get('email', [None])[0]
        if email_address:
            if not is_valid_email(email_address):
                template_dict['email_invalid'] = True
            else:
                template_dict['email_address'] = email_address
                validated.add('email')
        else:
            template_dict['email_missing'] = True
            empty.add('email')

    # Challenge (e.g., reCAPTCHA).
    if g.notebook.conf()['challenge']:
        status = chal.is_valid_response(req_args = request.args)
        if status.is_valid is True:
            validated.add('challenge')
        elif status.is_valid is False:
            err_code = status.error_code
            if err_code:
                template_dict['challenge_html'] = chal.html(error_code = err_code)
            else:
                template_dict['challenge_invalid'] = True
        else:
            template_dict['challenge_missing'] = True
            empty.add('challenge')

    # VALIDATE OVERALL.
    if empty == required:
        # All required fields are empty.  Not really an error.
        return render_template(os.path.join('html', 'accounts', 'registration.html'),
                               **empty_form_dict)
    elif validated != required:
        # Error(s)!
        errors = len(required) - len(validated)
        template_dict['error'] = 'E ' if errors == 1 else 'Es '
        return render_template(os.path.join('html', 'accounts', 'registration.html'),
                        **template_dict)

    # Create an account, if username is unique.
    try:
        g.notebook.user_manager().add_user(username, password, email_address)
    except ValueError:
        template_dict['username_taken'] = True
        template_dict['error'] = 'E '

        form = render_template(os.path.join('html', 'accounts', 'registration.html'),
                        **template_dict)
        return HTMLResponse(stream = form)

    #XXX: Add logging support
    #log.msg("Created new user '%s'"%username)

    # POST-VALIDATION hooks.  All required fields should be valid.
    if g.notebook.conf()['email']:
        from sagenb.notebook.smtpsend import send_mail
        from sagenb.notebook.register import make_key, build_msg

        # TODO: make this come from the server settings
        key = make_key()
        listenaddr = g.notebook.interface
        port = g.notebook.port
        fromaddr = 'no-reply@%s' % listenaddr
        body = build_msg(key, username, listenaddr, port, g.notebook.secure)

        # Send a confirmation message to the user.
        try:
            send_mail(fromaddr, email_address,
                      "Sage Notebook Registration", body)
            waiting[key] = username
        except ValueError:
            pass

    # Go to the login page.
    from sagenb.misc.misc import SAGE_VERSION
    template_dict = {'accounts': g.notebook.user_manager().get_accounts(),
                     'default_user': g.notebook.user_manager().default_user(),
                     'welcome_user': username,
                     'recovery': g.notebook.conf()['email'],
                     'sage_version': SAGE_VERSION}

    return render_template(os.path.join('html', 'login.html'), **template_dict)