Пример #1
0
        public async Task <Star> CreateAsync(Star model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (model.ThingId < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(model.ThingId));
            }

            if (model.CreatedUserId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(model.CreatedUserId));
            }

            if (String.IsNullOrEmpty(model.CancellationToken))
            {
                model.CancellationToken = _keyGenerator.GenerateKey(o =>
                {
                    o.MaxLength = 100;
                });
            }

            var result = await _starRepository.InsertUpdateAsync(model);

            if (result != null)
            {
                CancelTokens(result);
            }

            return(result);
        }
        public void GenerateKeyShouldDoIt()
        {
            // Arrange
            // Act
            var key = _keyGenerator.GenerateKey();

            // Assert
            key.ShouldNotBeNull();
        }
Пример #3
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _cacheSettings = BuildCacheSettings();

            var cacheKey = _keyGenerator.GenerateKey(filterContext, _cacheSettings);

            if (_cacheSettings.IsServerCachingEnabled)
            {
                var cachedItem = _outputCacheManager.GetItem(cacheKey);

                if (cachedItem != null)
                {
                    filterContext.Result = new ContentResult
                    {
                        Content     = _donutHoleFiller.ReplaceDonutHoleContent(cachedItem.Content, filterContext),
                        ContentType = cachedItem.ContentType
                    };
                }
            }

            if (filterContext.Result == null)
            {
                var cachingWriter = new StringWriter(CultureInfo.InvariantCulture);

                var originalWriter = filterContext.HttpContext.Response.Output;

                filterContext.HttpContext.Response.Output = cachingWriter;

                filterContext.HttpContext.Items[cacheKey] = new Action <bool>(hasErrors =>
                {
                    filterContext.HttpContext.Items.Remove(cacheKey);

                    filterContext.HttpContext.Response.Output = originalWriter;

                    if (!hasErrors)
                    {
                        var cacheItem = new CacheItem
                        {
                            Content     = cachingWriter.ToString(),
                            ContentType = filterContext.HttpContext.Response.ContentType
                        };

                        filterContext.HttpContext.Response.Write(_donutHoleFiller.RemoveDonutHoleWrappers(cacheItem.Content, filterContext));

                        if (_cacheSettings.IsServerCachingEnabled && filterContext.HttpContext.Response.StatusCode == 200)
                        {
                            _outputCacheManager.AddItem(cacheKey, cacheItem, DateTime.UtcNow.AddSeconds(_cacheSettings.Duration));
                        }
                    }
                });
            }
        }
Пример #4
0
        public override async Task SetUp(
            SetUpContext context,
            Action <string, string> reportError)
        {
            // --------------------------
            // Add default settings to dictionary store
            // --------------------------

            try
            {
                var siteSettings = await _siteSettingsStore.GetAsync() ?? new SiteSettings();

                siteSettings.SiteName  = context.SiteName;
                siteSettings.SuperUser = context.AdminUsername;
                siteSettings.ApiKey    = _keyGenerator.GenerateKey();
                siteSettings.HomeRoute = new HomeRoute();
                await _siteSettingsStore.SaveAsync(siteSettings);
            }
            catch (Exception ex)
            {
                reportError(ex.Message, ex.StackTrace);
            }

            // --------------------------
            // Apply default permissions to default roles for new feature
            // --------------------------

            await _defaultRolesManager.UpdateDefaultRolesAsync(new Permissions());
        }
        protected override async Task <TResult> InterceptAsync <TResult>(IInvocation invocation, Func <Task <TResult> > proceed)
        {
            string key = _keyGenerator.GenerateKey(invocation.Method, invocation.Arguments);

            await _cache.RemoveAsync(key);

            return(default);
Пример #6
0
        public async Task <ISiteSettings> SaveAsync(ISiteSettings siteSettings)
        {
            // Automatically generate an API key if one is not supplied
            if (String.IsNullOrWhiteSpace(siteSettings.ApiKey))
            {
                siteSettings.ApiKey = _keyGenerator.GenerateKey();
            }

            // Use default homepage route if a default route is not explicitly specified
            if (siteSettings.HomeRoute == null)
            {
                siteSettings.HomeRoute = new HomeRoute();
            }

            // Update settings
            var settings = await _dictionaryStore.UpdateAsync <SiteSettings>(Key, siteSettings);

            if (settings != null)
            {
                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation($"Settings for site '{settings.SiteName}' updated successfully");
                }
                // Expire cache
                _cacheManager.CancelTokens(this.GetType(), Key);
            }

            return(settings);
        }
Пример #7
0
        public string GetShortUrl(string email, string originalUrl)
        {
            var user = _dbContext.User.Find(email);

            if (user == null)
            {
                return(null);
            }
            var obj = _dbContext.UrlMapper
                      .FirstOrDefault(l => l.Email == email && l.OriginalUrl == originalUrl);

            if (obj != null)
            {
                return(obj.ShortUrl);
            }
            // Generate Key
            var shortUrl = _keyGenerator.GenerateKey(6);

            _dbContext.UrlMapper.Add(new UrlMapper
            {
                Email       = email,
                OriginalUrl = originalUrl,
                ShortUrl    = shortUrl
            });
            _dbContext.SaveChanges();
            return(shortUrl);
        }
Пример #8
0
        /// <summary>
        /// Creates a new room, based on provided parameters.
        /// Throws exception if values are invalid.
        /// </summary>
        /// <param name="owner">IUser object - Owner of the newly created room.</param>
        /// <param name="roomName">Requested room name.</param>
        /// <param name="services">List of streamingplatforms provided initially</param>
        /// <returns>Newly created room</returns>
        public IRoom CreateRoom(IUser owner, string roomName, List <IStreamingPlatform> services)
        {
            // Null checks
            if (owner == null)
            {
                throw new ArgumentNullException("owner", "Owner must not be null.");
            }
            if (services == null)
            {
                throw new ArgumentNullException("services", "Services must not be null.");
            }

            // Value checks
            if (string.IsNullOrEmpty(roomName) || string.IsNullOrWhiteSpace(roomName))
            {
                throw new ArgumentException("roomName", "RoomName must contain a value.");
            }
            if (owner.Id == 0)
            {
                throw new ArgumentException("Owner does not contain a valid Id.", "owner");
            }
            if (services.Count < 1)
            {
                throw new ArgumentException("Services must contain at least 1 streaming platform.", "services");
            }
            if (roomName.Length < 4)
            {
                throw new ArgumentException("roomName", "RoomName must be atleast 4 characters long.");
            }


            // Fields and values
            IRoom  roomToBeCreated;
            string roomKey;

            // Create room key.
            IKeyGenerator keyGenerator = KeyGeneratorFactory.GetKeyGenerator();
            bool          keyIsUnique  = false;

            // Check that key is unique
            // Retry if the key is not unique
            do
            {
                // Generate key
                roomKey = keyGenerator.GenerateKey();

                // Check if the generated key exists.
                keyIsUnique = this._roomDAO.ValidateRoomKey(roomKey);
            } while (keyIsUnique);

            // Create room object.
            roomToBeCreated = new Room(roomName, owner, roomKey, services);

            // Generate room object on DAO
            roomToBeCreated = this._roomDAO.Create(roomToBeCreated);

            // Return created room
            return(roomToBeCreated);
        }
 public void Setup()
 {
     _fakeScenarioContext = A.Fake<IScenarioContext>();
     _fakeKeyGenerator = A.Fake<IKeyGenerator>();
     A.CallTo(() => _fakeKeyGenerator.GenerateKey(A<Type>.Ignored, A<MethodInfo>.Ignored)).Returns("testkey");
     _proxyInterceptor = new ProxyInterceptor(_fakeScenarioContext, _fakeKeyGenerator);
     _proxyGenerator = new ProxyGenerator();
 }
Пример #10
0
        public Task <string> CreateAsync(Secret secret)
        {
            var id = _keyGenerator.GenerateKey();

            _logger.LogDebug($"Creating a secret - id {id} given");
            secret.Id = id;
            _store.TryAdd(id, secret);
            return(Task.FromResult(id));
        }
Пример #11
0
        public async Task <string> InitiateAgniKaiAsync()
        {
            var ticket = await _keyGenerator.GenerateKey();

            await _vault.AddAgniKaiTicket(ticket);

            await _database.AddAgniKaiAsync(new AgniKai { Ticket = ticket });

            return(ticket);
        }
        //private ILogger _log;


        public async Task Create(
            string projectId,
            IPage page,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            var p = Page.FromIPage(page);

            p.Id           = _keyGenerator.GenerateKey(p);
            p.LastModified = DateTime.UtcNow;

            await _commands.CreateAsync(projectId, p.Id, p).ConfigureAwait(false);
        }
Пример #13
0
        public async Task <string> CreateAsync(Secret secret)
        {
            var db = GetContext();
            var id = _keyGenerator.GenerateKey();

            _logger.LogDebug($"Creating a secret - id {id} given");

            secret.Id = id;

            db.Secrets.Add(secret);
            await db.SaveChangesAsync();

            return(secret.Id);
        }
Пример #14
0
        // ------------
        // Reset App Api Key
        // ------------

        public async Task <IActionResult> ResetApiKey()
        {
            var settings = await _siteSettingsStore.GetAsync();

            if (settings == null)
            {
                return(RedirectToAction(nameof(Index)));
            }

            settings.ApiKey = _keyGenerator.GenerateKey();

            var result = await _siteSettingsStore.SaveAsync(settings);

            if (result != null)
            {
                _alerter.Success(T["Key Updated Successfully!"]);
            }
            else
            {
                _alerter.Danger(T["A problem occurred updating the settings. Please try again!"]);
            }

            return(RedirectToAction(nameof(Index)));
        }
Пример #15
0
        //private ILogger log;


        public async Task Create(
            string projectId,
            IPage page,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            //if (string.IsNullOrEmpty(page.Id)) { page.Id = Guid.NewGuid().ToString(); }

            var p = Page.FromIPage(page);

            p.Id           = _keyGenerator.GenerateKey(p);
            p.LastModified = DateTime.UtcNow;
            p.PubDate      = DateTime.UtcNow;

            await commands.CreateAsync(projectId, p.Id, p).ConfigureAwait(false);
        }
        public async Task Create(
            string projectId,
            IPost post,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            var p = Post.FromIPost(post);

            p.LastModified = DateTime.UtcNow;

            p.Id = _keyGenerator.GenerateKey(p);

            await _commands.CreateAsync(projectId, p.Id, p).ConfigureAwait(false);

            _cache.ClearListCache(projectId);
        }
Пример #17
0
        private static void CreatePgpKeyForAlice(IKeyGenerator keygen)
        {
            KeyParameters aliceparam = new KeyParameters {
                RealName       = "Alice",
                Comment        = "my comment",
                Email          = "*****@*****.**",
                ExpirationDate = DateTime.Now.AddYears(3),
                KeyLength      = KeyParameters.KEY_LENGTH_2048,
                // primary key parameters
                PubkeyAlgorithm = KeyAlgorithm.RSA,
                // the primary key algorithm MUST have the "Sign" capability
                PubkeyUsage = AlgorithmCapability.CanSign | AlgorithmCapability.CanAuth | AlgorithmCapability.CanCert,
                // subkey parameters (optional)
                SubkeyLength    = KeyParameters.KEY_LENGTH_4096,
                SubkeyAlgorithm = KeyAlgorithm.RSA,
                SubkeyUsage     = AlgorithmCapability.CanEncrypt,
                Passphrase      = "topsecret"
            };

            Console.WriteLine(
                @"Create a new PGP key for Alice.
Name: {0}
Comment: {1}
Email: {2}
Secret passphrase: {3}
Expire date: {4}
Primary key algorithm = {5} ({6} bit)
Sub key algorithm = {7} ({8} bit)",
                aliceparam.RealName,
                aliceparam.Comment,
                aliceparam.Email,
                aliceparam.Passphrase,
                aliceparam.ExpirationDate.ToString(CultureInfo.InvariantCulture),
                Gpgme.GetPubkeyAlgoName(aliceparam.PubkeyAlgorithm),
                aliceparam.PubkeyLength,
                Gpgme.GetPubkeyAlgoName(aliceparam.SubkeyAlgorithm),
                aliceparam.SubkeyLength);

            Console.Write("Start key generation.. ");

            GenkeyResult result = keygen.GenerateKey(
                Protocol.OpenPGP,
                aliceparam);

            Console.WriteLine("done.\nFingerprint: {0}\n",
                              result.Fingerprint);
        }
Пример #18
0
        public string NewGuid(string uniqueKey)
        {
            // Create a 256 bit unique ASCII string
            var key = _keyGenerator.GenerateKey(o =>
            {
                o.MaxLength        = 32;
                o.UniqueIdentifier = uniqueKey;
            });

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            // Transform to 256 bit / 32 character hexadecimal string
            return(key.ToStream(Encoding.ASCII).ToMD5().ToHex());
        }
Пример #19
0
        protected override async Task <TResult> InterceptAsync <TResult>(IInvocation invocation, Func <Task <TResult> > proceed)
        {
            string key = _keyGenerator.GenerateKey(invocation.Method, invocation.Arguments);

            byte[] cached = await _cache.GetAsync(key);

            if (cached is null || cached.Length == 0)
            {
                _logger.LogTrace("Cached value unavailable for {Method}", invocation.Method);

                var value = await proceed();

                _logger.LogTrace("Setting cached value for {Method}", invocation.Method);
                await _cache.SetAsync(key, _serializer.Serialize(value));

                return(value);
            }
Пример #20
0
        private static void CreatePgpKeyForBob(IKeyGenerator keygen)
        {
            Console.Write("Create PGP key for Bob.. ");
            KeyParameters bobparam = new KeyParameters {
                RealName       = "Bob",
                Email          = "*****@*****.**",
                ExpirationDate = DateTime.Now.AddYears(2),
                Passphrase     = "topsecret"
            };

            GenkeyResult result = keygen.GenerateKey(
                Protocol.OpenPGP,
                bobparam);

            Console.WriteLine("done.\nFingerprint: {0}\n",
                              result.Fingerprint);
        }
        public async Task Create(
            string projectId,
            IPost post,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            var p = Post.FromIPost(post);

            p.LastModified = DateTime.UtcNow;

            p.Id = _keyGenerator.GenerateKey(p);

            //if (string.IsNullOrEmpty(p.Id)) { p.Id = Guid.NewGuid().ToString(); }

            await commands.CreateAsync(projectId, p.Id, p).ConfigureAwait(false);

            cache.ClearListCache(projectId);
        }
Пример #22
0
        private async Task <WebApiSettingsViewModel> GetModel()
        {
            var settings = await _siteSettingsStore.GetAsync();

            if (settings != null)
            {
                return(new WebApiSettingsViewModel()
                {
                    ApiKey = settings.ApiKey
                });
            }

            // return default settings
            return(new WebApiSettingsViewModel()
            {
                ApiKey = _keyGenerator.GenerateKey()
            });
        }
        public async Task Create(
            string projectId,
            IPage page,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            var p = Page.FromIPage(page);

            // metaweblog sets the id, don't change it if it exists
            if (string.IsNullOrWhiteSpace(p.Id))
            {
                p.Id = _keyGenerator.GenerateKey(p);
            }

            p.LastModified = DateTime.UtcNow;

            await _commands.CreateAsync(projectId, p.Id, p).ConfigureAwait(false);
        }
Пример #24
0
        public async Task <User> UpdateAsync(User user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (user.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(user.Id));
            }

            // Generate a default api key
            if (String.IsNullOrEmpty(user.ApiKey))
            {
                user.ApiKey = _keyGenerator.GenerateKey(o =>
                {
                    o.UniqueIdentifier = user.Id.ToString();
                });
            }

            // Update alias
            user.Alias = _aliasCreator.Create(user.DisplayName);

            // transform meta data
            user.Data = await SerializeMetaDataAsync(user);

            var updatedUser = await _userRepository.InsertUpdateAsync(user);

            if (updatedUser != null)
            {
                // Cancel tokens for old user
                CancelTokens(user);
                // Cancel tokens for updated user
                CancelTokens(updatedUser);

                if (user.LoginInfos != null)
                {
                }
            }

            return(updatedUser);
        }
Пример #25
0
        private static void CreatePgpKeyForMallory(IKeyGenerator keygen)
        {
            Console.Write("Create PGP key for Mallory.. ");

            KeyParameters malloryparam = new KeyParameters {
                RealName = "Mallory",
                Email    = "*****@*****.**"
            };

            malloryparam.MakeInfinitely(); // PGP key does not expire
            malloryparam.Passphrase = "topsecret";

            GenkeyResult result = keygen.GenerateKey(
                Protocol.OpenPGP,
                malloryparam);

            Console.WriteLine("done.\nFingerprint: {0}",
                              result.Fingerprint);
        }
Пример #26
0
        public async Task <UrlMapping> GenerateTinyUrl(string url)
        {
            try
            {
                //check in cache
                _cache.TryGetValue(url, out UrlMapping urlMapping);
                if (urlMapping != null)
                {
                    return(urlMapping);
                }

                //check in db
                var result = await IsUrlExits(url);

                if (result.Item2)
                {
                    return(result.Item1);
                }

                var lastInsertedId = await GetLastId();

                var code = _keyGenerator.GenerateKey(lastInsertedId + 1);

                urlMapping = new UrlMapping {
                    Code = code, Url = url
                };
                var now = DateTime.Now;

                await InsertAsync(urlMapping);

                await _context.SaveChangesAsync();

                return(urlMapping);
            }
            catch (System.Exception)
            {
                _logger.LogError("Error while generating tiny url");
                throw;
            }
        }
Пример #27
0
        public override async Task <IViewProviderResult> BuildEditAsync(Article entity, IViewProviderContext context)
        {
            if (entity == null)
            {
                return(await BuildIndexAsync(new Article(), context));
            }

            var entityId    = entity.Id;
            var contentGuid = string.Empty;
            var user        = await _contextFacade.GetAuthenticatedUserAsync();

            // Use posted guid if available
            var postedGuid = PostedGuidValue();

            if (!string.IsNullOrEmpty(postedGuid))
            {
                contentGuid = postedGuid;
            }
            else
            {
                // Create a new temporary 256 bit unique ASCII string
                var key = _keyGenerator.GenerateKey(o =>
                {
                    o.MaxLength        = 32;
                    o.UniqueIdentifier = $"{user.Id.ToString()}-{entity.Id.ToString()}";
                });
                // Convert to 256 bit / 32 character hexadecimal string
                contentGuid = key.ToStream(Encoding.ASCII).ToMD5().ToHex();
            }

            return(Views(
                       View <EntityAttachmentOptions>("Attachments.Edit.Sidebar", model =>
            {
                model.EntityId = entityId;
                model.Guid = contentGuid;
                model.GuidHtmlName = GuidHtmlName;
                return model;
            }).Zone("sidebar").Order(1)
                       ));
        }
Пример #28
0
        public async Task <GenerateLinkModel> Handle(GeneratePasswordLinkRequest request, CancellationToken cancellationToken)
        {
            var key = _keyGenerator.GenerateKey();

            var passwordGroup = new PasswordGroup
            {
                Id        = Guid.NewGuid(),
                Passwords = request.Passwords.Select(password => Handle(password, key)).ToArray(),
            };

            var expiration = TimeSpan.FromSeconds(request.ExpiresIn);

            _logger.Information("Create new group {@group} for {@expiration}", passwordGroup, expiration);

            var redisClient = _redisClientFactory.GetClient();
            await redisClient.SetAsync(new PasswordGroupKey(passwordGroup.Id), passwordGroup, expiration);

            return(new GenerateLinkModel
            {
                Key = _keyGenerator.ToString(key),
                PasswordGroupId = passwordGroup.Id
            });
        }
Пример #29
0
        private void GenerateLocalEphemeralAndProcessRemotePublicKey(ReadOnlySpan <byte> publicKey, IBufferWriter <byte> output)
        {
            Span <byte> outputText = output.GetSpan(50);

            Span <byte> ephemeralPublicKey = outputText.Slice(1, 33);
            Span <byte> cipher             = outputText.Slice(34, 16);

            HandshakeContext.EphemeralPrivateKey = _keyGenerator.GenerateKey();

            _keyGenerator.GetPublicKey(HandshakeContext.EphemeralPrivateKey)
            .CopyTo(ephemeralPublicKey);

            _hasher.Hash(HandshakeContext.Hash, ephemeralPublicKey, HandshakeContext.Hash);

            var es = _curveActions.Multiply(HandshakeContext.EphemeralPrivateKey, publicKey);

            ExtractNextKeys(es);

            _aeadConstruction.EncryptWithAd(HandshakeContext.Hash, null, cipher);

            _hasher.Hash(HandshakeContext.Hash, cipher, HandshakeContext.Hash);

            output.Advance(50);
        }
        /// <summary>
        /// Called before an action method executes.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            CacheSettings = BuildCacheSettings();

            var cacheKey = KeyGenerator.GenerateKey(filterContext, CacheSettings);

            // If we are unable to generate a cache key it means we can't do anything
            if (string.IsNullOrEmpty(cacheKey))
            {
                return;
            }

            // Are we actually storing data on the server side ?
            if (CacheSettings.IsServerCachingEnabled)
            {
                CacheItem cachedItem = null;

                // If the request is a POST, we lookup for NoCacheLookupForPosts option
                // We are fetching the stored value only if the option has not been set and the request is not a POST
                if (
                    (CacheSettings.Options & OutputCacheOptions.NoCacheLookupForPosts) != OutputCacheOptions.NoCacheLookupForPosts ||
                    filterContext.HttpContext.Request.HttpMethod != "POST"
                    )
                {
                    cachedItem = OutputCacheManager.GetItem(cacheKey);
                }

                // We have a cached version on the server side
                if (cachedItem != null)
                {
                    // We inject the previous result into the MVC pipeline
                    // The MVC action won't execute as we injected the previous cached result.
                    filterContext.Result = new ContentResult
                    {
                        Content     = DonutHoleFiller.ReplaceDonutHoleContent(cachedItem.Content, filterContext, CacheSettings.Options),
                        ContentType = cachedItem.ContentType
                    };
                    // we already injected something to Result, let's exit
                    return;
                }
            }


            // We are hooking into the pipeline to replace the response Output writer
            // by something we own and later eventually gonna cache
            var cachingWriter = new StringWriter(CultureInfo.InvariantCulture);

            var originalWriter = filterContext.HttpContext.Response.Output;

            filterContext.HttpContext.Response.Output = cachingWriter;

            // Will be called back by OnResultExecuted -> ExecuteCallback
            filterContext.HttpContext.Items[cacheKey] = new Action <bool>(hasErrors =>
            {
                // Removing this executing action from the context
                filterContext.HttpContext.Items.Remove(cacheKey);

                // We restore the original writer for response
                filterContext.HttpContext.Response.Output = originalWriter;

                if (hasErrors)
                {
                    return; // Something went wrong, we are not going to cache something bad
                }

                // Now we use owned caching writer to actually store data
                var cacheItem = new CacheItem
                {
                    Content     = cachingWriter.ToString(),
                    ContentType = filterContext.HttpContext.Response.ContentType
                };

                filterContext.HttpContext.Response.Write(
                    DonutHoleFiller.RemoveDonutHoleWrappers(cacheItem.Content, filterContext, CacheSettings.Options)
                    );

                if (CacheSettings.IsServerCachingEnabled && filterContext.HttpContext.Response.StatusCode == 200)
                {
                    OutputCacheManager.AddItem(cacheKey, cacheItem, DateTime.UtcNow.AddSeconds(CacheSettings.Duration));
                }
            });
        }
Пример #31
0
        public static void Initialize(
            ApplicationDbContext db,
            UserManager <ApplicationUser> userManager,
            IKeyGenerator keyGenerator)
        {
            // Database
            db.Database.EnsureCreated();

            if (db.Users.Any())
            {
                return;
            }

            // Users
            //var user1 = new ApplicationUser
            //{
            //    FirstName = "Natan",
            //    LastName = "Tapia",
            //    UserName = "******",
            //    Email = "*****@*****.**"
            //};
            //userManager.CreateAsync(user1, "Test-1234");

            //var user2 = new ApplicationUser
            //{
            //    FirstName = "Emily",
            //    LastName = "Tapia",
            //    UserName = "******",
            //    Email = "*****@*****.**"
            //};
            //userManager.CreateAsync(user2, "Test-1234");

            //var user3 = new ApplicationUser
            //{
            //    FirstName = "Wesley",
            //    LastName = "Figueroa",
            //    UserName = "******",
            //    Email = "*****@*****.**"
            //};
            //userManager.CreateAsync(user3, "Test-1234");

            var users = new ApplicationUser[10];

            for (int i = 0; i <= users.GetUpperBound(0); i++)
            {
                users[i] = new ApplicationUser
                {
                    FirstName = "User",
                    LastName  = i.ToString("0"),
                    UserName  = "******" + i.ToString() + "@test.com",
                    Email     = "test" + i.ToString() + "@test.com"
                };
                userManager.CreateAsync(users[i], "Test-1234").Wait();
            }
            db.SaveChanges();

            // Groups
            var groups = new Group[]
            {
                new Group
                {
                    Id   = keyGenerator.GenerateKey(),
                    Name = "Metrowest",
                    UsersCanScheduleOthers = true,
                    Members = new Member[]
                    {
                        new Member
                        {
                            User     = users[0],
                            Role     = GroupRole.Administrator,
                            Approved = true
                        },
                        new Member
                        {
                            User     = users[2],
                            Role     = GroupRole.Publisher,
                            Approved = true
                        },
                        new Member
                        {
                            User     = users[1],
                            Role     = GroupRole.Publisher,
                            Approved = true
                        },
                        new Member
                        {
                            User     = users[3],
                            Role     = GroupRole.Assistant,
                            Approved = true
                        },
                        new Member
                        {
                            User     = users[4],
                            Role     = GroupRole.Publisher,
                            Approved = false
                        },
                        new Member
                        {
                            User     = users[5],
                            Role     = GroupRole.Publisher,
                            Approved = false
                        },
                        new Member
                        {
                            User     = users[6],
                            Role     = GroupRole.Publisher,
                            Approved = false
                        },
                        new Member
                        {
                            User     = users[7],
                            Role     = GroupRole.Publisher,
                            Approved = false
                        }
                    },
                    Locations = new Location[]
                    {
                        new Location
                        {
                            Name = "Location 0-0"
                        },
                        new Location
                        {
                            Name = "Location 0-3"
                        },
                        new Location
                        {
                            Name = "Location 0-2"
                        },
                        new Location
                        {
                            Name = "Location 0-1"
                        },
                    }
                },
                new Group
                {
                    Id   = keyGenerator.GenerateKey(),
                    Name = "MCO Airport",
                    UsersCanScheduleOthers = true,
                    Members = new Member[]
                    {
                        new Member
                        {
                            User     = users[0],
                            Role     = GroupRole.Publisher,
                            Approved = true
                        },
                        new Member
                        {
                            User     = users[1],
                            Role     = GroupRole.Administrator,
                            Approved = true
                        }
                    },
                    Locations = new Location[]
                    {
                        new Location
                        {
                            Name = "Location 1-0"
                        },
                        new Location
                        {
                            Name = "Location 1-1"
                        }
                    }
                },
                new Group
                {
                    Id   = keyGenerator.GenerateKey(),
                    Name = "Port Canaveral",
                    UsersCanScheduleOthers = true,
                    Members = new Member[]
                    {
                        new Member
                        {
                            User     = users[0],
                            Role     = GroupRole.Publisher,
                            Approved = false
                        },
                        new Member
                        {
                            User     = users[1],
                            Role     = GroupRole.Administrator,
                            Approved = true
                        }
                    }
                }
            };

            foreach (Group g in groups)
            {
                db.Groups.Add(g);
            }

            db.SaveChanges();
        }