コード例 #1
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,AspnetIdentityId,FirstName,LastName")] FujiUser fujiUser)
        {
            if (id != fujiUser.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(fujiUser);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!FujiUserExists(fujiUser.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(fujiUser));
        }
コード例 #2
0
        /// <summary>
        /// Initialize an admin user and role
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="email"></param>
        /// <param name="userName"></param>
        /// <param name="adminPw"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <returns></returns>
        public static async Task InitializeAdmin(IServiceProvider serviceProvider, string email, string userName, string adminPw, string firstName, string lastName)
        {
            try
            {
                using (var context = new FujiDbContext(serviceProvider.GetRequiredService <DbContextOptions <FujiDbContext> >()))
                {
                    // Get the Identity user manager
                    var userManager = serviceProvider.GetRequiredService <UserManager <IdentityUser> >();
                    // Ensure the admin user exists
                    var identityID = await EnsureUser(userManager, adminPw, email, email, true);

                    // Create a new FujiUser if this one doesn't already exist
                    FujiUser fu = new FujiUser {
                        AspnetIdentityId = identityID, FirstName = firstName, LastName = lastName
                    };
                    if (!context.FujiUsers.Any(x => x.AspnetIdentityId == fu.AspnetIdentityId && x.FirstName == fu.FirstName && x.LastName == fu.LastName))
                    {
                        // Doesn't already exist, so add a new user
                        context.Add(fu);
                        await context.SaveChangesAsync();
                    }
                    // Now make sure admin role exists and give it to this user
                    var roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();
                    await EnsureRoleForUser(roleManager, userManager, identityID, "admin");
                }
            }
            catch (InvalidOperationException ex)
            {
                // Thrown if there is no service of the type requested from the service provider
                // Catch it (and don't throw the exception below) if you don't want it to fail (5xx status code)
                throw new Exception("Failed to initialize admin user or role, service provider did not have the correct service:" + ex.Message);
            }
        }
コード例 #3
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    // Check and see if the id was set in the IdentityUser object when it was successfully created
                    _logger.LogInformation($"User created a new account with password, id is {user.Id}");

                    // Create one of our users
                    FujiUser fu = new FujiUser
                    {
                        AspnetIdentityId = user.Id,     // get the aspnet id of the newly created identity user
                        FirstName        = Input.FirstName,
                        LastName         = Input.LastName
                    };
                    _fujiDbContext.Add(fu);
                    await _fujiDbContext.SaveChangesAsync();

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
コード例 #4
0
        public async Task <IActionResult> Create([Bind("Id,AspnetIdentityId,FirstName,LastName")] FujiUser fujiUser)
        {
            if (ModelState.IsValid)
            {
                _context.Add(fujiUser);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(fujiUser));
        }
コード例 #5
0
        // Note: can be forged as we don't have an anti forgery token.  Will need to add this
        public async Task <JsonResult> Ate(int?id)
        {
            // verify id is actually a real apple
            if (id == null)
            {
                return(Json(new { success = false, message = "id expected" }));
            }
            //if (!AppleExists((int)id))
            if (!await _appleRepo.ExistsAsync((int)id))
            {
                return(Json(new { success = false, message = "appleID not found" }));
            }

            // and that we have a logged in user
            string aspNetUserID = _userManager.GetUserId(User);

            if (aspNetUserID == null)
            {
                return(Json(new { success = false, message = "user not logged in" }));
            }
            FujiUser fu = null;

            if (aspNetUserID != null)
            {
                //fu = _context.FujiUsers.Where(u => u.AspnetIdentityId == aspNetUserID).FirstOrDefault();
                fu = _fuRepo.GetFujiUserByIdentityId(aspNetUserID);
                if (fu == null)
                {
                    return(Json(new { success = false, message = "user not found" }));
                }
            }

            // Now we have a verified Apple and a verified User.  Let that user eat that apple!

            /*ApplesConsumed appleCore = new ApplesConsumed {
             *  Apple = await _context.Apples.FirstOrDefaultAsync(a => a.Id == id),
             *  FujiUser = fu,
             *  ConsumedAt = DateTime.UtcNow,
             *  Count = 1
             * };
             * _context.Add(appleCore);
             * await _context.SaveChangesAsync();
             */
            await _fuRepo.EatAsync(fu, (int)id, DateTime.UtcNow);

            return(Json(new { success = true, message = "user ate apple" }));
        }
コード例 #6
0
        public JsonResult Eaten()
        {
            // Find the current user
            string aspNetUserID = _userManager.GetUserId(User);

            if (aspNetUserID == null)
            {
                return(Json(new { success = false, message = "user not logged in" }));
            }
            FujiUser fu = null;

            if (aspNetUserID != null)
            {
                //fu = _context.FujiUsers.Where(u => u.AspnetIdentityId == aspNetUserID).FirstOrDefault();
                fu = _fuRepo.GetFujiUserByIdentityId(aspNetUserID);
                if (fu == null)
                {
                    return(Json(new { success = false, message = "user not found" }));
                }
            }
            // We need to use var here since we're selecting a list of a dynamic object type (by using select new {}).  This is a complex LINQ query.  Use LinqPad to break it down and see what each step does.  I'm not sure it needs both select statements but it was easiest that way.  A join, groupby and then select would have worked.

            /*
             * var apples = _context.ApplesConsumeds
             *  .Where(ac => ac.FujiUser == fu)
             *  .Select(ac => new
             *  {
             *      VarietyName = ac.Apple.VarietyName,
             *      Count = ac.Count
             *  })
             *  .GroupBy(ac => ac.VarietyName)
             *  .Select(g => new
             *  {
             *      VarietyName = g.Key,
             *      Total = g.Sum(x => x.Count)
             *  });
             */
            // refactored to ...
            Dictionary <Apple, int> values = _fuRepo.GetCountOfSpecificApplesEaten(_appleRepo.GetAll(), fu);
            //Total and VarietyName
            var apples = values.Select(v => new { VarietyName = v.Key.VarietyName, Total = v.Value });

            return(Json(new { success = true, message = "ok", apples = apples }));
        }
コード例 #7
0
        /// <summary>
        /// Initialize seed data for users.  Creates users for login using Identity and also application users.  One password
        /// is used for all accounts.
        /// </summary>
        /// <param name="serviceProvider">The fully configured service provider for this app that can provide a UserManager and the applications dbcontext</param>
        /// <param name="seedData">Array of seed data holding all the attributes needed to create the user objects</param>
        /// <param name="testUserPw">Password for all seed accounts</param>
        /// <returns></returns>
        public static async Task Initialize(IServiceProvider serviceProvider, UserInfoData[] seedData, string testUserPw)
        {
            try
            {
                // Get our application db context
                //   For later reference -- this uses the "Service Locator anti-pattern", not usually a good pattern
                //   but unavoidable here
                using (var context = new FujiDbContext(serviceProvider.GetRequiredService <DbContextOptions <FujiDbContext> >()))
                {
                    // Get the Identity user manager
                    var userManager = serviceProvider.GetRequiredService <UserManager <IdentityUser> >();

                    foreach (var u in seedData)
                    {
                        // Ensure this user exists or is newly created (Email is used for username since that is the default in Register and Login -- change those and then use username here if you want it different than email
                        var identityID = await EnsureUser(userManager, testUserPw, u.Email, u.Email, u.EmailConfirmed);

                        // Create a new FujiUser if this one doesn't already exist
                        FujiUser fu = new FujiUser {
                            AspnetIdentityId = identityID, FirstName = u.FirstName, LastName = u.LastName
                        };
                        if (!context.FujiUsers.Any(x => x.AspnetIdentityId == fu.AspnetIdentityId && x.FirstName == fu.FirstName && x.LastName == fu.LastName))
                        {
                            // Doesn't already exist, so add a new user
                            context.Add(fu);
                            await context.SaveChangesAsync();
                        }
                    }
                }
            }
            catch (InvalidOperationException ex)
            {
                // Thrown if there is no service of the type requested from the service provider
                // Catch it (and don't throw the exception below) if you don't want it to fail (5xx status code)
                throw new Exception("Failed to initialize user seed data, service provider did not have the correct service");
            }
        }
コード例 #8
0
        public async Task <IActionResult> Index()
        {
            // Information straight from the Controller (does not need to go to the database)
            bool   isAdmin         = User.IsInRole("Admin");
            bool   isAuthenticated = User.Identity.IsAuthenticated;
            string name            = User.Identity.Name;
            string authType        = User.Identity.AuthenticationType;

            // Information from Identity through the user manager
            string       id   = _userManager.GetUserId(User);          // reportedly does not need to hit the db
            IdentityUser user = await _userManager.GetUserAsync(User); // does go to the db

            string email = user?.Email ?? "no email";
            string phone = user?.PhoneNumber ?? "no phone number";

            ViewBag.Message = $"User {name} is authenticated? {isAuthenticated} using type {authType} and is an Admin? {isAdmin}.  ID from Identity is {id}, email is {email} and phone is {phone}";

            FujiUser fu = null;

            if (id != null)
            {
                fu = _fujiDbContext.FujiUsers.Where(u => u.AspnetIdentityId == id).FirstOrDefault();
            }

            var        appleList = _fujiDbContext.Apples.ToList();
            MainPageVM vm        = new MainPageVM {
                TheIdentityUser = user, TheFujiUser = fu, Apples = appleList
            };

            // Read cookie
            string cookie = Request.Cookies["Fuji-app"];

            _logger.LogInformation($"Read cookie: {cookie}");

            return(View(vm));
        }
コード例 #9
0
        public async Task <IActionResult> Index()
        {
            // Information from Identity through the user manager
            string       id   = _userManager.GetUserId(User);          // reportedly does not need to hit the db
            IdentityUser user = await _userManager.GetUserAsync(User); // does go to the db

            FujiUser fu = null;

            if (id != null)
            {
                //fu = _fujiDbContext.FujiUsers.Where(u => u.AspnetIdentityId == id).FirstOrDefault();
                fu = _fuRepo.GetFujiUserByIdentityId(id);
            }

            //var appleList = _fujiDbContext.Apples.ToList();
            var        appleList = _appleRepo.GetAll().ToList();
            MainPageVM vm        = new MainPageVM {
                TheIdentityUser = user, TheFujiUser = fu, Apples = appleList
            };

            ViewBag.TotalConsumed = _appleRepo.GetTotalConsumed(_appleRepo.GetAll());

            return(View(vm));
        }
コード例 #10
0
        public JsonResult Eaten()
        {
            // Find the current user
            string aspNetUserID = _userManager.GetUserId(User);

            if (aspNetUserID == null)
            {
                return(Json(new { success = false, message = "user not logged in" }));
            }
            FujiUser fu = null;

            if (aspNetUserID != null)
            {
                fu = _context.FujiUsers.Where(u => u.AspnetIdentityId == aspNetUserID).FirstOrDefault();
                if (fu == null)
                {
                    return(Json(new { success = false, message = "user not found" }));
                }
            }
            // We need to use var here since we're selecting a list of a dynamic object type (by using select new {}).  This is a complex LINQ query.  Use LinqPad to break it down and see what each step does.  I'm not sure it needs both select statements but it was easiest that way.  A join, groupby and then select would have worked.
            var apples = _context.ApplesConsumeds
                         .Where(ac => ac.FujiUser == fu)
                         .Select(ac => new
            {
                VarietyName = ac.Apple.VarietyName,
                Count       = ac.Count
            })
                         .GroupBy(ac => ac.VarietyName)
                         .Select(g => new
            {
                VarietyName = g.Key,
                Total       = g.Sum(x => x.Count)
            });

            return(Json(new { success = true, message = "ok", apples = apples }));
        }