public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                TokkepediaApiClient apiClient = new TokkepediaApiClient();
                var link = await apiClient.LinkAccountsAsync(Input.FirebaseToken, Input.Email, Input.Password);

                DateTime date = DateTime.Parse(Input.Birthday);
                var      user = new TokketUser
                {
                    Id           = Input.Id,
                    UserName     = Input.UserName,
                    DisplayName  = Input.DisplayName,
                    Birthday     = date,
                    Country      = Input.Country,
                    Email        = Input.Email,
                    PasswordHash = Input.Password,
                    IdToken      = Input.FirebaseToken
                };

                //---Error to fix-----------------------------
                //--------------------------------------------
                var result = await _userManager.CreateAsync(user, Input.Password);

                //--------------------------------------------
                //--------------------------------------------

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");
                    await _signInManager.SignInAsync(user, isPersistent : false);

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

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
        public async Task <IdentityResult> CreateAsync(T user, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            TokkepediaApiClient apiClient = new TokkepediaApiClient();

            //Firebase Create
            try
            {
                FirebaseAuthLink link = await apiClient.SignUpAsync(user.Email, user.PasswordHash, user.DisplayName, user.Country, user.Birthday, user.UserPhoto);

                user.Id      = link.User.LocalId;
                user.IdToken = link.FirebaseToken;
            }
            catch (Exception ex)
            {
                var    err          = ex.Message;
                string toBeSearched = "Reason: ";
                int    ix           = err.IndexOf(toBeSearched);

                if (ix != -1)
                {
                    string code = err.Substring(ix + toBeSearched.Length);
                    err    = code;
                    result = code;
                }
            }

            if (result == "EmailExists")
            {
                result = "";
            }

            return(result == ""
                ? IdentityResult.Success
                : IdentityResult.Failed(new IdentityError()
            {
                Code = result
            }));
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                try
                {
                    TokkepediaApiClient apiClient = new TokkepediaApiClient();
                    await apiClient.SendPasswordResetAsync(Input.Email?.Trim());

                    return(RedirectToPage("./ForgotPasswordConfirmation"));
                }
                catch
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToPage("./ForgotPasswordConfirmation"));
                }



                //var user = await _userManager.FindByEmailAsync(Input.Email);
                //if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                //{

                //}

                //// For more information on how to enable account confirmation and password reset please
                //// visit https://go.microsoft.com/fwlink/?LinkID=532713
                //var code = await _userManager.GeneratePasswordResetTokenAsync(user);
                //var callbackUrl = Url.Page(
                //    "/Account/ResetPassword",
                //    pageHandler: null,
                //    values: new { code },
                //    protocol: Request.Scheme);

                //await _emailSender.SendEmailAsync(
                //    Input.Email,
                //    "Reset Password",
                //    $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                //return RedirectToPage("./ForgotPasswordConfirmation");
            }

            return(Page());
        }
        public async Task <IdentityResult> UpdateAsync(T user, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            TokkepediaApiClient apiClient = new TokkepediaApiClient();

            apiClient.User = user;
            try
            {
                await apiClient.UpdateUserAsync(user);
            }
            catch (Exception e)
            {
                return(IdentityResult.Failed());
            }

            return(IdentityResult.Success);
        }
        public async Task <T> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (normalizedUserName == null)
            {
                throw new ArgumentNullException(nameof(normalizedUserName));
            }
            T foundUser = null;

            try
            {
                TokkepediaApiClient apiClient = new TokkepediaApiClient();
                foundUser = (T)(dynamic)await apiClient.GetUserAsync(normalizedUserName);
            }
            catch
            {
            }

            return(null);

            //return (T)(dynamic)(new FirebaseIdentityUser());
        }
        public async Task <IdentityResult> DeleteAsync(T user, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            try
            {
                TokkepediaApiClient apiClient = new TokkepediaApiClient();
                apiClient.User = (TokketUser)(dynamic)user;
                await apiClient.DeleteUserAsync(user.Id);
            }
            catch (Exception ex)
            {
                var    err          = ex.Message;
                string toBeSearched = "Reason: ";
                int    ix           = err.IndexOf(toBeSearched);

                if (ix != -1)
                {
                    string code = err.Substring(ix + toBeSearched.Length);
                    // do something here
                    err    = code;
                    result = code;
                }
            }

            return(result == ""
                ? IdentityResult.Success
                : IdentityResult.Failed(new IdentityError()
            {
                Code = result
            }));
        }
        public async Task <T> FindByIdAsync(string userId, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (userId == null)
            {
                throw new ArgumentNullException(nameof(userId));
            }

            T foundUser = null;

            try
            {
                TokkepediaApiClient apiClient = new TokkepediaApiClient();
                var item = await apiClient.GetUserAsync(userId);

                foundUser = (T)(dynamic)item;
            }
            catch
            {
            }

            return(foundUser);
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true

                FirebaseAuthLink    link = null; string t = "";
                TokkepediaApiClient apiClient = new TokkepediaApiClient();
                try
                {
                    link = await apiClient.LoginEmailPasswordAsync(Input.Email.Trim(), Input.Password.Trim());

                    var user = new TokketUser()
                    {
                        Id                 = link.User.LocalId,
                        UserName           = link.User.LocalId,
                        NormalizedUserName = link.User.LocalId.ToUpper(),
                        Email              = Input.Email.Trim(),
                        NormalizedEmail    = Input.Email.Trim().ToUpper(),
                        IdToken            = link.FirebaseToken,
                        PasswordHash       = Input.Password,
                        UserPhoto          = link.User.PhotoUrl,
                        DisplayName        = link.User.DisplayName
                    };
                    user.IdToken      = link.FirebaseToken;
                    user.RefreshToken = link.RefreshToken;
                    await _signInManager.SignInAsync(user, new AuthenticationProperties()
                    {
                        AllowRefresh = true, IsPersistent = Input.RememberMe, ExpiresUtc = DateTime.UtcNow.AddMinutes(30)
                    });

                    // Add Claims and Principals including Token
                    var claims = new List <Claim>();
                    claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id));
                    claims.Add(new Claim(ClaimTypes.Name, user.Id));
                    claims.Add(new Claim("IdToken", user.IdToken));
                    claims.Add(new Claim("StreamToken", user.RefreshToken)); //Refresh token is Stream token, may be changed in the future

                    var identity = new ClaimsIdentity(claims, "Identity.Application");
                    var p        = new ClaimsPrincipal(identity);

                    // Authentication
                    await HttpContext.SignInAsync("Identity.Application", p, new AuthenticationProperties()
                    {
                        AllowRefresh = true, IsPersistent = Input.RememberMe, ExpiresUtc = DateTime.UtcNow.AddMinutes(30)
                    });

                    HttpContext.User = p;

                    _logger.LogInformation("User logged in.");
                    return(LocalRedirect(returnUrl));//returnUrl
                }
                catch (Exception ex)
                {
                    t = ex.Message;
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }

                //var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password.Trim(), Input.RememberMe, lockoutOnFailure: true);
                //if (result.Succeeded) // && link != null
                //{
                //    _logger.LogInformation("User logged in.");
                //    return LocalRedirect(returnUrl);
                //}
                //if (result.RequiresTwoFactor)
                //{
                //    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                //}
                //if (result.IsLockedOut)
                //{
                //    _logger.LogWarning("User account locked out.");
                //    return RedirectToPage("./Lockout");
                //}
                //else
                //{
                //    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                //    return Page();
                //}
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            // profile claims

            // Sign in the user with this external login provider if the user already has a login.
            FirebaseAuthType authType;
            string           email = "", photoUrl = "";

            if (info.ProviderDisplayName == "Facebook")
            {
                authType = FirebaseAuthType.Facebook;
                var claims = info.Principal.Identities.First().Claims;
                email = claims.ElementAt(1).Value;
            }
            else if (info.ProviderDisplayName == "Google")
            {
                authType = FirebaseAuthType.Google;
                var claims = info.Principal.Identities.First().Claims;
                email    = claims.ElementAt(4).Value;
                photoUrl = claims.ElementAt(5).Value;
            }
            else
            {
                authType = new FirebaseAuthType();
            }


            var token = info.AuthenticationTokens.First().Value;

            TokkepediaApiClient apiClient = new TokkepediaApiClient();
            FirebaseAuthLink    link      = null;

            try
            {
                link = await apiClient.LoginOAuthAsync(info.ProviderDisplayName, token);
            }
            catch
            {
            }

            TokketUser user = await apiClient.GetUserAsync(link.User.LocalId);

            // If the user does not have an account, then ask the user to create an account.
            if (user == null)
            {
                ReturnUrl     = returnUrl;
                LoginProvider = info.LoginProvider;
                if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
                {
                    Input = new InputModel
                    {
                        FirebaseToken = link.FirebaseToken,
                        Id            = link.User.LocalId,
                        UserName      = link.User.LocalId,
                        DisplayName   = info.Principal.Identity.Name,
                        Email         = info.Principal.FindFirstValue(ClaimTypes.Email)
                    };
                }
                return(Page());
            }
            //Sign user in
            else
            {
                if (user.IsLockedOut)
                {
                    return(RedirectToPage("./Lockout"));
                }

                await _signInManager.SignInAsync(user, true);

                _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
                return(LocalRedirect(returnUrl));
            }

            //var result = new Microsoft.AspNetCore.Identity.SignInResult();// await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor : true);
            //if (result.Succeeded)
            //{
            //    _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
            //    return LocalRedirect(returnUrl);
            //}
            //if (result.IsLockedOut)
            //{
            //    return RedirectToPage("./Lockout");
            //}
            //else
            //{
            //    // If the user does not have an account, then ask the user to create an account.
            //    ReturnUrl = returnUrl;
            //    LoginProvider = info.LoginProvider;
            //    if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
            //    {
            //        Input = new InputModel
            //        {
            //            Email = info.Principal.FindFirstValue(ClaimTypes.Email)
            //        };
            //    }
            //    return Page();
            //}
        }
Exemple #10
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                DateTime date = DateTime.Parse(Input.Birthday);
                var      user = new TokketUser {
                    UserName     = Input.Email,
                    DisplayName  = Input.DisplayName,
                    Birthday     = date,
                    Country      = Input.Country,
                    State        = Input.State,
                    Email        = Input.Email,
                    PasswordHash = Input.Password
                };

                user.BirthDate  = $"{CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(date.Month)} {date.Day}";
                user.BirthYear  = date.Year;
                user.BirthMonth = date.Month;
                user.BirthDay   = date.Day;

                TokkepediaApiClient apiClient = new TokkepediaApiClient();
                //Image Upload
                if (Input.CroppedPhoto == "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAFIklEQVR4Xu3VsRHAMAzEsHj/pTOBXbB9pFchyLycz0eAwFXgsCFA4C4gEK+DwENAIJ4HAYF4AwSagD9IczM1IiCQkUNbswkIpLmZGh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OHtmYTEEhzMzUiIJCRQ1uzCQikuZkaERDIyKGt2QQE0txMjQgIZOTQ1mwCAmlupkYEBDJyaGs2AYE0N1MjAgIZObQ1m4BAmpupEQGBjBzamk1AIM3N1IiAQEYObc0mIJDmZmpEQCAjh7ZmExBIczM1IiCQkUNbswkIpLmZGhEQyMihrdkEBNLcTI0ICGTk0NZsAgJpbqZGBAQycmhrNgGBNDdTIwICGTm0NZuAQJqbqREBgYwc2ppNQCDNzdSIgEBGDm3NJiCQ5mZqREAgI4e2ZhMQSHMzNSIgkJFDW7MJCKS5mRoREMjIoa3ZBATS3EyNCAhk5NDWbAICaW6mRgQEMnJoazYBgTQ3UyMCAhk5tDWbgECam6kRAYGMHNqaTUAgzc3UiIBARg5tzSYgkOZmakRAICOHtmYTEEhzMzUiIJCRQ1uzCQikuZkaERDIyKGt2QQE0txMjQgIZOTQ1mwCAmlupkYEBDJyaGs2AYE0N1MjAgIZObQ1m4BAmpupEQGBjBzamk1AIM3N1IiAQEYObc0mIJDmZmpEQCAjh7ZmExBIczM1IiCQkUNbswkIpLmZGhH4AStUAMmSuOW2AAAAAElFTkSuQmCC")
                {
                    Input.CroppedPhoto = null;
                }
                if (!string.IsNullOrEmpty(Input.CroppedPhoto))
                {
                    user.UserPhoto = Input.CroppedPhoto;
                }
                else
                {
                    user.UserPhoto = "";
                }

                var result = await _userManager.CreateAsync(user, Input.Password);

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

                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Page(
                    //    "/Account/ConfirmEmail",
                    //    pageHandler: null,
                    //    values: new { userId = user.Id, code = code },
                    //    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>.");

                    await _signInManager.SignInAsync(user, new AuthenticationProperties()
                    {
                        AllowRefresh = true, IsPersistent = false, ExpiresUtc = DateTime.UtcNow.AddHours(24)
                    });

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

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