public async Task <RedirectToActionResult> GoogleSigninAndroidAsync(string token, [FromServices] IGoogleAuth service, [FromServices] IDataProtectionProvider dataProtectProvider, CancellationToken cancellationToken ) { var result = await service.LogInAsync(token, cancellationToken); if (result == null) { return(RedirectToAction("Index")); } var result2 = await _signInManager.ExternalLoginSignInAsync("Google", result.Id, true, true); var user2 = await _userManager.FindByEmailAsync(result.Email); var dataProtector = dataProtectProvider.CreateProtector("Spitball").ToTimeLimitedDataProtector(); var code = dataProtector.Protect(user2.Id.ToString(), DateTimeOffset.UtcNow.AddDays(5)); return(RedirectToAction("Index", new { token = code })); }
public async Task <ActionResult <ReturnSignUserResponse> > GoogleSignInAsync( [FromBody] GoogleTokenRequest model, [FromServices] IGoogleAuth service, [FromServices] IUserDirectoryBlobProvider blobProvider, [FromServices] TelemetryClient logClient, [FromServices] IHttpClientFactory clientFactory, CancellationToken cancellationToken) { var result = await service.LogInAsync(model.Token, cancellationToken); _logger.Info($"received google user {result}"); if (result == null) { logClient.TrackTrace("result from google is null"); ModelState.AddModelError("Google", _localizer["GoogleNoResponse"]); return(BadRequest(ModelState)); } var result2 = await _signInManager.ExternalLoginSignInAsync("Google", result.Id, true, true); if (result2.Succeeded) { return(ReturnSignUserResponse.SignIn()); //return new ReturnSignUserResponse(false); } if (result2.IsLockedOut) { logClient.TrackTrace("user is locked out"); ModelState.AddModelError("Google", _loginLocalizer["LockOut"]); return(BadRequest(ModelState)); } var user = await _userManager.FindByEmailAsync(result.Email); if (result2.IsNotAllowed && user != null && await _userManager.IsLockedOutAsync(user)) { ModelState.AddModelError("Google", _loginLocalizer["LockOut"]); return(BadRequest(ModelState)); } if (user == null) { var country = await _countryProvider.GetUserCountryAsync(cancellationToken); user = new User(result.Email, result.FirstName, result.LastName, result.Language, country) { EmailConfirmed = true }; var result3 = await _userManager.CreateAsync(user); if (result3.Succeeded) { if (!string.IsNullOrEmpty(result.Picture)) { using var httpClient = clientFactory.CreateClient(); var message = await httpClient.GetAsync(result.Picture, cancellationToken); await using var sr = await message.Content.ReadAsStreamAsync(); var mimeType = message.Content.Headers.ContentType; try { var uri = await blobProvider.UploadImageAsync(user.Id, result.Picture, sr, mimeType.ToString(), cancellationToken); var imageProperties = new ImageProperties(uri, ImageProperties.BlurEffect.None); var url = Url.ImageUrl(imageProperties); var fileName = uri.AbsolutePath.Split('/').LastOrDefault(); user.UpdateUserImage(url, fileName); } catch (ArgumentException e) { logClient.TrackException(e, new Dictionary <string, string>() { ["FromGoogle"] = result.Picture }); } } await _userManager.AddLoginAsync(user, new UserLoginInfo("Google", result.Id, result.Name)); return(await MakeDecisionAsync(user, true, null, cancellationToken)); } logClient.TrackTrace($"failed to register {string.Join(", ", result3.Errors)}"); ModelState.AddModelError("Google", _localizer["GoogleUserRegisteredWithEmail"]); return(BadRequest(ModelState)); } if (!user.EmailConfirmed) { user.EmailConfirmed = true; await _userManager.UpdateAsync(user); } await _userManager.AddLoginAsync(user, new UserLoginInfo("Google", result.Id, result.Name)); return(await MakeDecisionAsync(user, true, null, cancellationToken)); }
public async Task <IActionResult> LogInGoogle([FromBody] GoogleLogInRequest model, [FromServices] IGoogleAuth service, CancellationToken cancellationToken) { var login = await service.LogInAsync(model.Token, cancellationToken); if (login is null) { return(BadRequest()); } var query = new ValidateUserQuery(login.Email); var result = await _queryBus.QueryAsync(query, cancellationToken); if (result is null) { return(Unauthorized()); } var claims = new List <Claim> { new Claim(ClaimTypes.Name, login.Email), new Claim("FullName", $"{login.FirstName} { login.LastName}"), new Claim("UserId", result.Id.ToString()), new Claim(ClaimsPrincipalExtensions.ClaimCountry, result.Country ?? "None"), }; //foreach (var resultRole in result.Roles ?? Enumerable.Empty<string>()) //{ // claims.Add(new Claim(ClaimTypes.Role, resultRole)); //} var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { //AllowRefresh = <bool>, // Refreshing the authentication session should be allowed. ExpiresUtc = DateTimeOffset.UtcNow.AddHours(1), // The time at which the authentication ticket expires. A // value set here overrides the ExpireTimeSpan option of // CookieAuthenticationOptions set with AddCookie. IsPersistent = false, // Whether the authentication session is persisted across // multiple requests. When used with cookies, controls // whether the cookie's lifetime is absolute (matching the // lifetime of the authentication ticket) or session-based. //IssuedUtc = <DateTimeOffset>, // The time at which the authentication ticket was issued. //RedirectUri = <string> // The full path or absolute URI to be used as an http // redirect response value. }; await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); return(Ok()); }