コード例 #1
0
        public async Task <IActionResult> RegisterAsync(UserRegister data)
        {
            var user = new ApplicationUser
            {
                UserName    = data.UserName,
                Email       = data.Email,
                DateOfBirth = data.DateofBirth,
                FirstName   = data.FirstName,
                LastName    = data.LastName,
                PhoneNumber = ExtractPhoneNumber.RemoveNonNumeric(data.PhoneNumber),
                AccountType = AccountType.Regular,
                Gender      = data.Gender
            };
            var result = await _userManager.CreateAsync(user, data.Password);

            if (result.Succeeded)
            {
                _logger.LogInformation("New user created.");
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                await _emailSender.SendEmailConfirmationAsync(data.Email, callbackUrl);

                return(Ok());
            }
            return(BadRequest());
        }
コード例 #2
0
        public async Task <IActionResult> Index(IndexViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var email = user.Email;

            if (model.Email != email)
            {
                var setEmailResult = await _userManager.SetEmailAsync(user, model.Email);

                if (!setEmailResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
                }
            }

            var phoneNumber = user.PhoneNumber;

            if (ExtractPhoneNumber.RemoveNonNumeric(model.PhoneNumber) != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, ExtractPhoneNumber.RemoveNonNumeric(model.PhoneNumber));

                if (!setPhoneResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting phone number for user with ID '{user.Id}'.");
                }
            }

            StatusMessage = "Your profile has been updated";
            return(RedirectToAction(nameof(Index)));
        }
コード例 #3
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName    = model.DisplayName,
                    Email       = model.Email,
                    DateOfBirth = model.DateOfBirth,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    PhoneNumber = ExtractPhoneNumber.RemoveNonNumeric(model.PhoneNumber),
                    AccountType = AccountType.Regular
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation("User created a new account with password.");
                    return(RedirectToLocal(returnUrl));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #4
0
        public async Task InitializeMockUsers(IServiceProvider serviceProvider)
        {
            _userManager = serviceProvider.GetRequiredService <UserManager <ApplicationUser> >();
            _context     = serviceProvider.GetRequiredService <ApplicationDbContext>();
            _hexagonal   = serviceProvider.GetRequiredService <IHexagonal>();

            //create the mock users if they don't exist
            var mock = await _userManager.FindByEmailAsync("*****@*****.**");

            if (mock == null)
            {
                for (int i = 1; i <= 25; ++i)
                {
                    string mockFirst  = String.Format("Mock{0}", i.ToString("D2"));
                    string mockLast   = String.Format("Data{0}", i.ToString("D2"));
                    string mockMail   = String.Format("{0}@RyanRauch.com", mockFirst);
                    string mockNumber = String.Format("55512300{0}", i.ToString("D2"));
                    string mockPass   = String.Format("Password{0}!", i.ToString("D2"));
                    var    user       = new ApplicationUser
                    {
                        UserName    = mockFirst + mockLast,
                        Email       = mockMail,
                        DateOfBirth = DateTime.Now.Date.AddYears(-30).Subtract(TimeSpan.FromDays(30 * i)),
                        FirstName   = mockFirst,
                        LastName    = mockLast,
                        PhoneNumber = ExtractPhoneNumber.RemoveNonNumeric(mockNumber),
                        AccountType = AccountType.MockedData,
                        Gender      = i % 2 == 0 ? AccountGender.Male : AccountGender.Female
                    };
                    var result = await _userManager.CreateAsync(user, mockPass);
                }
            }

            //update current location data for mock users
            /////////////////////////////////////////////
            double latmin      = 30.3740;
            double latmax      = 30.4251;
            double lonmin      = -97.7501;
            double lonmax      = -97.7001;
            Random randomLat   = new Random((int)DateTime.Now.Ticks);
            Random randomLon   = new Random((int)DateTime.Now.Ticks);
            Random randomMin   = new Random((int)DateTime.Now.Ticks);
            var    mockedUsers = await _context.ApplicationUser.Where(a => a.AccountType.Equals(AccountType.MockedData)).ToListAsync();

            foreach (var user in mockedUsers)
            {
                DateTime timeStamp = DateTime.Now.Subtract(TimeSpan.FromMinutes(randomMin.NextDouble() * 60));
                double   lat       = randomLat.NextDouble() * (latmax - latmin) + latmin;
                double   lon       = randomLon.NextDouble() * (lonmax - lonmin) + lonmin;
                user.CurrentTimeStamp = timeStamp;
                user.CurrentLatitude  = lat;
                user.CurrentLongitude = lon;
                _hexagonal.Initialize(lat, lon, _hexagonal.Layers[0]);
                String layers       = _hexagonal.AllLayersDelimited();
                var    currentLayer = await _context.CurrentLayers.FirstOrDefaultAsync(c => c.UserId.Equals(user.Id));

                if (currentLayer == null)
                {
                    await _context.CurrentLayers.AddAsync(new CurrentLayer()
                    {
                        UserId          = user.Id,
                        LayersDelimited = layers,
                        TimeStamp       = timeStamp
                    });
                }
                else
                {
                    currentLayer.LayersDelimited = layers;
                    currentLayer.TimeStamp       = timeStamp;
                }
            }
            await _context.SaveChangesAsync();

            //establish friend-requests for all of the mock users
            //////////////////////////////////////////
            var ryan = await _context.ApplicationUser
                       .FirstOrDefaultAsync(a => a.Email.Equals("*****@*****.**", StringComparison.OrdinalIgnoreCase));

            mockedUsers = await _context.ApplicationUser
                          .Where(a => a.AccountType.Equals(AccountType.MockedData))
                          .ToListAsync();

            foreach (var initiator in mockedUsers)
            {
                DateTime timeStamp     = DateTime.Now.Subtract(TimeSpan.FromMinutes(randomMin.NextDouble() * 60));
                var      friendRequest = await _context.FriendRequests
                                         .FirstOrDefaultAsync(f => f.InitiatorId.Equals(initiator.Id) &&
                                                              f.TargetId.Equals(ryan.Id));

                if (friendRequest == null)
                {
                    await _context.FriendRequests
                    .AddAsync(new FriendRequest()
                    {
                        InitiatorId = initiator.Id,
                        TargetId    = ryan.Id,
                        TimeStamp   = DateTime.Now,
                        Type        = FriendRequestType.Normal
                    });
                }
                else
                {
                    friendRequest.TimeStamp = timeStamp;
                }
            }
            await _context.SaveChangesAsync();
        }