Esempio n. 1
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                ExternalLoginInfo info = await signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    TempData.AddErrorMessage(WebConstants.ErrorTryAgain);
                    return(RedirectToHome());
                }

                Picture profilePicture = new Picture();

                Stream stream             = new MemoryStream(model.ProfilePictureBytes);
                Image  pictureImage       = Image.FromStream(stream);
                bool   imageInsertSuccess = await pictureService.InsertAsync(profilePicture, pictureImage); // inserts image into database and file system

                if (!imageInsertSuccess)                                                                    // if something with the image goes wrong return error
                {
                    TempData.AddErrorMessage(WebConstants.ErrorTryAgain);
                    return(View(nameof(ExternalLogin), model));
                }

                string[] personalNames = AuthenticationHelpers.GetNamesFromExternalLogin(model.Username); // Extracts the first and last name of the person
                User     user          = new User
                {
                    UserName               = AuthenticationHelpers.GenerateUniqueUsername(personalNames[0], personalNames[1]),
                    Email                  = model.Email,
                    FirstName              = personalNames[0],
                    LastName               = personalNames[1],
                    PhoneNumber            = model.PhoneNumber,
                    ProfilePictureFileName = profilePicture.FileName
                };

                IdentityResult result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await signInManager.SignInAsync(user, isPersistent : false);

                        return(RedirectToLocal(returnUrl));
                    }
                }

                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(nameof(ExternalLogin), model));
        }