Ejemplo n.º 1
0
        public async Task <IHttpActionResult> Login(LoginRequest request)
        {
            try {
                var google = new GoogleTokenRequest(request);
                var token  = await GetGoogleToken(google);

                var user = await UserByToken(token);

                var loginReponse = default(LoginResponse);

                if (user == null)
                {
                    var profile = await GetGoogleProfile(token);

                    user = await CreateUser(profile, token);

                    loginReponse = new LoginResponse(user);
                }
                else
                {
                    loginReponse = new LoginResponse(user);
                }

                return(Ok(loginReponse));
            } catch (Exception ex) {
                return(InternalServerError(ex));
            }
        }
Ejemplo n.º 2
0
        private async Task <string> GetGoogleToken(GoogleTokenRequest request)
        {
            var client   = new HttpClient();
            var content  = request.AsFormContent();
            var url      = ConfigurationManager.AppSettings["GoogleAuthURL"];
            var response = await client.PostAsync(url, content);

            if (!response.IsSuccessStatusCode)
            {
                var errMsg = await response.Content.ReadAsStringAsync();

                throw new ApplicationException(errMsg);
            }

            var googleResponse = await response.Content.ReadAsAsync <GoogleTokenResponse>();

            return(googleResponse.access_token);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// GetTokenByCode
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        private async Task <GoogleTokenResponse> GetTokenByCode(string url, GoogleTokenRequest postData)
        {
            var result    = new GoogleTokenResponse();
            var keyValues = new List <KeyValuePair <string, string> >();

            keyValues.Add(new KeyValuePair <string, string>("code", postData.Code));
            keyValues.Add(new KeyValuePair <string, string>("client_id", postData.ClientId));
            keyValues.Add(new KeyValuePair <string, string>("client_secret", postData.ClientSecret));
            keyValues.Add(new KeyValuePair <string, string>("redirect_uri", postData.RedirectUri));
            keyValues.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));

            HttpContent cont = new FormUrlEncodedContent(keyValues);

            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.PostAsync(url, cont))
                {
                    using (HttpContent content = response.Content)
                    {
                        string data = await content.ReadAsStringAsync();

                        if (!string.IsNullOrWhiteSpace(data))
                        {
                            if (data.Contains("error"))
                            {
                                result.ErrorMessage = data;
                            }
                            else
                            {
                                result = JsonToObject.FromJson <GoogleTokenResponse>(data);
                            }
                        }
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// AuthenticateAsync
        /// </summary>
        /// <returns></returns>
        public async Task <OAuth2AccessResponse> AuthenticateAsync(string code)
        {
            var response = new OAuth2AccessResponse();

            var tokenRequest = new GoogleTokenRequest()
            {
                ClientId     = _clientConfig.OAuth2TokenizeRequestInfo.ClientId,
                ClientSecret = _clientConfig.OAuth2TokenizeRequestInfo.ClientSecret,
                RedirectUri  = _clientConfig.OAuth2TokenizeRequestInfo.RedirectUrl,
                Code         = code
            };

            _clientConfig.OAuth2TokenizeRequestInfo.AuthorizedCode = code;

            var result = await GetTokenByCode(_clientConfig.OAuth2TokenizeRequestInfo.TokenEndPointUrl, tokenRequest);

            if (!string.IsNullOrWhiteSpace(result.AccessToken))
            {
                var refreshDataExpireDate = DateTimeOffset.Now.AddMonths(12);

                var tokenExpireTime = double.Parse(result.ExpiresIn);
                var tokenExpireDate = DateTimeOffset.Now.AddSeconds(tokenExpireTime);
                _clientConfig.MailDataStore.Add($"{_clientConfig.MailDataStore.StoreKey}_GMailToken", result.AccessToken, tokenExpireDate);

                if (!string.IsNullOrWhiteSpace(result.RefreshToken))
                {
                    _clientConfig.MailDataStore.Add($"{_clientConfig.MailDataStore.StoreKey}_GMailRefreshData", result, refreshDataExpireDate);
                }


                response.Token    = result.AccessToken;
                _token            = result.AccessToken;
                response.IsSucces = true;
            }

            return(response);
        }
Ejemplo n.º 5
0
        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));
        }