Member Login behaviour - viewing protected content vs. independent login

Umbraco version: 15.4.2

When using the public access feature of Umbraco to restrict access to pages, a Login page must be specified. When a user tries to view that protected page, the page’s content is replaced with the Login page content at the same URL, then replaced by the page content after a successful login. I would like the Login page to handle both this scenario, and cases where someone has arrived at the Login page without first trying to view protected content. In the latter case, I would like the page to automatically redirect to a given page, instead of redirecting to the same page, which in this case is the Login page.

We are currently using UmbLoginController.HandleLogin to handle the Login request, and I know there is a redirect URL parameter which can be used for this, but at the moment I am unsure if it’s possible to determine if a given visitor has arrived at the Login page because they are trying to view protected content, in which case they should be sent to the same URL after logging in, or if they have arrived at the Login page independently, in which case they should be sent to a different URL.

Is it possible to determine whether a given user has arrived at the Login page after attempting to view protected content, and therefore not include a redirect URL? Or worded another way, is it possible to determine whether a given user has arrived at the Login page without first trying to view protected content, so we can include a redirect URL parameter in the login request?

I’ve got a potential solution for this, which relies on the “current page” property of the Umbraco context reflecting the page with access restrictions applied when showing the login view:

// Get published content for current request
var currentPage = umbracoContext.PublishedRequest?.PublishedContent;

// Get nearest login page, relative to the ancestor Home node
var loginPage = currentPage?.AncestorOrSelf<HomePage>()?.Children<Login>()?.FirstOrDefault();

// If we are requesting the login page, redirect to root. Otherwise, do not redirect
var defaultRedir = currentPage?.Key != loginPage?.Key ? null : "/";

var loginModel = new LoginModel
{
    RedirectUrl = Context.GetQueryValueOrDefault<string?>("redirectUrl",
        defaultRedir)
};

Note: GetQueryValueOrDefault is a utility method from our codebase, which retrieves either the query string value with the specified key (“redirectUrl” here) or the specified fallback value.

This implementation assumes that the Login page configured for public access for the current page is the same as that recorded in the loginPage variable, which may not always be a given. Is it possible to retrieve the Login page that has been configured in the back office for a given node? Specifically, I’m looking to get the node referenced by the “Login” field shown below: