2020-11-04 20:45:53 +01:00
using Microsoft.AspNetCore.Identity ;
2020-04-08 13:07:15 +02:00
using Raven.Client.Documents ;
2020-11-16 14:48:23 +01:00
using Raven.Client.Documents.Session ;
using System ;
2020-05-11 11:30:56 +02:00
using System.Collections.Generic ;
2020-04-15 14:09:52 +02:00
using System.Linq ;
using System.Security.Claims ;
2020-04-08 13:07:15 +02:00
using System.Threading.Tasks ;
2020-11-15 17:07:27 +01:00
using zero.Core.Database ;
2020-04-08 13:07:15 +02:00
using zero.Core.Entities ;
2020-11-16 14:48:23 +01:00
using zero.Core.Extensions ;
2020-04-16 00:56:22 +02:00
using zero.Core.Identity ;
2020-04-08 13:07:15 +02:00
namespace zero.Core.Api
{
public class AuthenticationApi : IAuthenticationApi
{
2020-11-04 20:45:53 +01:00
protected IZeroContext Context { get ; set ; }
2020-04-08 13:07:15 +02:00
2020-11-05 00:27:02 +01:00
protected SignInManager < BackofficeUser > SignInManager { get ; private set ; }
2020-04-08 13:07:15 +02:00
2021-10-28 12:11:07 +02:00
protected IZeroStore Store { get ; set ; }
2020-05-11 11:30:56 +02:00
2020-11-16 14:48:23 +01:00
2021-10-28 12:11:07 +02:00
public AuthenticationApi ( IZeroContext context , SignInManager < BackofficeUser > signInManager , IZeroStore store )
2020-04-08 13:07:15 +02:00
{
2020-11-04 20:45:53 +01:00
Context = context ;
2020-04-15 14:09:52 +02:00
SignInManager = signInManager ;
2021-10-28 12:11:07 +02:00
Store = store ;
2020-04-08 13:07:15 +02:00
}
/// <inheritdoc />
public bool IsLoggedIn ()
{
2020-11-05 16:28:59 +01:00
return SignInManager . IsSignedIn ( Context . BackofficeUser );
2020-04-15 14:09:52 +02:00
}
2020-05-11 11:30:56 +02:00
/// <inheritdoc />
public bool IsSuper ()
{
2020-11-05 16:28:59 +01:00
return Context . BackofficeUser . HasClaim ( Constants . Auth . Claims . IsSuper , PermissionsValue . True );
2020-05-11 11:30:56 +02:00
}
/// <inheritdoc />
public bool IsAdmin ()
{
2020-11-05 16:28:59 +01:00
return Context . BackofficeUser . HasClaim ( Constants . Auth . Claims . Role , "administrator" ); // TODO use constant (in setup as well)
2020-05-11 11:30:56 +02:00
}
/// <inheritdoc />
2020-11-05 00:27:02 +01:00
public async Task < BackofficeUser > GetUser ()
2020-05-11 11:30:56 +02:00
{
2020-11-05 16:28:59 +01:00
return await SignInManager . UserManager . GetUserAsync ( Context . BackofficeUser );
2020-05-11 11:30:56 +02:00
}
/// <inheritdoc />
public IList < Permission > GetPermissions ( string prefix = null )
{
2020-11-05 16:28:59 +01:00
return Context . BackofficeUser . Claims
2020-05-11 11:30:56 +02:00
. Where ( claim => claim . Type == Constants . Auth . Claims . Permission && ( prefix == null || claim . Value . StartsWith ( prefix )))
. Select ( claim => Permission . FromClaim ( claim , prefix ))
. ToList ();
}
/// <inheritdoc />
public Permission GetPermission ( string key = null )
{
2020-11-05 16:28:59 +01:00
Claim claim = Context . BackofficeUser . Claims . FirstOrDefault ( claim => claim . Type == Constants . Auth . Claims . Permission && claim . Value . StartsWith ( key + ":" ));
2020-05-11 11:30:56 +02:00
return Permission . FromClaim ( claim );
}
2020-04-15 14:09:52 +02:00
/// <inheritdoc />
2020-04-15 15:13:38 +02:00
public async Task < EntityResult > Login ( string email , string password , bool isPersistent )
2020-04-15 14:09:52 +02:00
{
2020-05-07 15:20:41 +02:00
EntityResult result = new EntityResult ();
2020-04-15 14:09:52 +02:00
2020-11-05 00:27:02 +01:00
BackofficeUser user = await SignInManager . UserManager . FindByNameAsync ( email );
2020-05-07 15:20:41 +02:00
if ( user == null )
2020-04-15 15:13:38 +02:00
{
2020-11-03 23:25:26 +01:00
result . AddError ( "@login.errors.wrongcredentials" ); // TODO we don't need translations here, but return an enum, so the app itself can translate the error
2020-05-07 15:20:41 +02:00
return result ;
}
// TODO probably move this logic into a custom SignInManager which overrides CanSignInAsync()
// see https://stackoverflow.com/a/35484758/670860
else if (! user . IsActive )
{
result . AddError ( "@login.errors.disabled" );
return result ;
}
2020-11-03 23:25:26 +01:00
SignInResult signInResult = await SignInManager . PasswordSignInAsync ( user , password , isPersistent , true );
2020-05-07 15:20:41 +02:00
if (! signInResult . Succeeded )
{
if ( signInResult . IsLockedOut )
2020-04-15 15:13:38 +02:00
{
2020-05-07 15:20:41 +02:00
result . AddError ( "@login.errors.lockedout" );
2020-04-15 15:13:38 +02:00
}
2020-05-07 15:20:41 +02:00
else if ( signInResult . IsNotAllowed )
2020-04-15 15:13:38 +02:00
{
2020-05-07 15:20:41 +02:00
result . AddError ( "@login.errors.notallowed" );
2020-04-15 15:13:38 +02:00
}
2020-05-07 15:20:41 +02:00
else if ( signInResult . RequiresTwoFactor )
2020-04-15 15:13:38 +02:00
{
2020-05-07 15:20:41 +02:00
result . AddError ( "@login.errors.requirestwofactor" );
2020-04-15 15:13:38 +02:00
}
else
{
2020-05-07 15:20:41 +02:00
result . AddError ( "@login.errors.wrongcredentials" );
2020-04-15 15:13:38 +02:00
}
2020-05-07 15:20:41 +02:00
return result ;
2020-04-15 15:13:38 +02:00
}
return EntityResult . Success ();
2020-04-15 14:09:52 +02:00
}
/// <inheritdoc />
public async Task Logout ()
{
2020-11-03 23:25:26 +01:00
await SignInManager . SignOutAsync ();
2020-04-08 13:07:15 +02:00
}
/// <inheritdoc />
public string GetUserId ()
{
2020-11-05 16:28:59 +01:00
return SignInManager . UserManager . GetUserId ( Context . BackofficeUser );
2020-04-08 13:07:15 +02:00
}
2020-11-16 14:48:23 +01:00
/// <inheritdoc />
public async Task < bool > TrySwitchApp ( string appId )
{
2021-10-28 12:11:07 +02:00
IZeroDocumentSession session = Store . Session ( global : true );
2021-05-04 17:23:52 +02:00
BackofficeUser user = await GetUser ();
2020-11-16 14:48:23 +01:00
if ( user == null || appId . IsNullOrEmpty ())
{
return false ;
}
string [] allowedAppIds = user . GetAllowedAppIds ();
bool isMainId = appId . Equals ( user . AppId , StringComparison . InvariantCultureIgnoreCase );
bool isAllowedId = allowedAppIds . Contains ( appId , StringComparer . InvariantCultureIgnoreCase );
if ( user . IsSuper || isMainId || isAllowedId )
{
user . CurrentAppId = appId ;
//byte[] bytes = new byte[20];
//RandomNumberGenerator.Fill(bytes);
//user.SecurityStamp = Base32.ToBase32(bytes); // TODO update security stamp but Base32 is .net core internal
2021-10-28 12:11:07 +02:00
await session . StoreAsync ( user );
await session . SaveChangesAsync ();
2020-11-16 14:48:23 +01:00
return true ;
}
return false ;
}
2020-04-08 13:07:15 +02:00
}
public interface IAuthenticationApi
{
2020-05-11 11:30:56 +02:00
/// <summary>
/// Get currently logged-in user
/// </summary>
2020-11-05 00:27:02 +01:00
Task < BackofficeUser > GetUser ();
2020-05-11 11:30:56 +02:00
2020-04-08 13:07:15 +02:00
/// <summary>
/// Whether a user is currently logged-in
/// </summary>
bool IsLoggedIn ();
2020-05-11 11:30:56 +02:00
/// <summary>
/// Whether the current user is the super user who created the zero instance
/// </summary>
bool IsSuper ();
/// <summary>
/// Whether the current user belongs to the administrator role (will always return false if this role gets deleted)
/// </summary>
bool IsAdmin ();
2020-04-15 14:09:52 +02:00
/// <summary>
/// Logs a zero-user in and sets cookie
/// </summary>
2020-04-15 15:13:38 +02:00
Task < EntityResult > Login ( string email , string password , bool isPersistent );
2020-04-15 14:09:52 +02:00
/// <summary>
/// Logs out the current user
/// </summary>
Task Logout ();
2020-04-08 13:07:15 +02:00
/// <summary>
/// Get the ID of the currently logged in user
/// </summary>
string GetUserId ();
2020-05-11 11:30:56 +02:00
/// <summary>
/// Get all permissions for the current user with an optional prefix
/// </summary>
IList < Permission > GetPermissions ( string prefix = null );
/// <summary>
/// Get a single permissions by key
/// </summary>
2020-11-16 14:48:23 +01:00
Permission GetPermission ( string key = null );
/// <summary>
/// Tries to switch the currently loaded backoffice application for the current user
/// </summary>
Task < bool > TrySwitchApp ( string appId );
2020-04-08 13:07:15 +02:00
}
}