Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvement/sc 230 google login #23

Merged
merged 6 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions SmartCharger.Business/Interfaces/IGoogleAuthService.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@


using SmartCharger.Business.DTOs;
using SmartCharger.Business.DTOs;

namespace SmartCharger.Business.Interfaces
{
public interface IGoogleAuthService
{
Task<LoginResponseDTO> GetUserInfoAsync(string accessToken);
Task<LoginResponseDTO> GetUserInfoFromAuthCodeAsync(string authorizationCode);
}

}
}
2 changes: 1 addition & 1 deletion SmartCharger.Business/Interfaces/IGoogleLoginService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ namespace SmartCharger.Business.Interfaces
{
public interface IGoogleLoginService
{
Task<LoginResponseDTO> LoginWithGoogleAsync(string googleLoginDTO);
Task<LoginResponseDTO> LoginWithGoogleAsync(string authorizationCode);
}
}
99 changes: 60 additions & 39 deletions SmartCharger.Business/Services/GoogleAuthService.cs
Original file line number Diff line number Diff line change
@@ -1,63 +1,84 @@
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Oauth2.v2;
using Google.Apis.Services;
using SmartCharger.Business.DTOs;
using SmartCharger.Business.Interfaces;


public class GoogleAuthService : IGoogleAuthService {

public async Task<LoginResponseDTO> GetUserInfoAsync(string accessToken)
public class GoogleAuthService : IGoogleAuthService
{
try
public async Task<LoginResponseDTO> GetUserInfoFromAuthCodeAsync(string authorizationCode)
{
var credential = GoogleCredential.FromAccessToken(accessToken);
var service = new Oauth2Service(new BaseClientService.Initializer
try
{
HttpClientInitializer = credential,
ApplicationName = "Smart Charger",
});
var clientSecrets = new ClientSecrets
{
ClientId = "223586710221-3808p3ltsqf0e42ge6jun8mibsa2dt3k.apps.googleusercontent.com",
ClientSecret = "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"
};

var tokenResponse = await new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = clientSecrets
})
.ExchangeCodeForTokenAsync("user", authorizationCode, "https://developers.google.com/oauthplayground", CancellationToken.None);

var credential = new UserCredential(
new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = clientSecrets
}),
"user",
tokenResponse);

var service = new Oauth2Service(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Smart Charger",
});

var userInfo = await service.Userinfo.Get().ExecuteAsync();
var userInfo = await service.Userinfo.Get().ExecuteAsync();

if (userInfo == null)
if (userInfo == null)
{
return new LoginResponseDTO
{
Success = false,
Message = "Invalid authorization code."
};
}

return new LoginResponseDTO
{
Success = true,
User = new UserDTO
{
Email = userInfo.Email,
FirstName = userInfo.Name,
LastName = userInfo.FamilyName,
}
};
}
catch (GoogleApiException ex) when (ex.HttpStatusCode == System.Net.HttpStatusCode.Unauthorized)
{
return new LoginResponseDTO
{
Success = false,
Message = "Invalid access token."
Message = "Invalid authorization code."
};
}

return new LoginResponseDTO
catch (Exception ex)
{
Success = true,
User = new UserDTO
return new LoginResponseDTO
{
Email = userInfo.Email,
FirstName = userInfo.Name,
LastName = userInfo.FamilyName,
}
};
}
catch (GoogleApiException ex) when (ex.HttpStatusCode == System.Net.HttpStatusCode.Unauthorized)
{
return new LoginResponseDTO
{
Success = false,
Message = "Invalid access token."
};
}
catch (Exception ex)
{
return new LoginResponseDTO
{
Success = false,
Message = "An error occurred: " + ex.Message
};
Success = false,
Message = "An error occurred: " + ex.Message
};
}
}
}

}

16 changes: 8 additions & 8 deletions SmartCharger.Business/Services/GoogleLoginService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using Google.Apis.Auth;
using Google.Apis.Oauth2.v2;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using SmartCharger.Business.DTOs;
using SmartCharger.Business.Interfaces;
using SmartCharger.Data;
Expand All @@ -9,7 +7,7 @@

namespace SmartCharger.Business.Services
{
public class GoogleLoginService : IGoogleLoginService
public class GoogleLoginService : IGoogleLoginService
{
private readonly SmartChargerContext _context;
private readonly IGoogleAuthService _googleAuthService;
Expand All @@ -21,11 +19,11 @@ public GoogleLoginService(SmartChargerContext context, IGoogleAuthService google

}

public async Task<LoginResponseDTO> LoginWithGoogleAsync(string accessToken)
public async Task<LoginResponseDTO> LoginWithGoogleAsync(string authorizationCode)
{
AuthService authService = new AuthService();

var response = await _googleAuthService.GetUserInfoAsync(accessToken);
var response = await _googleAuthService.GetUserInfoFromAuthCodeAsync(authorizationCode);

if (!response.Success)
{
Expand All @@ -36,12 +34,15 @@ public async Task<LoginResponseDTO> LoginWithGoogleAsync(string accessToken)

var user = await _context.Users.FirstOrDefaultAsync(u => u.Email == googleUser.Email);

var nameParts = googleUser.FirstName.Split(' ');
var firstName = nameParts[0];

if (user == null)
{
user = new User
{
Email = googleUser.Email,
FirstName = googleUser.FirstName,
FirstName = firstName,
LastName = googleUser.LastName,
RoleId = 2,
CreationTime = DateTime.UtcNow,
Expand Down Expand Up @@ -88,4 +89,3 @@ public async Task<LoginResponseDTO> LoginWithGoogleAsync(string accessToken)
}

}

4 changes: 2 additions & 2 deletions SmartCharger.Test/ServicesTests/GoogleLoginServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public async Task LoginWithGoogleAsync_WhenUserProvidesValidAccessToken_ShouldRe
.Options;

var googleAuthServiceMock = new Mock<IGoogleAuthService>();
googleAuthServiceMock.Setup(service => service.GetUserInfoAsync(It.IsAny<string>()))
googleAuthServiceMock.Setup(service => service.GetUserInfoFromAuthCodeAsync(It.IsAny<string>()))
.ReturnsAsync(new LoginResponseDTO
{
Success = true,
Expand Down Expand Up @@ -54,7 +54,7 @@ public async Task LoginWithGoogleAsync_WhenUserPoricdesnvalidAccessToken_ShouldR
.Options;

var googleAuthServiceMock = new Mock<IGoogleAuthService>();
googleAuthServiceMock.Setup(service => service.GetUserInfoAsync(It.IsAny<string>()))
googleAuthServiceMock.Setup(service => service.GetUserInfoFromAuthCodeAsync(It.IsAny<string>()))
.ReturnsAsync(new LoginResponseDTO
{
Success = false,
Expand Down
5 changes: 2 additions & 3 deletions SmartCharger/Controllers/GoogleLoginController.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Microsoft.AspNetCore.Mvc;
using SmartCharger.Business.DTOs;
using SmartCharger.Business.Interfaces;
using System.Threading.Tasks;

namespace SmartCharger.Controllers
{
Expand All @@ -17,9 +16,9 @@ public GoogleLoginController(IGoogleLoginService googleLoginService)
}

[HttpPost("login/google")]
public async Task<IActionResult> LoginWithGoogle([FromBody] string accessToken)
public async Task<IActionResult> LoginWithGoogle([FromBody] string authorizationCode)
{
LoginResponseDTO loginResult = await _googleLoginService.LoginWithGoogleAsync(accessToken);
LoginResponseDTO loginResult = await _googleLoginService.LoginWithGoogleAsync(authorizationCode);

if (loginResult.Success == true)
{
Expand Down
4 changes: 0 additions & 4 deletions SmartCharger/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,6 @@
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:Secret"]))
};
}).AddGoogle(options =>
{
options.ClientId = "223586710221-3808p3ltsqf0e42ge6jun8mibsa2dt3k.apps.googleusercontent.com";
options.ClientSecret = "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";
});


Expand Down