Example #1
0
        public async Task <bool> UpdateUserAsync(TokketUser item)
        {
            var apiUrl = $"{_apiSettings.ApiPrefix}/user/{item.Id}";     // Api Method to Call with values

            apiUrl += $"{_apiSettings.CodePrefix}{_apiSettings.ApiKey}"; // Add Suffix for API
            return((await _httpClient.PutAsJsonAsync(apiUrl, item)).IsSuccessStatusCode);
        }
        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());
        }
Example #3
0
        public async Task <FirebaseAuthLink> LoginEmailPasswordAsync(string email, string password)
        {
            TokketUser user = new TokketUser()
            {
                Email = email, PasswordHash = password
            };

            client.BaseAddress = new Uri($"{baseUrl}/login{codePrefix}{apiKey}");
            HttpResponseMessage response = await client.PostAsJsonAsync(client.BaseAddress, user);

            client = new HttpClient();
            return(JsonConvert.DeserializeObject <FirebaseAuthLink>(await response.Content.ReadAsStringAsync()));
        }
Example #4
0
        public async Task <FirebaseAuthLink> LoginEmailPasswordAsync(string email, string password)
        {
            TokketUser user = new TokketUser()
            {
                Email = email, PasswordHash = password
            };
            var apiUrl = $"{_apiSettings.ApiPrefix}/login";              // Api Method to Call with values

            apiUrl += $"{_apiSettings.CodePrefix}{_apiSettings.ApiKey}"; // Add Suffix for API
            HttpResponseMessage response = await _httpClient.PostAsJsonAsync(apiUrl, user);

            return(JsonConvert.DeserializeObject <FirebaseAuthLink>(await response.Content.ReadAsStringAsync()));
        }
Example #5
0
        public async Task <bool> CreateUserAsync(TokketUser item)
        {
            if (User == null)
            {
                throw new UnauthorizedAccessException();
            }
            client.DefaultRequestHeaders.Add("userid", User.Id);
            client.DefaultRequestHeaders.Add("token", User.IdToken);
            client.BaseAddress = new Uri($"{baseUrl}/user/{item.Id}{codePrefix}{apiKey}");
            HttpResponseMessage response = await client.PostAsJsonAsync(client.BaseAddress, item);

            client = new HttpClient();
            return(response.IsSuccessStatusCode);
        }
Example #6
0
        public async Task <IActionResult> DownloadPersonalData()
        {
            var userAccount = await _userService.GetUserAsync(HttpContext.User.Identity.Name);

            TokketUser user = JsonConvert.DeserializeObject <TokketUser>(JsonConvert.SerializeObject(userAccount));

            return(new PartialViewAsPdf("User/_PersonalDataPDF", user)   // Temporary
            {
                FileName = "tokkepedia_personalData.pdf",
                CustomSwitches = "--page-offset 0 --footer-center [page] --footer-font-size 8",
                PageSize = Size.A4,
                PageOrientation = Orientation.Portrait,
                PageMargins = new Margins(10, 5, 10, 5)
            });
        }
Example #7
0
        /// <summary>
        ///  Links Facebook/Google login with an Email and Password
        /// </summary>
        public async Task <FirebaseAuthLink> LinkAccountsAsync(string token, string email, string password)
        {
            TokketUser user = new TokketUser()
            {
                Email = email, PasswordHash = password
            };

            client.DefaultRequestHeaders.Add("email", email);
            client.DefaultRequestHeaders.Add("password", password);
            client.DefaultRequestHeaders.Add("token", token);
            client.BaseAddress = new Uri($"{baseUrl}/linkaccounts{codePrefix}{apiKey}");
            HttpResponseMessage response = await client.PostAsJsonAsync(client.BaseAddress, user);

            client = new HttpClient();
            return(await response.Content.ReadAsAsync <FirebaseAuthLink>());
        }
Example #8
0
        /// <summary>
        ///  Links Facebook/Google login with an Email and Password
        /// </summary>
        public async Task <FirebaseAuthLink> LinkAccountsAsync(string token, string email, string password)
        {
            TokketUser user = new TokketUser()
            {
                Email = email, PasswordHash = password
            };

            _httpClient.DefaultRequestHeaders.Add("email", email);
            _httpClient.DefaultRequestHeaders.Add("password", password);
            _httpClient.DefaultRequestHeaders.Add("token", token);
            var apiUrl = $"{_apiSettings.ApiPrefix}/linkaccounts";       // Api Method to Call with values

            apiUrl += $"{_apiSettings.CodePrefix}{_apiSettings.ApiKey}"; // Add Suffix for API
            HttpResponseMessage response = await _httpClient.PostAsJsonAsync(apiUrl, user);

            return(await response.Content.ReadAsAsync <FirebaseAuthLink>());
        }
Example #9
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(TokketUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
Example #10
0
        public async Task <FirebaseAuthLink> SignUpAsync(string email, string password, string displayName, string country, DateTime date, string userPhoto)
        {
            TokketUser user = new TokketUser()
            {
                Email = email, PasswordHash = password, DisplayName = displayName, Country = country, Birthday = date, UserPhoto = userPhoto
            };

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

            client.BaseAddress = new Uri($"{baseUrl}/signup{codePrefix}{apiKey}");
            HttpResponseMessage response = await client.PostAsJsonAsync(client.BaseAddress, user);

            client = new HttpClient();
            var res = await response.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <FirebaseAuthLink>(res));
        }
Example #11
0
        public async Task <FirebaseAuthLink> SignUpAsync(string email, string password, string displayName, string country, DateTime date, string userPhoto)
        {
            TokketUser user = new TokketUser()
            {
                Email = email, PasswordHash = password, DisplayName = displayName, Country = country, Birthday = date, UserPhoto = userPhoto
            };

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

            var apiUrl = $"{_apiSettings.ApiPrefix}/signup";             // Api Method to Call with values

            apiUrl += $"{_apiSettings.CodePrefix}{_apiSettings.ApiKey}"; // Add Suffix for API

            var res = await _httpClient.PostAsJsonAsync(apiUrl, user);

            return(JsonConvert.DeserializeObject <FirebaseAuthLink>(await res.Content.ReadAsStringAsync()));
        }
Example #12
0
        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();
            //}
        }
Example #14
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+DwENAIJ4HAYF4AwSagD9IczM1IiCQkUNbswkIpLmZGhEQyMihrdkEBNLcTI0ICGTk0NZsAgJpbqZGBAQycmhrNgGBNDdTIwICGTm0NZuAQJqbqREBgYwc2ppNQCDNzdSIgEBGDm3NJiCQ5mZqREAgI4e2ZhMQSHMzNSI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c0mIJDmZmpEQCAjh7ZmExBIczM1IiCQkUNbswkIpLmZGhEQyMihrdkEBNLcTI0ICGTk0NZsAgJpbqZGBAQycmhrNgGBNDdTIwICGTm0NZuAQJqbqREBgYwc2ppNQCDNzdSIgEBGDm3NJiCQ5mZqREAgI4e2ZhMQSHMzNSIgkJFDW7MJCKS5mRoREMjIoa3ZBATS3EyNCAhk5NDWbAICaW6mRgQEMnJoazYBgTQ3UyMCAhk5tDWbgECam6kRAYGMHNqaTUAgzc3UiIBARg5tzSYgkOZmakRAICOHtmYTEEhzMzUiIJCRQ1uzCQikuZkaERDIyKGt2QQE0txMjQgIZOTQ1mwCAmlupkYEBDJyaGs2AYE0N1MjAgIZObQ1m4BAmpupEQGBjBzamk1AIM3N1IiAQEYObc0mIJDmZmpEQCAjh7ZmExBIczM1IiCQkUNbswkIpLmZGhH4AStUAMmSuOW2AAAAAElFTkSuQmCC")
                {
                    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());
        }