/// <summary> /// Tries to log the user in by making an API call to our website /// </summary> /// <param name="email">The user's email</param> /// <param name="password">The user's password</param> /// <returns> /// In case login fails, the returned string is an error message to display /// Otherwise, null string is returned /// </returns> public async Task <string> LogInAsync(string email, string password) { // Prepare user data to send var url = "https://localhost:44306/" + ApiRoutes.LoginRoute; // TODO: Put host in configuration var credentials = new LoginCredentialsApiModel { Email = email, Password = password }; // Make a POST request to the API and catch the response var result = await WebRequests.PostAsync <ApiResponse <LoginResultApiModel> >(url, credentials); // If response was null if (result?.ServerResponse == null) { return(LocalizationResource.UnableToConnectWithWeb); } // We got the response, check if we successfully logged in if (result.ServerResponse.Successful) { // User is logged in, store the data in database var user = mUserMapper.Map(result.ServerResponse.Response); mUserRepository.SaveNewUserData(user); // Return no error return(null); } // We got the response, but logging in didnt succeed, return the error return(result.ServerResponse.ErrorMessage); }
public async Task <IActionResult> Login( [FromBody] LoginCredentialsApiModel loginCredentials) { try { var result = await loginService.LogInAsync(loginCredentials.UidToken, loginCredentials.PhoneNumber); return(Ok(new ResponseApiModel <LoginResultApiModel> { IsSuccessfull = true, Response = result })); } catch (FirebaseAdmin.FirebaseException) { return(BadRequest(new ResponseApiModel <bool> { IsSuccessfull = false, ErrorMessage = "Wrong firebase user token." })); } catch (InvalidDataException ex) { return(BadRequest(new ResponseApiModel <bool> { IsSuccessfull = false, ErrorMessage = ex.Message })); } catch (UnauthorizedAccessException ex) { return(StatusCode((int)HttpStatusCode.Forbidden, new ResponseApiModel <bool> { IsSuccessfull = false, ErrorMessage = ex.Message })); } catch (KeyNotFoundException ex) { return(NotFound(new ResponseApiModel <bool> { IsSuccessfull = false, ErrorMessage = ex.Message })); } catch (Exception) { return(StatusCode((int)HttpStatusCode.InternalServerError, new ResponseApiModel <bool> { IsSuccessfull = false })); } }
public async Task <ActionResult <ApiResponse <LoginResultApiModel> > > LogIn([FromBody] LoginCredentialsApiModel loginCredentials) { var invalidErrorMessage = "Invalid username or password"; var errorReposnse = new GeneralApiResponse <LoginResultApiModel> { Error = invalidErrorMessage }; var user = await _userManager.FindByEmailAsync(loginCredentials.Username); if (user == null) { return(BadRequest(errorReposnse)); } var isValidPassword = await _userManager.CheckPasswordAsync(user, loginCredentials.Password); if (!isValidPassword) { return(BadRequest(errorReposnse)); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), new Claim(ClaimsIdentity.DefaultNameClaimType, loginCredentials.Username), new Claim(ClaimTypes.NameIdentifier, user.Id) }; // Create the credentials var credentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])), SecurityAlgorithms.HmacSha256); // Generate the Jwt token var token = new JwtSecurityToken( issuer: _configuration["Jwt:Issuer"], audience: _configuration["Jwt:Audience"], claims: claims, expires: DateTime.Now.AddMonths(3), signingCredentials: credentials); return(Ok(new GeneralApiResponse <LoginResultApiModel> { Response = new LoginResultApiModel { Username = user.Email, Token = new JwtSecurityTokenHandler().WriteToken(token) } })); }
public async Task <ApiResponse <LoginResultApiModel> > LoginAsync([FromBody] LoginCredentialsApiModel loginCredentials) { // Prepare the error response in case login fails var errorResponse = new ApiResponse <LoginResultApiModel> { ErrorMessage = "Invalid username of password" }; // Check if provided data is eligible if (loginCredentials?.Email == null || string.IsNullOrWhiteSpace(loginCredentials.Email)) { // Return error message to user return(errorResponse); } // Find the user in database var user = await mUserManager.FindByEmailAsync(loginCredentials.Email); // If no user was found... if (user == null) { // Return error message to user return(errorResponse); } // Check if the password is valid if (!await mUserManager.CheckPasswordAsync(user, loginCredentials.Password)) { // Return error message to user return(errorResponse); } // If we get here, we are valid and the user passed the correct login details // Return JWT token to the user so he can log in using it return(new ApiResponse <LoginResultApiModel> { // Pass back the user details and the token Response = new LoginResultApiModel { FirstName = user.FirstName, SecondName = user.SecondName, Email = user.Email, Token = user.GenerateJwtToken() } }); }
public async Task <ApiResponse <UserProfileDetailsApiModel> > LogInAsync( [FromBody] LoginCredentialsApiModel loginCredentials) { // TODO: Localize all strings // The message when we fail to login var invalidErrorMessage = "Niepoprawny login lub hasło"; var notConfirmedErrorMessage = "Podany adres email nie został potwierdzony"; // The error response for a failed login var errorResponse = new ApiResponse <UserProfileDetailsApiModel> { // Set error message ErrorMessage = invalidErrorMessage }; var errorResponse2 = new ApiResponse <UserProfileDetailsApiModel> { // Set error message ErrorMessage = notConfirmedErrorMessage }; // Make sure we have a user name if (loginCredentials?.UsernameOrEmail == null || string.IsNullOrWhiteSpace(loginCredentials.UsernameOrEmail)) { // Return error message to user return(errorResponse); } // Validate if the user credentials are correct... // Is it an email? var isEmail = loginCredentials.UsernameOrEmail.Contains("@"); // Get the user details var user = isEmail ? // Find by email await mUserManager.FindByEmailAsync(loginCredentials.UsernameOrEmail) : // Find by username await mUserManager.FindByNameAsync(loginCredentials.UsernameOrEmail); // If we failed to find a user... if (user == null) { // Return error message to user return(errorResponse); } // If we got here we have a user... // Let's validate the password // Get if password is valid var isValidPassword = await mUserManager.CheckPasswordAsync(user, loginCredentials.Password); // If the password was wrong if (!isValidPassword) { // Return error message to user return(errorResponse); } // If we get here, we are valid and the user passed the correct login details // Get username var username = user.UserName; // get user table var userDb = mContext.Users.Where(a => a.Id == user.Id).FirstOrDefault(); var roles = await mUserManager.GetRolesAsync(user); string role = ""; foreach (var r in roles) { role = r; } // Generate new refresh token for user if (userDb != null) { userDb.RefreshToken = user.GenerateJwtRefreshToken(role); } mContext.SaveChanges(); if (user.EmailConfirmed == false) { // Return error message to user return(errorResponse2); } // Return token to user return(new ApiResponse <UserProfileDetailsApiModel> { // Pass back the user details and the token Response = new UserProfileDetailsApiModel { Id = user.Id, FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, Confirmed = user.EmailConfirmed, Username = user.UserName, Token = user.GenerateJwtToken(role), Role = role } }); }
public async Task <ApiResponse <UserProfileDetailsApiModel> > LogInAsync([FromBody] LoginCredentialsApiModel loginCredentials) { // TODO: Localize all strings // The message when we fail to login var invalidErrorMessage = "Invalid username or password"; // The error response for a failed login var errorResponse = new ApiResponse <UserProfileDetailsApiModel> { // Set error message ErrorMessage = invalidErrorMessage }; // Make sure we have a user name if (loginCredentials?.UsernameOrEmail == null || string.IsNullOrWhiteSpace(loginCredentials.UsernameOrEmail)) { // Return error message to user return(errorResponse); } // Validate if the user credentials are correct... // Is it an email? var isEmail = loginCredentials.UsernameOrEmail.Contains("@"); // Get the user details var user = isEmail ? // Find by email await mUserManager.FindByEmailAsync(loginCredentials.UsernameOrEmail) : // Find by username await mUserManager.FindByNameAsync(loginCredentials.UsernameOrEmail); // If we failed to find a user... if (user == null) { // Return error message to user return(errorResponse); } // If we got here we have a user... // Let's validate the password // Get if password is valid var isValidPassword = await mUserManager.CheckPasswordAsync(user, loginCredentials.Password); // If the password was wrong if (!isValidPassword) { // Return error message to user return(errorResponse); } // If we get here, we are valid and the user passed the correct login details // Get username var username = user.UserName; // Return token to user return(new ApiResponse <UserProfileDetailsApiModel> { // Pass back the user details and the token Response = new UserProfileDetailsApiModel { FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, Username = user.UserName, Token = user.GenerateJwtToken() } }); }
public async Task <ApiResponse <UserProfileDetailsApiModel> > LogInAsync([FromBody] LoginCredentialsApiModel loginCredentials) { //Create default error message var errorResponse = new ApiResponse <UserProfileDetailsApiModel> { ErrorMessage = UserMessages.InvalidUserNameOrPassword }; return(await TaskManager.Run(async() => { // Validate if the user credentials are correct... // Is it an email? var isEmail = loginCredentials.UsernameOrEmail.Contains("@"); // Get the user details var user = isEmail ? // Find by email await mUserManager.Users .Include(x => x.Employee) .FirstOrDefaultAsync(y => y.Email == loginCredentials.UsernameOrEmail) : // Find by username await mUserManager.Users .Include(x => x.Employee) .FirstOrDefaultAsync(y => y.UserName == loginCredentials.UsernameOrEmail); // If we failed to find a user... if (user == null) { // Return error message to user return errorResponse; } // If we got here we have a user... // Let's validate the password // Check if password is valid var isValidPassword = await mUserManager.CheckPasswordAsync(user, loginCredentials.Password); // If the password was wrong if (!isValidPassword) { // Return error message to user return errorResponse; } // Get if the user is confirm var isConfirmed = await mUserManager.IsEmailConfirmedAsync(user); // if not confirm if (!isConfirmed) { errorResponse.ErrorMessage = UserMessages.EmailNotConfirmed; // Return error message to user return errorResponse; } // If we get here, we are valid and the user passed the correct login details // Get username var username = user.UserName; ////Sign user in with the valid credentials //var res = await mSignInManager.PasswordSignInAsync(user, loginCredentials.Password, true, false); var a = user.Employee; // Return token to user return new ApiResponse <UserProfileDetailsApiModel> { // Pass back the user details and the token Response = new UserProfileDetailsApiModel { FirstName = user.Employee.FirstName, LastName = user.Employee.LastName, Username = user.UserName, Email = user.Email, Token = user.GenerateJwtToken(), } }; })); }
public async Task <ApiResponse <LoginResultApiModel> > LogIn([FromBody] LoginCredentialsApiModel loginCredentials) { var invalidErrorMessage = "Invalid username or password"; var errorResponse = new ApiResponse <LoginResultApiModel> { ErrorMessage = invalidErrorMessage }; if (loginCredentials?.UsernameOrEmail == null || string.IsNullOrWhiteSpace(loginCredentials.UsernameOrEmail)) { return(errorResponse); } var isEmail = loginCredentials.UsernameOrEmail.Contains("@"); var user = isEmail ? await mUserManager.FindByEmailAsync(loginCredentials.UsernameOrEmail) : await mUserManager.FindByNameAsync(loginCredentials.UsernameOrEmail); if (user == null) { return(errorResponse); } var isValidPassword = await mUserManager.CheckPasswordAsync(user, loginCredentials.Password); if (!isValidPassword) { return(errorResponse); } var username = user.UserName; var claims = new[] { // Unique ID for this token new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), // The username using the Identity name so it fills out the HttpContext.User.Identity.Name value new Claim(ClaimsIdentity.DefaultNameClaimType, username), }; // Create the credentials used to generate the token var credentials = new SigningCredentials( new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])), SecurityAlgorithms.HmacSha256); // Generate the Jwt Token var token = new JwtSecurityToken( issuer: Configuration["Jwt:Issuer"], audience: Configuration["Jwt:Audience"], claims: claims, signingCredentials: credentials, expires: DateTime.Now.AddMonths(3) ); // Return token to user return(new ApiResponse <LoginResultApiModel> { Response = new LoginResultApiModel { FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, Username = user.UserName, Token = new JwtSecurityTokenHandler().WriteToken(token) } }); }
public async Task <ApiResponse <LoginResultApiModel> > LogInAsync([FromBody] LoginCredentialsApiModel loginCredentials) { // TODO: Localize all strings // The message when we fail to login var invalidErrorMessage = "Invalid username or password"; // The error response for a failed login var errorResponse = new ApiResponse <LoginResultApiModel> { // Set error message ErrorMessage = invalidErrorMessage }; // Make sure we have a user name if (loginCredentials?.UsernameOrEmail == null || string.IsNullOrWhiteSpace(loginCredentials.UsernameOrEmail)) { // Return error message to user return(errorResponse); } // Validate if the user credentials are correct... // Is it an email? var isEmail = loginCredentials.UsernameOrEmail.Contains("@"); // Get the user details var user = isEmail ? // Find by email await mUserManager.FindByEmailAsync(loginCredentials.UsernameOrEmail) : // Find by username await mUserManager.FindByNameAsync(loginCredentials.UsernameOrEmail); // If we failed to find a user... if (user == null) { // Return error message to user return(errorResponse); } // If we got here we have a user... // Let's validate the password // Get if password is valid var isValidPassword = await mUserManager.CheckPasswordAsync(user, loginCredentials.Password); // If the password was wrong if (!isValidPassword) { // Return error message to user return(errorResponse); } // If we get here, we are valid and the user passed the correct login details // Get username var username = user.UserName; // Set our tokens claims var claims = new[] { // Unique ID for this token new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), // The username using the Identity name so it fills out the HttpContext.User.Identity.Name value new Claim(ClaimsIdentity.DefaultNameClaimType, username), }; // Create the credentials used to generate the token var credentials = new SigningCredentials( // Get the secret key from configuration new SymmetricSecurityKey(Encoding.UTF8.GetBytes(IoCContainer.Configuration["Jwt:SecretKey"])), // Use HS256 algorithm SecurityAlgorithms.HmacSha256); // Generate the Jwt Token var token = new JwtSecurityToken( issuer: IoCContainer.Configuration["Jwt:Issuer"], audience: IoCContainer.Configuration["Jwt:Audience"], claims: claims, signingCredentials: credentials, // Expire if not used for 3 months expires: DateTime.Now.AddMonths(3) ); // Return token to user return(new ApiResponse <LoginResultApiModel> { // Pass back the user details and the token Response = new LoginResultApiModel { FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, Username = user.UserName, Token = new JwtSecurityTokenHandler().WriteToken(token) } }); }