How can I check if a user is logged in?

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
3 years ago
var isAuthenticated = !workContext.CurrentCustomer.CustomerRoles.Any(x => x.SystemName == "Guests");

:)
2 years ago
How about if someone wants to check for this on a Topic page? In my case, I want to have a button click to content we want to gate and only let Registered users access -- otherwise, we want to throw an alert saying you need to login to access these materials. I tried the if/else logic suggested in the other posts via Javascript without success, e.g.:

Uncaught ReferenceError: customerService is not defined

Thanks for your help here.
2 years ago
@using Nop.Core
@using Nop.Services.Customers

@inject IWorkContext workContext
@inject ICustomerService customerService

@{
    var currentCustomer = await workContext.GetCurrentCustomerAsync();
    if (currentCustomer != null)
    {
        if (await customerService.IsRegisteredAsync(currentCustomer))
        {
            // Do Something
        }
    }
}
2 years ago
Yidna wrote:
@using Nop.Core
@using Nop.Services.Customers

@inject IWorkContext workContext
@inject ICustomerService customerService

@{
    var currentCustomer = await workContext.GetCurrentCustomerAsync();
    if (currentCustomer != null)
    {
        if (await customerService.IsRegisteredAsync(currentCustomer))
        {
            // Do Something
        }
    }
}


That would be in a Razor view -- Topic pages only allow HTML and Javascript, which is why I asked if there was a way via Javascript to determine if someone currently viewing the page is a Registered user (I really meant logged in). Thanks all the same.
2 years ago
If you are asking if you can run code from the HTML and Script entered in the topic then I don’t think so
You can define a variable in the Razor that can be used in script
Another option is to use ajax that does a call to a routine to get extra text if logged in
There is also a password protected option in topics to only display if password is correct which could be modified for your purpose

@using Nop.Core
@using Nop.Services.Customers

@inject IWorkContext workContext
@inject ICustomerService customerService

@{
    var customerIsRegistered = false;
    var currentCustomer = await workContext.GetCurrentCustomerAsync();
    if (currentCustomer != null)
    {
        if (await customerService.IsRegisteredAsync(currentCustomer))
        {
            // Do Something
            customerIsRegistered = true;
        }
    }
}

<script>
....
var test = "Value " + '@customerIsRegistered';
...
</script>
2 years ago
Sorry to say, I'm stuck with the Topic page (/Admin/Topic) as the way to check if a current user is logged in. I had hoped there was a straightforward way via Javascript to determine that, but you're saying there is not?
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.