Exemplo n.º 1
0
def authorize():
    # Login is required since we need to know the current resource owner.
    # The decorator ensures the redirection to the login page when the current
    # user is not authenticated.
    if not current_user.is_authenticated:
        NextRouteRegistry.save(route=request.url)
        return redirect(url_for('auth.login'))
    return _process_authorization()
Exemplo n.º 2
0
def login():
    form = LoginForm()
    flask.session["confirm_user_details"] = True
    if form.validate_on_submit():
        user = form.get_user()
        if user:
            login_user(user)
            flash("You have logged in", category="success")
            return redirect(NextRouteRegistry.pop(url_for("auth.index")))
    return render_template("auth/login.j2",
                           form=form,
                           providers=get_providers())
Exemplo n.º 3
0
def logout():
    logout_user()
    flash("You have logged out", category="success")
    NextRouteRegistry.clear()
    return redirect(url_for("auth.index"))
Exemplo n.º 4
0
    def handle_authorize(self, provider: FlaskRemoteApp, token, user_info: OAuthUserProfile):
        logger.debug("Remote: %r", provider.name)
        logger.debug("Acquired token: %r", token)
        logger.debug("Acquired user_info: %r", user_info)
        # avoid autoflush in this session
        with db.session.no_autoflush:
            try:
                p = OAuth2IdentityProvider.find(provider.name)
                logger.debug("Provider found: %r", p)
            except exceptions.EntityNotFoundException:
                try:
                    logger.debug(f"Provider '{provider.name}' not found!")
                    p = OAuth2IdentityProvider(provider.name, **provider.OAUTH_APP_CONFIG)
                    p.save()
                    logger.info(f"Provider '{provider.name}' registered")
                except Exception as e:
                    return exceptions.report_problem_from_exception(e)

            try:
                identity = p.find_identity_by_provider_user_id(user_info.sub)
                logger.debug("Found OAuth identity <%r,%r>: %r",
                             provider.name, user_info.sub, identity)
                # update identity with the last token and userinfo
                identity.user_info = user_info.to_dict()
                identity.token = token
                logger.debug("Update identity token: %r -> %r", identity.token, token)
            except OAuthIdentityNotFoundException:
                logger.debug("Not found OAuth identity <%r,%r>", provider.name, user_info.sub)
                with db.session.no_autoflush:
                    identity = OAuthIdentity(
                        provider=p,
                        user_info=user_info.to_dict(),
                        provider_user_id=user_info.sub,
                        token=token,
                    )
            # Now, figure out what to do with this token. There are 2x2 options:
            # user login state and token link state.
            if current_user.is_anonymous:
                # If the user is not logged in and the token is linked,
                # log the identity user
                if identity.user:
                    identity.save()
                    login_user(identity.user)
                else:
                    # If the user is not logged in and the token is unlinked,
                    # create a new local user account and log that account in.
                    # This means that one person can make multiple accounts, but it's
                    # OK because they can merge those accounts later.
                    user = User()
                    identity.user = user
                    # Check whether to review user details
                    review_details = session.get("confirm_user_details", None)
                    # Initialize username.
                    # if the user will be automatically registered (without review)
                    # we append a random string to the his identity username
                    identity.user.username = \
                        utils.generate_username(
                            user_info,
                            salt_length=4 if not review_details else 0)
                    if not review_details:
                        identity.save()
                        login_user(user)
                        flash("OAuth identity linked to the current user account.")
                    else:
                        # save the user identity on the current session
                        save_current_user_identity(identity)
                        # and redirect the user
                        # to finalize the registration
                        return redirect(url_for('auth.register_identity'))
            else:
                if identity.user:
                    # If the user is logged in and the token is linked, check if these
                    # accounts are the same!
                    if current_user != identity.user:
                        # Account collision! Ask user if they want to merge accounts.
                        return redirect(url_for(self.merge_view,
                                                provider=identity.provider,
                                                username=identity.user.username))
                # If the user is logged in and the token is unlinked or linked yet,
                # link the token to the current user
                identity.user = current_user
                identity.save()
                flash(f"Your account has successfully been linked to the identity {identity}.")

            # Determine the right next hop
            next_url = NextRouteRegistry.pop()
            flash(f"Logged with your \"{provider.name.capitalize()}\" identity.", category="success")
            return redirect(next_url, code=307) if next_url \
                else RequestHelper.response() or redirect('/', code=302)