Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed problem with logging in users and immediately needing the cookie #692

Merged
merged 1 commit into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion GeeksCoreLibrary/Components/Account/Account.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
private readonly GclSettings gclSettings;
private readonly IObjectsService objectsService;
private readonly ICommunicationsService communicationsService;

#region Enums

public enum ComponentModes
Expand Down Expand Up @@ -1155,7 +1155,7 @@
/// Handle everything for logging in for cXML punch out (OCI).
/// </summary>
/// <returns></returns>
private async Task HandleCXmlPunchOutLoginModeAsync()

Check warning on line 1158 in GeeksCoreLibrary/Components/Account/Account.cs

View workflow job for this annotation

GitHub Actions / build

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
{
throw new NotImplementedException();
/*var httpContext = HttpContext;
Expand Down Expand Up @@ -1842,6 +1842,8 @@

var offset = (amountOfDaysToRememberCookie ?? 0) <= 0 ? (DateTimeOffset?)null : DateTimeOffset.Now.AddDays(amountOfDaysToRememberCookie.Value);
HttpContextHelpers.WriteCookie(HttpContext, Settings.CookieName, cookieValue, offset, isEssential: true);
// Save the cookie in the HttpContext.Items, so that we can use it in the rest of the request, because we can't read the cookie from the response.
HttpContext.Items[Settings.CookieName] = cookieValue;

if (decryptedUserId == 0)
{
Expand Down
31 changes: 26 additions & 5 deletions GeeksCoreLibrary/Components/Account/Services/AccountsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,18 @@ public async Task<UserCookieDataModel> GetUserDataFromCookieAsync(string cookieN
defaultAnonymousUserModel.MainUserId = defaultAnonymousUserId;
defaultAnonymousUserModel.UserId = defaultAnonymousUserId;

var cookieValue = httpContext.Request.Cookies[cookieName];
string cookieValue;
// First try to get the cookie from the http context items, because it could have been added there if we just logged in via the same request.
if (httpContext.Items.TryGetValue(cookieName, out var cookie))
{
cookieValue = (string) cookie;
}
else
{
// If there is no cookie value in the http context items, try to get it from the request.
cookieValue = httpContext.Request.Cookies[cookieName];
}

if (String.IsNullOrWhiteSpace(cookieValue))
{
return defaultAnonymousUserModel;
Expand Down Expand Up @@ -319,6 +330,11 @@ public async Task LogoutUserAsync(AccountCmsSettingsModel settings, bool isAutoL
return;
}

if (currentContext.Items.ContainsKey(settings.CookieName))
{
currentContext.Items.Remove(settings.CookieName);
}

var cookieValue = currentContext.Request.Cookies[settings.CookieName];
if (String.IsNullOrWhiteSpace(cookieValue))
{
Expand Down Expand Up @@ -469,9 +485,14 @@ public async Task AutoLoginUserAsync(ulong userId, ulong mainUserId, string role
var cookieValue = await GenerateNewCookieTokenAsync(userId, mainUserId, !amountOfDaysToRememberCookie.HasValue || amountOfDaysToRememberCookie.Value <= 0 ? 0 : amountOfDaysToRememberCookie.Value, settings.EntityType, settings.SubAccountEntityType, role);
await SaveGoogleClientIdAsync(userId, settings);

var offset = (amountOfDaysToRememberCookie ?? 0) <= 0 ? (DateTimeOffset?)null : DateTimeOffset.Now.AddDays(amountOfDaysToRememberCookie.Value);
var currentContext = httpContextAccessor.HttpContext;
HttpContextHelpers.WriteCookie(currentContext, settings.CookieName, cookieValue, offset, isEssential: true);
if (currentContext != null)
{
var offset = (amountOfDaysToRememberCookie ?? 0) <= 0 ? (DateTimeOffset?) null : DateTimeOffset.Now.AddDays(amountOfDaysToRememberCookie.Value);
HttpContextHelpers.WriteCookie(currentContext, settings.CookieName, cookieValue, offset, isEssential: true);
// Save the cookie in the HttpContext.Items, so that we can use it in the rest of the request, because we can't read the cookie from the response.
currentContext.Items[settings.CookieName] = cookieValue;
}

await SaveLoginAttemptAsync(true, userId, extraDataForReplacements, settings);
}
Expand Down Expand Up @@ -504,7 +525,7 @@ public async Task SaveGoogleClientIdAsync(ulong userIdForGoogleCid, AccountCmsSe
}

var googleClientId = String.Join(".", clientIdSplit.Skip(2));

// Here we need to retrieve the WiserItemService in a different way using ActivatorUtilities.
// That's because if we use ServiceProvider to retrieve it we gonna lose the database connection scope, and here we need it to be the same
var wiserItemsService = ActivatorUtilities.CreateInstance<WiserItemsService>(serviceProvider, databaseConnection);
Expand Down Expand Up @@ -604,7 +625,7 @@ public string SetupAccountQuery(string template,
.Replace("{subAccountEntityType}", "?subAccountEntityType", StringComparison.OrdinalIgnoreCase).Replace("'{subAccountId}'", "?subAccountId", StringComparison.OrdinalIgnoreCase).Replace("{subAccountId}", "?subAccountId", StringComparison.OrdinalIgnoreCase)
.Replace("'{role}'", "?role", StringComparison.OrdinalIgnoreCase).Replace("{role}", "?role", StringComparison.OrdinalIgnoreCase).Replace("'{basketId}'", "?basketId", StringComparison.OrdinalIgnoreCase).Replace("{basketId}", "?basketId", StringComparison.OrdinalIgnoreCase);
}

/// <inheritdoc />
public int? GetAmountOfDaysToRememberCookie(AccountCmsSettingsModel settings)
{
Expand Down
2 changes: 0 additions & 2 deletions GeeksCoreLibrary/Core/Helpers/HttpContextHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Linq;
using GeeksCoreLibrary.Core.Models;
using GeeksCoreLibrary.Modules.Templates.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
Expand Down Expand Up @@ -420,7 +419,6 @@ public static Uri GetOriginalRequestUri(HttpContext httpContext)
/// <returns>A <see cref="Uri"/> containing the base URL.</returns>
public static Uri GetBaseUri(HttpContext httpContext, bool alwaysHttps = false)
{

return httpContext?.Request == null
? new Uri("https://localhost/")
: new Uri($"{(alwaysHttps ? "https" : httpContext.Request.Scheme)}://{httpContext.Request.Host.Value}{httpContext.Request.PathBase.Value}");
Expand Down
Loading