コード例 #1
0
        public async Task <LoggedInUser> GetLoggedInUserAsync(Guid loggedInUserId)
        {
            var cacheKey = WebCacheKey.LoggedInUser(loggedInUserId);
            var expiry   = TimeSpan.FromHours(1);

            var loggedInUser = await _cache.GetWithSlidingExpirationAsync <LoggedInUser>(cacheKey, expiry);

            if (loggedInUser != null)
            {
                return(loggedInUser);
            }

            try
            {
                var commonUser = await _commonCtx.Users.SingleOrDefaultAsync(u => u.Id == loggedInUserId);

                if (commonUser == null)
                {
                    _logger.Error($"No matching {nameof(CommonUser)} record for loggedInUserId={loggedInUserId}");
                    return(null);
                }

                loggedInUser = Mapper.Map <LoggedInUser>(commonUser);

                await _cache.SetAsync(cacheKey, loggedInUser, expiry);
            }
            catch (Exception ex)
            {
            }

            return(loggedInUser);
        }
コード例 #2
0
        /// <summary>
        /// Looks for the accountuser in cache.  If it doesn't exists, looks for accountuser in database.  If found, adds it to cache.
        /// </summary>
        public async Task <CommonUserAccountModel> GetCommonAccountUserAsync(long accountNumber, Guid userId)
        {
            var cacheKey = WebCacheKey.CommonUserAccount(accountNumber, userId);
            var expiry   = TimeSpan.FromHours(24);

            // Try to pull it from the cache first.
            var commonUserAccountModel = await _cache.GetWithSlidingExpirationAsync <CommonUserAccountModel>(cacheKey, expiry);

            if (commonUserAccountModel != null)
            {
                return(commonUserAccountModel);
            }

            var commonUserAccount = await _commonContext.UserAccounts
                                    .AsNoTracking()
                                    .SingleOrDefaultAsync(cua => cua.UserId == userId && cua.Account.Number == accountNumber);

            if (commonUserAccount != null)
            {
                commonUserAccountModel = Mapper.Map <CommonUserAccountModel>(commonUserAccount);

                // Found it. Add it to the cache.
                await _cache.SetAsync(cacheKey, commonUserAccountModel, expiry);
            }

            return(commonUserAccountModel);
        }
コード例 #3
0
        public async Task <IActionResult> Edit(AccountUserViewModelEdit model)
        {
            if (ModelState.IsValid)
            {
                var existingUser = await CommonContext.UserAccounts.Include(x => x.User)
                                   .Where(m => m.UserId == model.UserId && m.AccountId == CommonAccount.Id).SingleOrDefaultAsync();

                if (existingUser == null)
                {
                    throw new Exception($"User cannot be found. UserId:{model.UserId}");
                }

                if (User.GetLoggedInUserId().Value == model.UserId && !model.Permissions.HasFlag(AccountPermissions.AccountAdministrator))
                {
                    ModelState.AddModelError(string.Empty, "You cannot remove the Account Administrator permission");
                    model.FirstName = existingUser.User.FirstName;
                    model.LastName  = existingUser.User.LastName;
                    model.Email     = existingUser.User.Email;
                    return(View(model));
                }

                if (User.GetLoggedInUserId().Value == model.UserId && model.Disabled)
                {
                    ModelState.AddModelError(string.Empty, "You cannot disable your own account");
                    model.FirstName = existingUser.User.FirstName;
                    model.LastName  = existingUser.User.LastName;
                    model.Email     = existingUser.User.Email;
                    return(View(model));
                }

                existingUser.Permissions  = model.Permissions;
                existingUser.Disabled     = model.Disabled;
                existingUser.UpdateUserId = LoggedInUser.Id;
                existingUser.UpdateUtc    = DateTime.UtcNow;

                using (var tx = CommonContext.Database.BeginTransaction())
                {
                    CommonContext.UserAccounts.Update(existingUser);
                    await CommonContext.SaveChangesAsync();

                    tx.Commit();

                    var cacheKey = WebCacheKey.CommonUserAccount(CommonAccount.Number, existingUser.UserId.Value);
                    await _cache.RemoveAsync(cacheKey);
                }

                return(RedirectToAction("Users"));
            }

            return(View(model));
        }
コード例 #4
0
        /// <summary>
        /// Look for <see cref="Data.Models.Common.CommonAccount" /> in cache. If found, return it. If not found,
        /// load it from the database and cache it.
        /// </summary>
        /// <param name="accountNumber"></param>
        /// <returns></returns>
        public async Task <CachedAccount> GetCachedAccountAsync(long accountNumber)
        {
            var cacheKey = WebCacheKey.CommonAccount(accountNumber);

            // Try to pull it from the cache first.
            var cachedAccount = await _cache.GetWithSlidingExpirationAsync <CachedAccount>(cacheKey, _commonAccountCacheExpiry);

            if (cachedAccount != null)
            {
                return(cachedAccount);
            }

            // Not in cache. Check the database.
            var commonAccount = await _commonCtx.CommonAccounts.AsNoTracking()
                                .Include(ca => ca.Partition)
                                .Include(ca => ca.Settings)
                                .Include(ca => ca.City)
                                .Include(ca => ca.CommonAccountViolationTypes)
                                .SingleOrDefaultAsync(ca => ca.Number == accountNumber);

            if (commonAccount == null)
            {
                // Account not found.
                return(null);
            }

            cachedAccount = Mapper.Map <CachedAccount>(commonAccount);

            var commonViolationTypes = await _commonCtx.CommonAccountViolationTypes.Where(m => m.AccountId == commonAccount.Id).Select(m => m.ViolationTypeId).ToListAsync();

            var accountCtx     = ContextsUtility.CreateAccountContext(Cryptography.Decrypt(commonAccount.Partition.ConnectionString));
            var violationTypes = await accountCtx.ViolationTypes.ForAccount(commonAccount.Id).Where(m => commonViolationTypes.Contains(m.CommonViolationTypeId)).ToListAsync();


            cachedAccount.ViolationTypes = Mapper.Map <ViolationTypeModel[]>(violationTypes);


            // Found it. Add it to the cache.
            await _cache.SetAsync(cacheKey, cachedAccount, _commonAccountCacheExpiry);

            return(cachedAccount);
        }
コード例 #5
0
        public async Task <IActionResult> PurgeCache()
        {
            var accountUsers = await CommonContext.UserAccounts.Include(m => m.Account).AsNoTracking().ToListAsync();

            var cachKeys = new List <string>();

            var accounts = accountUsers.Select(m => m.Account).Distinct();

            //CommonAccounts
            foreach (var account in accounts)
            {
                cachKeys.Add(WebCacheKey.CommonAccount(account.Number));
            }
            cachKeys.Add(WebCacheKey.CommonAccounts);

            //Account Users
            foreach (var accountUser in accountUsers)
            {
                cachKeys.Add(WebCacheKey.CommonUserAccount(accountUser.Account.Number, accountUser.UserId.Value));
            }


            var users = await CommonContext.Users.Select(m => m.Id).ToListAsync();

            foreach (var user in users)
            {
                cachKeys.Add(WebCacheKey.LoggedInUser(user));
            }

            cachKeys.Add(WebCacheKey.HealthCheck);
            cachKeys.Add(WebCacheKey.CommonViolationTypes);
            cachKeys.Add(WebCacheKey.CommonViolationCategories);
            cachKeys.Add(WebCacheKey.CommonViolations);
            cachKeys.Add(WebCacheKey.Violations);

            await _cache.RemoveAsync(cachKeys.ToArray());

            return(RedirectToAction("Index"));
        }
コード例 #6
0
        public async Task <List <CachedAccountViolations> > GetCachedAccountViolations(Guid accountId)
        {
            //First we need to get the correct cache key
            var cacheKey = WebCacheKey.AccountViolations(accountId);

            //Then we need to set the cache expiration time.
            var expiry = TimeSpan.FromMinutes(15);

            var cachedViolations = await _cache.GetWithSlidingExpirationAsync <List <CachedAccountViolations> >(cacheKey, expiry);

            if (cachedViolations == null)
            {
                var violations = await _accountCtx.Violations.ForAccount(accountId)
                                 .Include(m => m.Category).ThenInclude(m => m.Type)
                                 .ToListAsync();

                cachedViolations = Mapper.Map <List <CachedAccountViolations> >(violations);

                // Found it. Add it to the cache.
                await _cache.SetAsync(cacheKey, cachedViolations, expiry);
            }

            return(cachedViolations);
        }
コード例 #7
0
 protected async Task PurgeLoggedInUser(Guid id)
 {
     var cacheKey = WebCacheKey.LoggedInUser(id);
     await _cache.RemoveAsync(cacheKey);
 }
コード例 #8
0
 protected async Task PurgeAccountViolation(Guid accountId)
 {
     var cacheKey = WebCacheKey.AccountViolations(accountId);
     await _cache.RemoveAsync(cacheKey);
 }
コード例 #9
0
        /// <summary>
        /// Update an existing Account in the Common and Account partitions.
        /// Also update a user in the Account Partition.
        /// </summary>
        /// <param name="commonAccount"></param>
        /// <param name="createdById"></param>
        /// <returns></returns>
        public async Task <ServiceResponse <CommonAccount> > UpdateAccount(CommonAccount commonAccount, Guid createdById, int AccountNumber, List <AccountViolationType> AccViolationType)
        {
            var result = new ServiceResponse <CommonAccount>();

            try
            {
                using (var scope = _commonCtx.Database.BeginTransaction())
                {
                    //update common account table
                    var accountDetail = await _commonCtx.CommonAccounts.Include(m => m.Partition).Include(m => m.Settings).SingleOrDefaultAsync(a => a.Id == commonAccount.Id);


                    var accountCtx = ContextsUtility.CreateAccountContext(Cryptography.Decrypt(accountDetail.Partition.ConnectionString));


                    accountDetail.UpdateUserId      = createdById;
                    accountDetail.UpdateUtc         = DateTime.Now;
                    accountDetail.Name              = commonAccount.Name;
                    accountDetail.OwnerUserId       = commonAccount.OwnerUserId;
                    accountDetail.StorageBucketName = commonAccount.StorageBucketName;
                    accountDetail.CitationWorkflow  = commonAccount.CitationWorkflow;
                    accountDetail.Features          = commonAccount.Features;

                    _commonCtx.CommonAccounts.Update(accountDetail);
                    await _commonCtx.SaveChangesAsync();


                    //update accounts table from selected partition
                    var AccountsDetail = await accountCtx.Accounts.SingleOrDefaultAsync(a => a.Id == commonAccount.Id);

                    AccountsDetail.Name         = commonAccount.Name;
                    AccountsDetail.UpdateUserId = createdById;
                    AccountsDetail.UpdateUtc    = DateTime.UtcNow;

                    accountCtx.Accounts.Update(AccountsDetail);
                    await accountCtx.SaveChangesAsync();

                    //update user accounts table
                    if (commonAccount.OwnerUserId != null)
                    {
                        //Check to see if the owner exists in the User Account Table.
                        var userAccount = await _commonCtx.UserAccounts.SingleOrDefaultAsync(a => a.AccountId == commonAccount.Id && a.UserId == commonAccount.OwnerUserId);

                        if (userAccount == null)
                        {
                            CommonUserAccount NewuserAccount = new CommonUserAccount();
                            NewuserAccount.CreateUserId = createdById;
                            NewuserAccount.AccountId    = commonAccount.Id;
                            NewuserAccount.UpdateUserId = createdById;
                            NewuserAccount.UserId       = commonAccount.OwnerUserId;
                            NewuserAccount.Permissions  = (AccountPermissions)Enum.GetValues(typeof(AccountPermissions)).Cast <int>().Sum();

                            _commonCtx.UserAccounts.Add(NewuserAccount);

                            await _commonCtx.SaveChangesAsync();

                            var commonUser = await _commonCtx.Users.SingleAsync(m => m.Id == commonAccount.OwnerUserId);

                            //Add any new users to acconts
                            await SaveAccountUser(commonUser, createdById);
                        }
                    }


                    //Remove the current violation types
                    var AccountViolationType = await _commonCtx.CommonAccountViolationTypes.Where(av => av.AccountId == commonAccount.Id).ToListAsync();

                    _commonCtx.CommonAccountViolationTypes.RemoveRange(AccountViolationType);
                    await _commonCtx.SaveChangesAsync();


                    //Add new violatoin types from the page
                    foreach (var Types in AccViolationType)
                    {
                        if (Types.IsCheckedViolation == true)
                        {
                            CommonAccountViolationType AcntViolationType = new CommonAccountViolationType();
                            AcntViolationType.CreateUserId    = createdById;
                            AcntViolationType.AccountId       = commonAccount.Id;
                            AcntViolationType.UpdateUserId    = createdById;
                            AcntViolationType.ViolationTypeId = Types.TypeId;

                            _commonCtx.CommonAccountViolationTypes.Add(AcntViolationType);
                            await _commonCtx.SaveChangesAsync();
                        }
                    }
                    scope.Commit();

                    //Purge common accounts cache
                    var cacheKey = WebCacheKey.CommonAccount(accountDetail.Number);
                    await _cache.RemoveAsync(cacheKey);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error updating an Account");

                throw ex;
            }

            return(result);
        }
コード例 #10
0
        public async Task <IActionResult> UpdateProfile([FromBody] UserModel model)
        {
            var response = new APIResponse <UserModel>();

            if (ModelState.IsValid)
            {
                // if user is trying to update someone else profile.
                if (User.GetJWTLoggedInUserId() != model.Id)
                {
                    response.Success = false;
                    response.Errors.Add(new Error {
                        Code = 0, Message = "Invalid ID"
                    });
                    return(Ok(response));
                }



                var userAlreadyExists = await CommonContext.Users.AsNoTracking().AnyAsync(q => q.Email.ToLower() == model.Email.ToLower() && q.Id != model.Id);

                if (userAlreadyExists)
                {
                    // This isn't a security risk because we've verified the email address already
                    response.Success = false;
                    response.Errors.Add(new Error {
                        Code = 0, Message = "A user has already verified that email address."
                    });
                    return(Ok(response));
                }
                var user = await CommonContext.Users.SingleAsync(m => m.Id == model.Id);

                user.Email           = model.Email;
                user.FirstName       = model.FirstName;
                user.LastName        = model.LastName;
                user.PhoneNumber     = model.PhoneNumber;
                user.ProfileImageKey = model.profileImageKey;


                if (!string.IsNullOrWhiteSpace(model.Password))
                {
                    user.SetPassword(model.Password);
                }

                CommonContext.Users.Update(user);
                await CommonContext.SaveChangesAsync();

                //Update user information in all other accounts
                await _commonAccountSvc.SaveAccountUser(user, model.Id);

                //purge the user cache
                var cacheKey = WebCacheKey.LoggedInUser(model.Id);
                await _cache.RemoveAsync(cacheKey);

                response.Message = "Your profile has been updated";
            }
            else
            {
                response.Success = false;
                response.Errors.AddRange(ModelState.ToErrors());
            }

            return(Ok(response));
        }