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

Fix/Login with Google #116

Merged
merged 2 commits into from
Jul 3, 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
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ public interface IUserService
Task<ActivationResultDto> ActivateUserAsync(string activationCode);
public Task<bool> RegisterUserWithGoogle(string username, string email, string googleId);
public Task<bool> IsTheGoogleUserRegistered(string googleId);
public Task<UserDto?> LogInWithGoogle(string username, string googleId);
public Task<LogInResult> LogInWithGoogle(string email, string googleId);
}
31 changes: 19 additions & 12 deletions TutorLizard.BusinessLogic/Services/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,27 @@ public async Task<LogInResult> LogIn(string username, string password)
};
}

public async Task<UserDto?> LogInWithGoogle(string username, string googleId)
public async Task<LogInResult> LogInWithGoogle(string email, string googleId)
{
var user = await _userRepository.GetAll()
.FirstOrDefaultAsync(user => user.GoogleId == googleId);
.FirstOrDefaultAsync(user =>
user.GoogleId == googleId &&
user.Email == email);

if (user == null)
{
return null;
return new LogInResult()
{
ResultCode = LogInResultCode.UserNotFound,
User = null
};
}

if (user.GoogleId == googleId)
return user.ToDto();

return null;
return new LogInResult()
{
ResultCode = LogInResultCode.Success,
User = user.ToDto()
};
}


Expand Down Expand Up @@ -106,7 +113,10 @@ public async Task<bool> RegisterUserWithGoogle(string username, string email, st
Name = username,
UserType = UserType.Regular,
Email = email,
GoogleId = googleId
GoogleId = googleId,
IsActive = true,
ActivationCode = "Registered with Google Auth",
PasswordHash = null,
};

await _userRepository.Create(user);
Expand All @@ -116,10 +126,7 @@ public async Task<bool> RegisterUserWithGoogle(string username, string email, st

public async Task<bool> IsTheGoogleUserRegistered(string googleId)
{
if (await _userRepository.GetAll().AnyAsync(user => user.GoogleId == googleId))
return true;

return false;
return await _userRepository.GetAll().AnyAsync(user => user.GoogleId == googleId);
}

public async Task<ActivationResultDto> ActivateUserAsync(string activationCode)
Expand Down
24 changes: 13 additions & 11 deletions TutorLizard.Web/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,36 +71,38 @@ public async Task<IActionResult> GoogleResponse()
return RedirectToAction("Login");
}

var claims = result.Principal.Identities.FirstOrDefault()?.Claims.ToList();
var claims = result?.Principal?.Identities.FirstOrDefault()?.Claims.ToList();

var claimNameIdentifier = claims?.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
var claimName = claims?.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;
var claimEmail = claims?.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
string claimGoogleId = claims?.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value ?? "";
string claimUsername = claims?.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value ?? "";
string claimEmail = claims?.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value ?? "";

if(!(await _userAuthenticationService.IsGoogleUserRegistered(claimNameIdentifier)))
await _userAuthenticationService.LogOutAsync();

if(!(await _userAuthenticationService.IsGoogleUserRegistered(claimGoogleId)))
{
try
{
await _userAuthenticationService.RegisterUserWithGoogle(claimName, claimEmail, claimNameIdentifier);
await _userAuthenticationService.RegisterUserWithGoogle(claimUsername, claimEmail, claimGoogleId);
}
catch (Exception ex)
catch
{
_uiMessagesService.ShowFailureMessage("Rejestracja użytkownika za pomocą konta google się nie powiodła");
return RedirectToAction("Login");
}
}

var loggedIn = await _userAuthenticationService.LogInWithGoogleAsync(claimName,claimNameIdentifier);
var logInResult = await _userAuthenticationService.LogInWithGoogleAsync(claimEmail, claimGoogleId);

if (!loggedIn)
if (logInResult.ResultCode != LogInResultCode.Success)
{
_uiMessagesService.ShowFailureMessage("Logowanie nieudane.");
return RedirectToAction("Login");
}

return RedirectToAction("Index", "Home");
}
catch (Exception ex)
catch
{
_uiMessagesService.ShowFailureMessage("Logowanie nieudane.");
return RedirectToAction("Login");
Expand All @@ -121,7 +123,7 @@ public async Task<IActionResult> Login(LoginModel model)
{
if (ModelState.IsValid)
{
var logInResult = await _userAuthenticationService.LogInAsync(model.UserName, model.Password);
var logInResult = await _userAuthenticationService.LogInWithPasswordAsync(model.UserName, model.Password);

switch (logInResult.ResultCode)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ public interface IUserAuthenticationService

{
int? GetLoggedInUserId();
Task<LogInResult> LogInAsync(string username, string password);
Task<LogInResult> LogInWithPasswordAsync(string username, string password);
public Task LogOutAsync();
public Task<bool> IsGoogleUserRegistered(string googleid);
public Task<bool> RegisterUserWithGoogle(string username, string email, string googleId);
public Task<bool> LogInWithGoogleAsync(string username, string googleId);
public Task<bool> IsGoogleUserRegistered(string? googleId);
public Task<bool> RegisterUserWithGoogle(string? username, string? email, string? googleId);
public Task<LogInResult> LogInWithGoogleAsync(string email, string googleId);
Task<(bool, string)> RegisterUser(string username, UserType type, string email, string password);
void SendActivationEmail(string email, string activationCode);
}
119 changes: 50 additions & 69 deletions TutorLizard.Web/Services/UserAuthenticationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,77 +28,16 @@ public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUser
_userRepository = userRepository;
}

public async Task<LogInResult> LogInAsync(string username, string password)
public async Task<LogInResult> LogInWithPasswordAsync(string username, string password)
{
var logInResult = await _userService.LogIn(username, password);

if (logInResult.ResultCode == LogInResultCode.Success && logInResult.User != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, logInResult.User.Email),
new Claim(ClaimTypes.Name, logInResult.User.Name),
new Claim(ClaimTypes.NameIdentifier, logInResult.User.Id.ToString()),
new Claim(ClaimTypes.Role, logInResult.User.UserType.ToString())
};

var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
{
AllowRefresh = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
IsPersistent = true,
};

if (_httpContextAccessor.HttpContext != null)
{
await _httpContextAccessor.HttpContext.SignInAsync("CookieAuth",
new ClaimsPrincipal(claimsIdentity),
authProperties);
}
}

return logInResult;
return await SignInUserAsync(logInResult);
}

public async Task<bool> LogInWithGoogleAsync(string username, string googleId)
public async Task<LogInResult> LogInWithGoogleAsync(string email, string googleId)
{
var user = await _userService.LogInWithGoogle(username, googleId);

if (user is null)
{
return false;
}

var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Role, user.UserType.ToString())
};

var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
{
AllowRefresh = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
IsPersistent = true,
};

if (_httpContextAccessor.HttpContext is null)
return false;

await _httpContextAccessor.HttpContext.SignOutAsync();
await _httpContextAccessor.HttpContext.SignInAsync("CookieAuth",
new ClaimsPrincipal(claimsIdentity),
authProperties);

return true;
var loginResult = await _userService.LogInWithGoogle(email, googleId);
return await SignInUserAsync(loginResult);
}

public async Task LogOutAsync()
Expand All @@ -122,14 +61,24 @@ private string GenerateActivationCode()
return Guid.NewGuid().ToString();
}

public Task<bool> RegisterUserWithGoogle(string username, string email, string googleId)
public Task<bool> RegisterUserWithGoogle(string? username, string? email, string? googleId)
{
if (String.IsNullOrWhiteSpace(username) ||
String.IsNullOrWhiteSpace(email) ||
String.IsNullOrWhiteSpace(googleId))
{
return Task.FromResult(false);
}
return _userService.RegisterUserWithGoogle(username, email, googleId);
}

public async Task<bool> IsGoogleUserRegistered(string googleid)
public async Task<bool> IsGoogleUserRegistered(string? googleId)
{
return await _userService.IsTheGoogleUserRegistered(googleid);
if (String.IsNullOrWhiteSpace(googleId))
{
return false;
}
return await _userService.IsTheGoogleUserRegistered(googleId);
}

public int? GetLoggedInUserId()
Expand Down Expand Up @@ -179,4 +128,36 @@ public void SendActivationEmail(string userEmail, string activationCode)
}
}

private async Task<LogInResult> SignInUserAsync(LogInResult logInResult)
{
if (logInResult.ResultCode == LogInResultCode.Success && logInResult.User != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, logInResult.User.Email),
new Claim(ClaimTypes.Name, logInResult.User.Name),
new Claim(ClaimTypes.NameIdentifier, logInResult.User.Id.ToString()),
new Claim(ClaimTypes.Role, logInResult.User.UserType.ToString())
};

var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
{
AllowRefresh = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
IsPersistent = true,
};

if (_httpContextAccessor.HttpContext != null)
{
await _httpContextAccessor.HttpContext.SignInAsync("CookieAuth",
new ClaimsPrincipal(claimsIdentity),
authProperties);
}
}

return logInResult;
}
}
Loading