Esempio n. 1
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    if (_roleManager.Roles.Count() == 0)
                    {
                        var roleAdmin = new IdentityRole("Admin");
                        var roleUser  = new IdentityRole("User");
                        await _roleManager.CreateAsync(roleAdmin);

                        await _roleManager.CreateAsync(roleUser);

                        await _userManager.AddToRoleAsync(user, "Admin");
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(user, "User");

                        var myUser = new User(user.Id, model.NickName);
                        if (model.UserPhoto != null)
                        {
                            using (var memoryStream = new MemoryStream())
                            {
                                await model.UserPhoto.CopyToAsync(memoryStream);

                                myUser.UserPhoto = memoryStream.ToArray();
                            }
                        }
                        _repository.AddUser(myUser);
                    }

                    _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(RedirectToAction("MainPage", "Quiz"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }