Exemple #1
0
def confirm_email(token):
    """View function which handles a email confirmation request."""

    expired, invalid, user = confirm_email_token_status(token)

    if not user or invalid:
        invalid = True

    already_confirmed = user is not None and user.confirmed_at is not None
    expired_and_not_confirmed = expired and not already_confirmed

    if expired_and_not_confirmed:
        send_confirmation_instructions(user)

    if invalid or expired_and_not_confirmed:
        return redirect(get_url(_security.confirm_error_view))

    if confirm_user(user):
        after_this_request(_commit)

    if user != current_user:
        logout_user()
        login_user(user)

    return redirect(get_url(_security.post_confirm_view))
Exemple #2
0
def register():
    form = UserCustomForm()
    #Create a new user
    if request.method == 'POST' and form.validate():
        data = {
            'first_name':
            str(request.values.get('first_name').encode('utf-8')).title(),
            'last_name':
            str(request.values.get('last_name').encode('utf-8')).title(),
            'email':
            str(request.values.get('email').encode('utf-8')),
        }

        if (request.values.get('user_nic')):
            data['extras'] = {'auth_nic': str(request.values.get('user_nic'))}

        userUdata = datastore.create_user(**data)
        datastore.commit()
        send_confirmation_instructions(userUdata)
        do_flash(*get_message('CONFIRM_REGISTRATION', email=data['email']))
        return redirect(url_for('security.login'))

    else:
        form.email.data = session.get('user_email')
        if form.email.data:
            form.email.render_kw = {'readonly': True}
        form.first_name.data = session.get('first_name')
        form.last_name.data = session.get('last_name')
        form.user_nic.data = session.get('user_nic')
        return theme.render('security/register_saml.html', form=form)
Exemple #3
0
def handle_profile_form(form):
    """Handle profile update form."""
    form.process(formdata=request.form)

    if form.validate_on_submit():
        email_changed = False
        with db.session.begin_nested():
            # Update profile.
            current_userprofile.username = form.username.data
            current_userprofile.full_name = form.full_name.data
            db.session.add(current_userprofile)

            # Update email
            if current_app.config['USERPROFILES_EMAIL_ENABLED'] and \
               form.email.data != current_user.email:
                current_user.email = form.email.data
                current_user.confirmed_at = None
                db.session.add(current_user)
                email_changed = True
        db.session.commit()

        if email_changed:
            send_confirmation_instructions(current_user)
            # NOTE: Flash message after successful update of profile.
            flash(_('Profile was updated. We have sent a verification '
                    'email to %(email)s. Please check it.',
                    email=current_user.email),
                  category='success')
        else:
            # NOTE: Flash message after successful update of profile.
            flash(_('Profile was updated.'), category='success')
Exemple #4
0
    def createuser():
        """Create an user"""
        username = click.prompt("Username", type=str)
        email = click.prompt("Email", type=str)
        password = click.prompt("Password",
                                type=str,
                                hide_input=True,
                                confirmation_prompt=True)
        while True:
            role = click.prompt("Role [admin/user]", type=str)
            if role == "admin" or role == "user":
                break

        if click.confirm("Do you want to continue ?"):
            role = Role.query.filter(Role.name == role).first()
            if not role:
                raise click.UsageError("Roles not present in database")
            u = user_datastore.create_user(name=username,
                                           email=email,
                                           password=encrypt_password(password),
                                           roles=[role])

            db.session.commit()

            if FSConfirmable.requires_confirmation(u):
                FSConfirmable.send_confirmation_instructions(u)
                print("Look at your emails for validation instructions.")
Exemple #5
0
def register_step_1_point_5():
    '''
    Tell the user to confirm their email address, with a button to
    send/re-send confirmation instructions.

    Note that users may have arrived here in one of two ways:

      1. They're a brand-new user, in which case flask-security
         has already sent them confirmation instructions.
      2. They're a legacy user, in which case they've already
         completed the subsequent registration steps, and need
         to be informed that the site now requires e-mail confirmation.

    If they user has already confirmed their address, move on.
    '''

    if not current_user.requires_confirmation:
        return redirect(url_for('views.activity'))
    if request.method == 'POST':
        confirmable.send_confirmation_instructions(current_user)
        flash(gettext(u'Confirmation instructions sent.'))
    return render_template('register-step-1.5.html',
        is_legacy_user=has_user_done_register_step_2(current_user),
        form=Form()
    )
Exemple #6
0
def handle_verification_form(form):
    """Handle email sending verification form."""
    form.process(formdata=request.form)

    if form.validate_on_submit():
        send_confirmation_instructions(current_user)
        # NOTE: Flash message.
        flash(_("Verification email sent."), category="success")
Exemple #7
0
def handle_profile_form(form):
    """Handle profile update form."""
    form.process(formdata=request.form)
    if form.validate_on_submit():
        email_changed = False
        with db.session.begin_nested():
            # Update profile.
            current_userprofile.username = form.username.data
            current_userprofile.full_name = form.full_name.data
            data = dict()
            data["biography"] = form.biography.data
            data["institution_id"] = form.institution.data.id
            data["institution_rol"] = form.institution_rol.data
            data["avatar"] = ""
            # print("fichero= ", form.avatar.data)

            # print("aquiiiiii", request)

            # if f:
            #     filename = secure_filename(f.filename)
            #     # print("otro= ", filename)

            if form.avatar.data:
                filename = secure_filename(form.avatar.data.filename)
                path_avatar = os.path.join(
                    current_app.config.get('UPLOADED_PHOTOS_DEST'), filename)
                # print("path= ", path_avatar)
                form.avatar.data.save(path_avatar)

                with open(path_avatar, "r") as file_avatar:
                    encoded_avatar = base64.b64encode(file_avatar)
                    data["avatar"] = encoded_avatar

            current_userprofile.json_metadata = data
            ## print(current_userprofile.json_metadata)
            db.session.add(current_userprofile)

            # Update email
            if current_app.config['USERPROFILES_EMAIL_ENABLED'] and \
                form.email.data != current_user.email:
                current_user.email = form.email.data
                current_user.confirmed_at = None
                db.session.add(current_user)
                email_changed = True
        db.session.commit()

        if email_changed:
            send_confirmation_instructions(current_user)
            # NOTE: Flash message after successful update of profile.
            flash(_(
                'Profile was updated. We have sent a verification '
                'email to %(email)s. Please check it.',
                email=current_user.email),
                  category='success')
        else:
            # NOTE: Flash message after successful update of profile.
            flash(_('Profile was updated.'), category='success')
Exemple #8
0
def resend_confirmation_email():
    """View function which sends confirmation instructions."""
    form = _security.send_confirmation_form(MultiDict(request.get_json()))

    if form.validate_on_submit():
        send_confirmation_instructions(form.user)
    else:
        return jsonify({'errors': form.errors}), HTTPStatus.BAD_REQUEST

    return '', HTTPStatus.NO_CONTENT
Exemple #9
0
def confirm_email(token):
    """View function which handles a email confirmation request."""
    after_this_request(_commit)

    try:
        user = confirm_by_token(token)
    except ConfirmationError, e:
        _logger.debug('Confirmation error: %s' % e)
        if e.user:
            send_confirmation_instructions(e.user)
        do_flash(str(e), 'error')
        confirm_error_url = get_url(_security.confirm_error_view)
        return redirect(confirm_error_url or url_for('send_confirmation'))
Exemple #10
0
def handle_profile_form(form):
    """Handle profile update form."""
    form.process(formdata=request.form)

    if form.validate_on_submit():
        email_changed = False
        with db.session.begin_nested():
            # Update profile.
            for key in form.__dict__:
                if getattr(form, key) and hasattr(current_userprofile, key):
                    form_data = getattr(form, key).data
                    setattr(current_userprofile, key, form_data)
            # Mapping role
            current_config = current_app.config
            if (current_config['WEKO_USERPROFILES_ROLE_MAPPING_ENABLED']
                    and current_userprofile.position):
                role_name = get_role_by_position(current_userprofile.position)
                roles1 = db.session.query(Role).filter_by(name=role_name).all()
                admin_role = current_config.get(
                    "WEKO_USERPROFILES_ADMINISTRATOR_ROLE")
                userprofile_roles = current_config.get(
                    "WEKO_USERPROFILES_ROLES")
                roles2 = [
                    role for role in current_user.roles
                    if role not in userprofile_roles or role == admin_role
                ]
                roles = roles1 + roles2
                if roles:
                    current_user.roles = roles
            db.session.add(current_userprofile)

            # Update email
            if current_app.config['USERPROFILES_EMAIL_ENABLED'] and \
                    form.email.data != current_user.email:
                current_user.email = form.email.data
                current_user.confirmed_at = None
                db.session.add(current_user)
                email_changed = True
        db.session.commit()

        if email_changed:
            send_confirmation_instructions(current_user)
            # NOTE: Flash message after successful update of profile.
            flash(_(
                'Profile was updated. We have sent a verification '
                'email to %(email)s. Please check it.',
                email=current_user.email),
                  category='success')
        else:
            # NOTE: Flash message after successful update of profile.
            flash(_('Profile was updated.'), category='success')
Exemple #11
0
def send_confirmation():
    """View function which sends confirmation instructions."""

    form = SendConfirmationForm(csrf_enabled=not app.testing)

    if form.validate_on_submit():
        user = _datastore.find_user(**form.to_dict())
        if user.confirmed_at is None:
            send_confirmation_instructions(user)
            msg = get_message('CONFIRMATION_REQUEST', email=user.email)
            _logger.debug('%s request confirmation instructions' % user)
        else:
            msg = get_message('ALREADY_CONFIRMED')
        do_flash(*msg)

    return render_template('security/send_confirmation.html',
                           reset_confirmation_form=form,
                           **_ctx('send_confirmation'))
Exemple #12
0
def create():
    """
    Create a user.
    """
    current_app.config["SERVER_NAME"] = current_app.config[
        "REEL2BITS_HOSTNAME"]
    username = click.prompt("Username", type=str)
    email = click.prompt("Email", type=str)
    password = click.prompt("Password",
                            type=str,
                            hide_input=True,
                            confirmation_prompt=True)
    while True:
        role = click.prompt("Role [admin/user]", type=str)
        if role == "admin" or role == "user":
            break

    if click.confirm("Do you want to continue ?"):
        role = Role.query.filter(Role.name == role).first()
        if not role:
            raise click.UsageError("Roles not present in database")
        u = user_datastore.create_user(name=username,
                                       email=email,
                                       password=hash_password(password),
                                       roles=[role])

        actor = create_actor(u)
        actor.user = u
        actor.user_id = u.id
        db.session.add(actor)

        db.session.commit()

        if FSConfirmable.requires_confirmation(u):
            with current_app.app_context():
                FSConfirmable.send_confirmation_instructions(u)
                print("Look at your emails for validation instructions.")
Exemple #13
0
def accounts():
    """
    Register an account
    The method is available to apps with a token obtained via the client credentials grant.
    It creates a user and account records, as well as an access token for the app that initiated the request.
    The method returns the access token, which the app should save for later.
    ---
    tags:
        - Accounts
    definitions:
      Token:
        type: object
        properties:
            access_token:
                type: string
            token_type:
                type: string
            scope:
                type: string
            created_at:
                type: integer
    responses:
      200:
        description: Returns Token
        schema:
            $ref: '#/definitions/Token'
    """

    if not current_app.config["REGISTRATION_ENABLED"]:
        abort(403)

    errors = {}

    # Get the bearer token
    bearer = None
    if "Authorization" in request.headers:
        b = request.headers.get("Authorization")
        b = b.strip().split(" ")
        if len(b) == 2:
            bearer = b[1]
        else:
            errors["bearer"] = ["API Bearer Authorization format issue"]
    else:
        current_app.logger.info(
            "/api/v1/accounts: no Authorization bearer given")

    if not request.json:
        abort(400)

    if "nickname" not in request.json:
        errors["nickname"] = ["nickname is missing"]
    if "email" not in request.json:
        errors["email"] = ["email is missing"]
    if "fullname" not in request.json:
        errors["fullname"] = ["fullname is missing"]
    if "password" not in request.json:
        errors["password"] = ["password is missing"]
    if "confirm" not in request.json:
        errors["confirm"] = ["password confirm is missing"]
    if "agreement" not in request.json:
        errors["agreement"] = ["agreement is missing"]

    if len(errors) > 0:
        return jsonify({"error": str(errors)}), 400

    if forbidden_username(request.json["nickname"]):
        return jsonify(
            {"error": str({"nickname":
                           ["this username cannot be used"]})}), 400

    if request.json["password"] != request.json["confirm"]:
        return jsonify(
            {"error": str({"confirm": ["passwords doesn't match"]})}), 400

    if "agreement" not in request.json:
        return jsonify({
            "error":
            str({"agreement": ["you need to accept the terms and conditions"]})
        }), 400

    # Check if user already exists by local user username
    user = User.query.filter(User.name == request.json["username"]).first()
    if user:
        return jsonify({"error": str({"ap_id":
                                      ["has already been taken"]})}), 400

    # Check if user already exists by old local user (Actors)
    user = Actor.query.filter(
        Actor.preferred_username == request.json["username"]).first()
    if user:
        return jsonify({"error": str({"ap_id":
                                      ["has already been taken"]})}), 400

    # Check if user already exists by email
    user = User.query.filter(User.email == request.json["email"]).first()
    if user:
        return jsonify({"error": str({"email":
                                      ["has already been taken"]})}), 400

    # Check username is valid
    # /^[a-zA-Z\d]+$/
    if not username_is_legal.match(request.json["username"]):
        return jsonify({
            "error":
            str({"ap_id": ["should contains only letters and numbers"]})
        }), 400

    # Proceed to register the user
    role = Role.query.filter(Role.name == "user").first()
    if not role:
        return jsonify({"error": "server error"}), 500

    u = user_datastore.create_user(
        name=request.json["username"],
        email=request.json["email"],
        display_name=request.json["fullname"],
        password=hash_password(request.json["password"]),
        roles=[role],
    )

    actor = create_actor(u)
    actor.user = u
    actor.user_id = u.id
    if "bio" in request.json:
        actor.summary = request.json["bio"]

    db.session.add(actor)
    db.session.commit()

    if FSConfirmable.requires_confirmation(u):
        FSConfirmable.send_confirmation_instructions(u)

    # get the matching item from the given bearer
    bearer_item = OAuth2Token.query.filter(
        OAuth2Token.access_token == bearer).first()
    if not bearer_item:
        abort(400)
    client_item = OAuth2Client.query.filter(
        OAuth2Client.client_id == bearer_item.client_id).first()
    if not client_item:
        abort(400)

    # https://github.com/lepture/authlib/blob/master/authlib/oauth2/rfc6749/grants/base.py#L51
    token = authorization.generate_token(client_item.client_id,
                                         "client_credentials",
                                         user=u,
                                         scope=client_item.scope,
                                         expires_in=None)

    tok = OAuth2Token()
    tok.user_id = u.id
    tok.client_id = client_item.client_id
    # the frontend should request an app every time it doesn't have one in local storage
    # and this app should allow delivering a somewhat non usuable Token
    # token which gets sent to this endpoint and gets used to get back the right client_id
    # to associate in the database...
    tok.token_type = token["token_type"]
    tok.access_token = token["access_token"]
    tok.refresh_token = None
    tok.scope = token["scope"]
    tok.revoked = False
    tok.expires_in = token["expires_in"]
    db.session.add(tok)
    db.session.commit()

    return jsonify({**token, "created_at": tok.issued_at}), 200
Exemple #14
0
        except:
            # Create user
            u = _datastore.create_user(**form.to_dict())
=======
    if not form.validate_on_submit():
        return render_template('security/register.html',
                               register_user_form=form,
                               **_ctx('register'))
>>>>>>> 8919129c95bb1e27e30a925240811cf63e13ece9

    token = None
    user = _datastore.create_user(**form.to_dict())
    _commit()

    if _security.confirmable:
        token = send_confirmation_instructions(user)
        do_flash(*get_message('CONFIRM_REGISTRATION', email=user.email))

    user_registered.send(dict(user=user, confirm_token=token),
                         app=app._get_current_object())

    _logger.debug('User %s registered' % user)

<<<<<<< HEAD
        return redirect(_security.post_register_view or
                        _security.post_login_view)
        
        do_flash(form.errors, 'error')
=======
    if not _security.confirmable or _security.login_without_confirmation:
        after_this_request(_commit)