internal void DeleteTestAggregate(TestAggregate aggregate)
        {
            var repository = new Repository<TestAggregate, TestEntity>();
            using (var unitOfWork = new UnitOfWorkFactory(TestSettings.BoilerMongoConfiguration).CreateUnitOfWork())
            {
                repository.UnitOfWork = unitOfWork;
                repository.Delete(aggregate);

                unitOfWork.Commit();
            }
        }
        internal void UpdateLastCreatedTestAggregateName(string name)
        {
            var repository = new Repository<TestAggregate, TestEntity>();
            using (var unitOfWork = new UnitOfWorkFactory(TestSettings.BoilerMongoConfiguration).CreateUnitOfWork())
            {
                repository.UnitOfWork = unitOfWork;
                var aggregate = repository[LastCreatedAggregateId].Value;
                aggregate.SetName(name);

                unitOfWork.Commit();
            }
        }
        public void ValidationErrorThrowsModelValidationException()
        {
            var    unitOfWork = new UnitOfWorkFactory().Create();
            Action act        = () =>
            {
                var repository = new InsureeRepository();
                repository.Add(new Insuree());
                unitOfWork.Commit(true);
            };

            act.ShouldThrow <ModelValidationException>();
            unitOfWork.Undo();
        }
        internal void StoreTestAggregate(TestAggregate testAggregate)
        {
            var repository = new Repository<TestAggregate, TestEntity>();
            using (var unitOfWork = new UnitOfWorkFactory(TestSettings.BoilerMongoConfiguration).CreateUnitOfWork())
            {
                repository.UnitOfWork = unitOfWork;
                repository.Add(testAggregate);

                unitOfWork.Commit();

                LastCreatedAggregateId = testAggregate.Id;
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (var unitOfWork = new UnitOfWorkFactory().Create())
            {
                string requestIPAddress = GetIpAddress();

                var auditLog = new AuditActivityLog()
                {
                    SenderUserID     = context.UserName,
                    SenderRequestURL = HttpContext.Current.Request.Url.OriginalString,
                    SenderIP         = requestIPAddress,
                    AuditDateTime    = DateTime.Now
                };
                var auditId = unitOfWork.AuditRepository.CreateAuditActivityLog(auditLog);
                unitOfWork.Commit();

                try
                {
                    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

                    var clientUser = unitOfWork.UserRepository.GetUserByName(x => x, context.UserName,
                                                                             new List <Expression <Func <ClientUser, object> > > {
                        x => x.Client,
                        x => x.UserIPAddresses
                    });
                    if (clientUser == null || !(await unitOfWork.UserRepository.IsPasswordValidAsync(clientUser, context.Password)))
                    {
                        throw new AuthenticationException("The user name or password is incorrect.");
                    }

                    auditLog.LoginUser    = clientUser;
                    auditLog.InsightEmail = clientUser.Email;

                    if (!clientUser.Active)
                    {
                        throw new AuthenticationException("The user account is disabled.");
                    }
                    if (clientUser.Client == null)
                    {
                        throw new AuthenticationException("The user account doesn't have a client associated with it.");
                    }

                    DateTime nowDateTime = DateTime.UtcNow;

                    //Check whitelisting of IP addresses
                    if (clientUser.Client.WhitelistIPs)
                    {
                        List <ClientIPAddresses> userIPWhiteList = clientUser.UserIPAddresses == null ? null : clientUser.UserIPAddresses.Where(x => (x.IPAddress4 == requestIPAddress)).ToList();
                        if (userIPWhiteList == null || userIPWhiteList.Count() == 0)
                        {
                            throw new AuthenticationException("Connection denied.");
                        }
                    }

                    //Check number of open tokens limit
                    int openTokensLimit = clientUser.Client.OpenTokensLimit;
                    if (openTokensLimit == 0 && !Int32.TryParse(ConfigurationManager.AppSettings["opentokenslimit"], out openTokensLimit))
                    {
                        openTokensLimit = 0;
                    }

                    if (openTokensLimit > 0)
                    {
                        List <ClientConnections> openConnections = unitOfWork.AuditRepository.GetConnectionsByClient(x => x, clientUser.Client.id)
                                                                   .Where(x => nowDateTime >= x.TokenStartDateTimeUTC && nowDateTime <= x.TokenEndDateTimeUTC).ToList();
                        if (openConnections != null && openConnections.Count() > openTokensLimit)
                        {
                            throw new AuthenticationException("Total number of open connection per client exceeds the limit.");
                        }
                    }

                    //Set timeouts
                    int tokenTimespanSec = clientUser.Client.TokenTimeOut;
                    if (tokenTimespanSec == 0 && !Int32.TryParse(ConfigurationManager.AppSettings["timeoutseconds"], out tokenTimespanSec))
                    {
                        tokenTimespanSec = 900;
                    }

                    DateTime tokenExpiration = nowDateTime.AddSeconds(tokenTimespanSec);

                    auditLog.TokenStartDateTimeUTC = nowDateTime;
                    auditLog.TokenEndDateTimeUTC   = tokenExpiration;
                    unitOfWork.Commit();

                    //record new connection
                    var newConnection = new ClientConnections()
                    {
                        LoginUser = clientUser,
                        ConnectionClientAccount = clientUser.Client,
                        ConnectionAuditLog      = auditLog,
                        TokenStartDateTimeUTC   = nowDateTime,
                        TokenEndDateTimeUTC     = tokenExpiration
                    };
                    unitOfWork.AuditRepository.CreateClientConnectionLog(newConnection);

                    //Generate claims for the token
                    var identity = new ClaimsIdentity("JWT");
                    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    identity.AddClaim(new Claim(ClaimTypes.Email, clientUser.Email));
                    identity.AddClaim(new Claim(ClaimTypes.Expiration, tokenExpiration.ToString()));
                    identity.AddClaim(new Claim("LogId", auditId.ToString()));
                    var tokenEnd = DateTime.UtcNow.AddSeconds(tokenTimespanSec);

                    var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    context.Validated(ticket);
                }
                catch (Exception ex)
                {
                    if (ex is AuthenticationException)
                    {
                        context.SetError("invalid_grant", ex.Message);
                    }
                    else
                    {
                        context.SetError("invalid_grant", String.Format("Internal Error (Please contact Exiger support with reference ID: {0})", auditLog.Id));
                    }
                    auditLog.ErrorMessage = ex.Message;
                }
                finally
                {
                    unitOfWork.Commit();
                }
            }
            return;
        }
Esempio n. 6
0
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            AuditActivityLog auditLog = null;
            var signedAndEncodedToken = "";

            using (var unitOfWork = new UnitOfWorkFactory().Create())
            {
                var logIdClaim = data.Identity.FindFirst("LogId");
                if (logIdClaim != null)
                {
                    int logId = Int32.Parse(logIdClaim.Value);
                    data.Identity.RemoveClaim(logIdClaim);
                    auditLog = unitOfWork.AuditRepository.GetAuditActivityLogById(x => x, logId);
                }
                //The following case should never happen, but just in case, to ensure theer is always a log object
                if (auditLog == null)
                {
                    auditLog = new AuditActivityLog()
                    {
                        SenderUserID     = data.Identity.FindFirst(ClaimTypes.Name).Value,
                        SenderRequestURL = "unknown",
                        SenderIP         = "unkbnown",
                        AuditDateTime    = DateTime.Now
                    };
                    unitOfWork.AuditRepository.CreateAuditActivityLog(auditLog);
                }

                var expClaim         = data.Identity.FindFirst(ClaimTypes.Expiration);
                var tikenExpDateTime = expClaim == null?DateTime.SpecifyKind(DateTime.UtcNow.AddSeconds(900), DateTimeKind.Utc) : DateTime.SpecifyKind(DateTime.Parse(expClaim.Value), DateTimeKind.Utc);

                data.Identity.RemoveClaim(expClaim);

                //Get identity's claims passed from CustomOAuthProvider
                var claimsIdentity = new ClaimsIdentity(data.Identity.Claims);

                //Currently using a symetrical key algorithm for signing
                var signingKey         = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret));
                var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);

                //AppliesToAddress and TokenIssuerName must be valid URI’s. Not in the sense that they should be resolvable, but they must be in a valid URI format
                //The AppliesToAddress should contain the token’s audience, i.e. the website or application that will receive te token.
                //The TokenIssuerName is the application issuing the token
                var securityTokenDescriptor = new SecurityTokenDescriptor()
                {
                    AppliesToAddress   = _tokenTarget,
                    TokenIssuerName    = _tokenIssuer,
                    Subject            = claimsIdentity,
                    SigningCredentials = signingCredentials,
                };

                securityTokenDescriptor.Lifetime = new System.IdentityModel.Protocols.WSTrust.Lifetime(DateTime.UtcNow, tikenExpDateTime);
                var tokenHandler = new JwtSecurityTokenHandler();
                var plainToken   = tokenHandler.CreateToken(securityTokenDescriptor);
                signedAndEncodedToken = tokenHandler.WriteToken(plainToken);

                auditLog.AuthenticationToken = signedAndEncodedToken.ToString();

                unitOfWork.Commit();
            }
            return(signedAndEncodedToken);
        }