public async Task <LoginResponseModel> ProcessRequest(GoogleWithEmailRequestModel model) { var profile = await GetProfile(model.Token); // If we didn`t get email from profile, get it from model var email = profile?.Email ?? model?.Email ?? null; var userWithGoogle = _unitOfWork.Repository <ApplicationUser>().Get(x => x.GoogleId == profile.Id) .Include(x => x.VerificationTokens) .FirstOrDefault(); // If there is such user in DB - just return if (userWithGoogle != null) { var loginResponse = await _jwtService.BuildLoginResponse(userWithGoogle); return(loginResponse); } else if (userWithGoogle == null && email != null) { // Check if there is such user in DB, if so - add to it google id var existingUser = _unitOfWork.Repository <ApplicationUser>().Find(x => x.Email == email); if (existingUser != null) { existingUser.GoogleId = profile.Id; _unitOfWork.Repository <ApplicationUser>().Update(existingUser); _unitOfWork.SaveChanges(); var loginResponse = await _jwtService.BuildLoginResponse(existingUser); return(loginResponse); } else { // In other case - create new user var user = new ApplicationUser { Email = email, UserName = email, IsActive = true, RegistratedAt = DateTime.UtcNow, EmailConfirmed = false, GoogleId = profile.Id }; var result = await _userManager.CreateAsync(user); if (!result.Succeeded) { throw new CustomException(HttpStatusCode.BadRequest, "general", result.Errors.FirstOrDefault().Description); } result = await _userManager.AddToRoleAsync(user, Role.User); if (!result.Succeeded) { throw new CustomException(HttpStatusCode.BadRequest, "general", result.Errors.FirstOrDefault().Description); } var loginResponse = await _jwtService.BuildLoginResponse(user); return(loginResponse); } } else { throw new CustomException(HttpStatusCode.BadRequest, "token", "There is no user with such google id"); } }
public async Task <IActionResult> Google([FromBody] GoogleWithEmailRequestModel model) { var response = await _googleService.ProcessRequest(model); return(Json(new JsonResponse <LoginResponseModel>(response))); }