Пример #1
0
        public async Task <IActionResult> Google([FromBody] GoogleAuthViewModel model)
        {
            var userInfo = GoogleJsonWebSignature.ValidateAsync(model.TokenId, new GoogleJsonWebSignature.ValidationSettings()).Result;

            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                string path = _fileService.UploadAccountImage(userInfo.Picture);

                user = new DbUser
                {
                    FirstName  = userInfo.GivenName,
                    LastName   = userInfo.FamilyName,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    SignUpTime = DateTime.Now,
                    AvatarUrl  = path
                };

                var result = await _userManager.CreateAsync(user, RandomPasswordGenerator.GenerateRandomPassword());

                if (!result.Succeeded)
                {
                    var errors = CustomValidator.GetErrorsByIdentityResult(result);
                    return(BadRequest(errors));
                }
                var roleName   = "User";
                var roleresult = _roleManager.CreateAsync(new DbRole
                {
                    Name = roleName
                }).Result;

                result = _userManager.AddToRoleAsync(user, roleName).Result;

                var invalid = new Dictionary <string, string>
                {
                    { "googleInvalid", "Error google login." }
                };

                if (!result.Succeeded)
                {
                    return(BadRequest(invalid));
                }
            }
            else
            {
                _fileService.UploadAccountImageIfNotExists(user, userInfo.Picture);
            }

            await _signInManager.SignInAsync(user, isPersistent : false);

            return(Ok(
                       new
            {
                token = _jWTTokenService.CreateToken(user),
                refToken = _jWTTokenService.CreateRefreshToken(user)
            }));
        }
        public async Task <IActionResult> Google([FromBody] GoogleAuthViewModel model)
        {
            // 1.generate an app token id
            var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://oauth2.googleapis.com/tokeninfo?id_token={model.id_token}");

            var userInfo = JsonConvert.DeserializeObject <GoogleUserData>(userAccessTokenValidationResponse);

            if (!userInfo.IsVerified || _googleAuthSettingsAccessor.ClientId != userInfo.ClientId)
            {
                return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid google id token.", ModelState)));
            }

            // 2. ready to create the local user account (if necessary) and jwt
            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                var appUser = new AppUser
                {
                    FirstName  = userInfo.FirstName,
                    LastName   = userInfo.LastName,
                    GoogleId   = userInfo.Id,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    PictureUrl = userInfo.Picture
                };

                var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8));

                if (!result.Succeeded)
                {
                    return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState)));
                }

                await _appDbContext.Customers.AddAsync(new Customer { IdentityId = appUser.Id, Location = "", Locale = userInfo.Locale, Gender = "" });

                await _appDbContext.SaveChangesAsync();
            }

            // generate the jwt for the local user...
            var localUser = await _userManager.FindByNameAsync(userInfo.Email);

            if (localUser == null)
            {
                return(BadRequest(Errors.AddErrorToModelState("login_failure", "Failed to create local user account.", ModelState)));
            }

            var jwt = await Tokens.GenerateJwt(_jwtFactory.GenerateClaimsIdentity(localUser.UserName, localUser.Id),
                                               _jwtFactory, localUser.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });

            return(new OkObjectResult(jwt));
        }
        public IActionResult CheckAuthCode([FromBody] GoogleAuthViewModel model)
        {
            var r = model?.Auth?.Verify(_authService, currentUserService.CurrentUser?.Id);

            if (!r.HasValue)
            {
                return(new JsonResult(ActionStatusMessage.Account.Auth.AuthCode.Default));
            }
            if (r.Value)
            {
                return(new JsonResult(ActionStatusMessage.Success));
            }
            return(new JsonResult(ActionStatusMessage.Account.Auth.AuthCode.Invalid));
        }
Пример #4
0
        public async Task <IActionResult> Google([FromBody] GoogleAuthViewModel model)
        {
            var userInfo = GoogleJsonWebSignature.ValidateAsync(model.TokenId, new GoogleJsonWebSignature.ValidationSettings()).Result;

            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                string path = _fileService.UploadFacebookImage(userInfo.Picture);

                user = new DbUser
                {
                    FirstName  = userInfo.GivenName,
                    LastName   = userInfo.FamilyName,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    SignUpTime = DateTime.Now,
                    AvatarUrl  = path
                };

                var result = await _userManager.CreateAsync(user, RandomPasswordGenerator.GenerateRandomPassword());

                if (!result.Succeeded)
                {
                    var errors = CustomValidator.GetErrorsByIdentityResult(result);
                    return(BadRequest(errors));
                }
                var roleName   = "User";
                var roleresult = _roleManager.CreateAsync(new DbRole
                {
                    Name = roleName
                }).Result;

                result = _userManager.AddToRoleAsync(user, roleName).Result;

                await _signInManager.SignInAsync(user, isPersistent : false);

                if (!result.Succeeded)
                {
                    return(BadRequest(new { invalid = "We can't create user" }));
                }
            }

            await _signInManager.SignInAsync(user, isPersistent : false);

            return(Ok(_jWTTokenService.CreateToken(_configuration, user, _userManager)));
        }
        public async Task <ActionResult> Index(CancellationToken cancellationToken)
        {
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);

            if (result.Credential != null)
            {
                var peopleService = new PeopleService(new BaseClientService.Initializer
                {
                    ApplicationName       = "People API .NET Quickstart",
                    HttpClientInitializer = result.Credential,
                });

                var response = peopleService.People.Get("people/me").Execute();

                var viewModel = new GoogleAuthViewModel();
                viewModel.Email = response.EmailAddresses.First().Value;
                viewModel.Name  = response.Names.First().DisplayName;

                return(View("~/Views/Admin/GoogleAuth/Index.cshtml", viewModel));
            }

            return(View("~/Views/Admin/GoogleAuth/Index.cshtml", null));
        }
Пример #6
0
        public async Task <IActionResult> Google([FromBody] GoogleAuthViewModel model)
        {
            try
            {
                var googleUser = await _googleService.GetAccountAsync(model.AccessToken);

                if (string.IsNullOrEmpty(googleUser.Sub))
                {
                    return(BadRequest(_localizer.GetString("InvalidTokenFacebook")));
                }

                // 4. ready to create the local user account (if necessary) and jwt
                var user         = GetUserByExternalId(googleUser.Sub, ExternalProviderTyper.Google);
                var isCreate     = user == null;
                var refreshToken = _tokenService.GenerateRefreshToken();
                var projectPath  = _hostingEnvironment.ContentRootPath;

                if (user == null)
                {
                    var pictureUrl = ImageHelper.SaveImageUrl(googleUser.Picture, ImageFormat.Jpeg);

                    var appUser = new ApplicationUser
                    {
                        FirstName                                      = googleUser.GivenName,
                        LastName                                       = googleUser.FamilyName,
                        GoogleId                                       = googleUser.Sub,
                        Email                                          = googleUser.Email,
                        Nickname                                       = Regex.Replace(googleUser.Name, @"[^\w]", "").ToLower(),
                        UserName                                       = Guid.NewGuid().ToString(),
                        PictureUrl                                     = pictureUrl,
                        LargePictureUrl                                = pictureUrl,
                        Birthday                                       = googleUser.Birthday != null?DateTime.ParseExact(googleUser.Birthday, "MM/dd/yyyy", CultureInfo.InvariantCulture) : DateTime.MinValue,
                                                          RefreshToken = refreshToken
                    };

                    if (!IsEmailUnique(appUser.Email))
                    {
                        return(BadRequest(_localizer.GetString("EmailIsInUse")));
                    }

                    appUser.CreationDate = DateTime.Now;
                    var result = await _userManager.CreateAsync(appUser, _randomPasswordHelper.GenerateRandomPassword());

                    if (!result.Succeeded)
                    {
                        return(BadRequest(_localizer.GetString("LoginFailed")));
                    }
                }

                // generate the jwt for the local user...
                var localUser = GetUserByExternalId(googleUser.Sub, ExternalProviderTyper.Google);

                if (localUser == null)
                {
                    return(BadRequest(_localizer.GetString("LoginFailed")));
                }

                var accessToken = _tokenService.GenerateAccessToken(localUser);

                // Syncing the Challenge DB User table
                await SyncChallengeUserTable(localUser, accessToken);

                // Syncing the Loyalty DB Loyalty table
                await SyncLoyaltyTable(isCreate, localUser, accessToken);

                // Syncing the Game DB User table
                await SyncGameUserTable(localUser, accessToken);

                return(Ok(new TokenModel(accessToken, refreshToken)));
            }
            catch (Exception)
            {
                return(BadRequest(_localizer.GetString("LoginFailed")));
            }
        }
Пример #7
0
        public async Task <IActionResult> Google([FromBody] GoogleAuthViewModel model)
        {
            using (var Client = new HttpClient())
            {
                // 1.generate an app access token
                var url = $"https://www.googleapis.com/oauth2/v4/token?code={model.Code}&client_id={_googleAuthSettings.ClientId}&client_secret={_googleAuthSettings.ClientSecret}&redirect_uri=http://localhost:5000/google-auth.html&grant_type=authorization_code";
                var uri = new Uri(url);
                Client.BaseAddress = uri;


                Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, uri);

                HttpResponseMessage httpResponseMessage = await Client.SendAsync(req);

                if (!httpResponseMessage.IsSuccessStatusCode)
                {
                    return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid google token.", ModelState)));
                }

                httpResponseMessage.EnsureSuccessStatusCode();
                HttpContent httpContent    = httpResponseMessage.Content;
                var         responseString = await httpContent.ReadAsStringAsync();

                var resultData = JsonConvert.DeserializeObject <GoogleAppAccessToken>(responseString);

                var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://www.googleapis.com/plus/v1/people/me/openIdConnect?access_token={resultData.AccessToken}");

                // HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                // response.Content = new StringContent(userAccessTokenValidationResponse, Encoding.UTF8, "application/json");
                var userInfo = JsonConvert.DeserializeObject <GoogleUserData>(userAccessTokenValidationResponse);


                // 4. ready to create the local user account (if necessary) and jwt
                var user = await _userManager.FindByEmailAsync(userInfo.Email);

                if (user == null)
                {
                    var appUser = new AppUser
                    {
                        FirstName  = userInfo.GivenName,
                        LastName   = userInfo.FamilyName,
                        GoogleId   = userInfo.Sub,
                        Email      = userInfo.Email,
                        UserName   = userInfo.Email,
                        PictureUrl = userInfo.Picture
                    };

                    var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8));

                    await _userManager.AddToRoleAsync(appUser, "Member");


                    if (!result.Succeeded)
                    {
                        return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState)));
                    }

                    await _appDbContext.QuanUsers.AddAsync(new QuanUser { IdentityId = appUser.Id });

                    await _appDbContext.SaveChangesAsync();
                }

                // generate the jwt for the local user...
                var localUser = await _userManager.FindByNameAsync(userInfo.Email);


                if (localUser == null)
                {
                    return(BadRequest(Errors.AddErrorToModelState("login_failure", "Failed to create local user account.", ModelState)));
                }
                var Roles = await _userManager.GetRolesAsync(localUser);

                var jwt = await Tokens.GenerateJwt(_jwtFactory.GenerateClaimsIdentity(localUser.UserName, localUser.Id, Roles),
                                                   _jwtFactory, localUser.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });

                return(new OkObjectResult(jwt));
            }
        }
Пример #8
0
        public async Task <IActionResult> Google([FromBody] GoogleAuthViewModel model)
        {
            var googleUser = await _googleService.GetAccountAsync(model.AccessToken);

            if (string.IsNullOrEmpty(googleUser.Sub))
            {
                return(BadRequest("Invalid google token."));
            }

            // 4. ready to create the local user account (if necessary) and jwt
            var user         = GetUserByExternalId(googleUser.Sub, ExternalProviderTyper.Google);
            var isCreate     = user == null;
            var refreshToken = _tokenService.GenerateRefreshToken();
            var projectPath  = _hostingEnvironment.ContentRootPath;

            if (user == null)
            {
                var appUser = new ApplicationUser
                {
                    FirstName  = googleUser.GivenName,
                    LastName   = googleUser.FamilyName,
                    GoogleId   = googleUser.Sub,
                    Email      = googleUser.Email,
                    Nickname   = Regex.Replace(googleUser.Name, @"[^\w]", "").ToLower(),
                    UserName   = Guid.NewGuid().ToString(),
                    PictureUrl = SaveImageUrlToDisk.SaveImage(googleUser.Picture, projectPath, ImageFormat.Jpeg),
                    Birthday   = googleUser.Birthday != null?DateTime.ParseExact(googleUser.Birthday, "MM/dd/yyyy", CultureInfo.InvariantCulture) : DateTime.MinValue,
                                     RefreshToken = refreshToken
                };

                if (!IsEmailUnique(appUser.Email))
                {
                    return(BadRequest("Email baska bir kullaniciya ait."));
                }

                appUser.CreationDate = DateTime.Now;
                var result = await userManager.CreateAsync(appUser, _randomPasswordHelper.GenerateRandomPassword());

                if (!result.Succeeded)
                {
                    return(new BadRequestObjectResult(result.Errors.FirstOrDefault()));
                }
            }

            // generate the jwt for the local user...
            var localUser = GetUserByExternalId(googleUser.Sub, ExternalProviderTyper.Google);

            if (localUser == null)
            {
                return(BadRequest("Failed to create local user account."));
            }

            var accessToken = _tokenService.GenerateAccessToken(localUser);

            await _spotPlayerSyncService.SyncSpotPlayerTableAsync(new CreateOrUpdateSpotPlayerViewModel
            {
                FirstName  = localUser.FirstName,
                LastName   = localUser.LastName,
                Nickname   = localUser.Nickname,
                UserId     = localUser.Id,
                PictureUrl = localUser.PictureUrl,
                Latitude   = localUser.Latitude,
                Longitude  = localUser.Longitude
            }, accessToken);

            return(Ok(new TokenModel(accessToken, refreshToken)));
        }