Skip to content

Instantly share code, notes, and snippets.

@dealproc
Created March 17, 2019 07:02
Show Gist options
  • Save dealproc/c9278bf5939e3a3bb8b6042bfd665215 to your computer and use it in GitHub Desktop.
Save dealproc/c9278bf5939e3a3bb8b6042bfd665215 to your computer and use it in GitHub Desktop.
Multi-Tenant Solutions - ClaimsPrincipalAccountAccessor.cs
public class ClaimsPrincipalAccountAccessor : IAccountAccessor {
static readonly ILog _log = LogProvider.For<ClaimsPrincipalAccountAccessor>();
readonly IAccountRepository _AccountRepository;
readonly IOwinContext _owinContext;
public ClaimsPrincipalAccountAccessor(IOwinContext owinContext, IAccountRepository accountRepository) {
_owinContext = owinContext;
_AccountRepository=accountRepository;
}
public DataModel.Users.Account GetCurrentAccount() {
if (_owinContext == null) {
throw new NotImplementedException("Owin context is not available.");
}
var principal = _owinContext.Authentication.User;
if (principal == null) {
throw new UnauthorizedAccessException("User is unauthorized.".ShouldBeAResource());
}
try {
var accountClaim = principal.Claims.First(x => x.Type == Constants.ClaimTypes.TenantId || x.Type == Constants.ClaimTypes.AssociatedAccount);
if (accountClaim == null) {
_log.Debug("Principal does not have a TenantId or Associated Account claim.");
throw new UnknownAccountException(4, "Principal does not have a TenantId or Associated Account claim.".ShouldBeAResource());
}
var account = _AccountRepository.GetFirst(x => x.GUID == accountClaim.Value);
if (account == null) {
_log.Debug("Account was not found in the system.");
throw new UnknownAccountException(3, "Account cannot be found from hardware's claims.".ShouldBeAResource());
};
_log.DebugFormat("Associated Account Id/GUID: {accountId}/{accountGuid}", account.Id, account.GUID);
return account;
} catch (Exception) {
_log.Debug("User is not a hardware device. Throwing 'null' back to calling method.");
return null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment