public bool AreEqual(GetUserDto other) { if (IsDeleted != other.IsDeleted) { return(false); } if (Role != other.Role) { return(false); } if (Email != other.Email) { return(false); } if (FirstName != other.FirstName) { return(false); } if (LastName != other.LastName) { return(false); } if (Login != other.Login) { return(false); } if (Id != other.Id) { return(false); } return(true); }
public void Execute(GetUserDto request) { var user = Context.Users.Find(request.Id); if (user == null) { throw new EntityNotFoundException(); } if (request.Email != user.Email && Context.Users.Any(u => u.Email == request.Email)) { throw new EntityAlreadyExistsException(); } if (request.Password != null) { user.Password = this.ComputeSha256Hash(request.Password); } user.FirstName = request.FirstName; user.LastName = request.LastName; user.Email = request.Email; user.Username = request.Username; user.RoleId = request.RoleId; Context.SaveChanges(); }
public async Task GetUserById_ValidId_ReturnsMappedUser() { var user = new User { Email = "*****@*****.**", FirstName = "Test", Id = 1, IsDeleted = false, LastName = "Testowy", Login = "******", Role = "User" }; GetUserDto mappedUser = new GetUserDto { Email = "*****@*****.**", Role = "User", Id = 1, IsDeleted = false, LastName = "Testowy", Login = "******", FirstName = "Test" }; var id = 1; _usersRepositoryMock.Setup(x => x.GetUserById(id, true)).ReturnsAsync(user); var service = new UsersService(_usersRepositoryMock.Object, _appSettingsMock.Object); var result = await service.GetUserById(id); Assert.True(mappedUser.AreEqual(result.Value)); }
private async Task <string> CreateToken(GetUserDto user) { List <Claim> claims = new List <Claim>() { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Email, user.Email), }; const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(sec)); SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature); SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor() { Issuer = GlobalConstants.JwtTokenIssuer, Audience = GlobalConstants.JwtTokenIssuer, Subject = new ClaimsIdentity(claims), NotBefore = DateTime.UtcNow, Expires = DateTime.UtcNow.AddDays(1), SigningCredentials = creds }; JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(token)); }
public GetUserDto Authenticate(string username, string password) { var user = context.Users .SingleOrDefault(x => x.Username == username && x.Password == ComputeSha256Hash(password)); // return null if user not found if (user == null) { return(null); } // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Username.ToString()), new Claim(ClaimTypes.Role, user.UserRole.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var result = new GetUserDto { Id = user.Id, Username = user.Username, Token = tokenHandler.WriteToken(token), UserRole = user.UserRole }; return(result); }
public async Task <GetUserDto> GetById(int id) { GetUserDto userDto = null; try { User user = await(from u in _context.Users where u.Id == id select u).FirstOrDefaultAsync(); //if (user == null || !BC.Verify(authUser.Password, user.Password)) if (user != null) { userDto = new GetUserDto() { Id = user.Id, ActivateKey = user.ActivateKey, Name = user.Name, Status = user.Status }; } } catch (System.Exception) { } return(userDto); }
public async void testCreateUser() { var client = _factory.CreateClient(); var user = new CreateUserDto { email = _email, password = _password, userName = _userName }; var userResponse = new GetUserDto { email = user.email, userName = user.userName }; var expectedResponse = new ControllerResponse <GetUserDto> { success = true, data = userResponse }; // Act var actualResponse = await client.testSuccessPostAsync <GetUserDto, CreateUserDto>("/api/users", user); // Assert expectedResponse.ShouldDeepEqual(actualResponse); }
private UserTokenDto GenerateToken(GetUserDto user) { Claim[] claims = new[] { new Claim(nameof(User.Id), user.Id), new Claim(nameof(User.Email), user.Email), new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()), new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(_configuration.TokenExpirationPeriodInDay)).ToUnixTimeSeconds().ToString()), }; JwtSecurityToken token = new JwtSecurityToken( new JwtHeader(new SigningCredentials(_configuration.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)), new JwtPayload(claims)); string tokenValue = new JwtSecurityTokenHandler().WriteToken(token); UserTokenDto tokenResponse = new UserTokenDto { User = user, AccessToken = tokenValue, ExpiresIn = (int)TimeSpan.FromDays(_configuration.TokenExpirationPeriodInDay).TotalSeconds }; return(tokenResponse); }
public async Task <IActionResult> UpdateUser(UpdateUserDto updatedUser) { GetUserDto usr = await _userService.UpdateUser(updatedUser); if (usr == null) { return(NotFound()); } return(Ok(usr)); }
public GetUserDto GetById(int id) { User user = context.Users .FirstOrDefault(u => u.Id == id); if (user == null) { return(null); } return(GetUserDto.FromUser(user)); }
public IActionResult GetUser(string id) { ServiceResponse <GetUserDto> response = new ServiceResponse <GetUserDto>(); GetUserDto userToReturn = _userRepository.MapUser(id); response.Data = userToReturn; response.Message = "Success"; response.Success = true; return(Ok(response)); }
public IActionResult Put(int id, [FromBody] GetUserDto dto) { try { dto.Id = id; _editUserCommand.Execute(dto); return(StatusCode(204, "Successfully updated user.")); } catch { return(StatusCode(422, "Error while trying to update user.")); } }
public async Task <GetUserDto> UpdateDataUser(string id, GetUserDto dto) { var entity = await _userManager.FindByIdAsync(id); entity.FirstName = dto.FirstName; entity.LastName = dto.LastName; entity.Birth = dto.Birth; entity.Email = dto.Email; await _userManager.UpdateAsync(entity); return(await AccountUpdateInfoDto(entity.Id)); }
public GetUserDto Delete(int id) { var existing = context.Users.FirstOrDefault(u => u.Id == id); if (existing == null) { return(null); } context.Users.Remove(existing); context.SaveChanges(); return(GetUserDto.FromUser(existing)); }
public async Task <ApiResult <GetUserDto> > Get(int id) { var user = await _userService.GetByIdAsync(id); if (user == null) { return(NotFound()); } GetUserDto userDto = _mapper.Map <GetUserDto>(user); var roles = await _userManager.GetRolesAsync(user); userDto.Role = roles.FirstOrDefault(); return(userDto); }
public async Task <IActionResult> GetUserInfo(GetUserDto getUserDto) { var objFromDb = _unitOfWork.User.GetFirstOrDefault(c => c.Email.Equals(getUserDto.Email.ToLower())); APIResponse <User> response = new APIResponse <User>() { Data = objFromDb }; if (objFromDb == null) { response.Success = false; response.Message = "User not found"; return(NotFound(response)); } return(Ok(response)); }
private string GenerateToken(GetUserDto user) { var claims = new[] { new Claim(nameof(Domain.Users.User.Id), user.Id), new Claim(nameof(Domain.Users.User.Email), user.Email), new Claim(nameof(Domain.Users.User.Interests), user.Interests ?? string.Empty), new Claim(ClaimTypes.Role, user.Role), new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()), new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()), }; var token = new JwtSecurityToken( new JwtHeader(new SigningCredentials(_configuration.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)), new JwtPayload(claims)); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public object GetUser([FromBody] GetUserDto model) { //var token = Request.Cookies.FirstOrDefault(e => e.Key == "authtoken").Value; //JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); //var parameters = new TokenValidationParameters //{ // //"JwtKey": "just some key with true random digit \"4\" that is hopefully random enough", // ValidIssuer = "kradle.ru", // //IssuerSigningKeys = openIdConfig.SigningKeys //}; //SecurityToken validatedToken; //var claimsPrincipal = handler.ValidateToken(token, parameters, out validatedToken); IdentityUser user = _userManager.Users.SingleOrDefault(r => r.Email == (model.Email ?? String.Empty)); return(new JsonResult(Json(user))); }
public GetUserDto Execute(int request) { var user = Context.Users.Find(request); if (user == null) { throw new EntityNotFoundException(); } var usertDto = new GetUserDto { Id = user.Id, FirstName = user.FirstName, LastName = user.LastName, Username = user.Username, Email = user.Email }; return(usertDto); }
private static (bool, string) Validate(GetUserDto data) { var valid = true; var message = new List <string>(); // Validate data if (string.IsNullOrWhiteSpace(data.Email)) { valid = false; message.Add("Email is invalid."); } if (string.IsNullOrWhiteSpace(data.Password)) { valid = false; message.Add("Password is invalid."); } return(valid, string.Join("\n", message)); }
public IActionResult GetUser([FromQuery] GetUserInput input) { try { using (var scope = _provider.CreateScope()) { var userService = scope.ServiceProvider.GetService <UserService>(); var user = userService.GetUser(input.UserId); if (user == null) { return(NotFound()); } else { var dto = new GetUserDto(); dto.UserId = user.UserId; foreach (var userTravelPlan in user.UserTravelPlans) { dto.TravelPlans.Add(new TravelPlanDto { Date = userTravelPlan.TravelPlan.Date, DepartureCityId = userTravelPlan.TravelPlan.DepartureCityId, Description = userTravelPlan.TravelPlan.Description, DestinationCityId = userTravelPlan.TravelPlan.DestinationCityId, IsActive = userTravelPlan.TravelPlan.IsActive, SeatCount = userTravelPlan.TravelPlan.SeatCount, TravelPlanId = userTravelPlan.TravelPlan.TravelPlanId, }); } return(Ok(dto)); } } } catch (Exception e) { return(StatusCode(500, new { Message = e.Message })); } }
public async Task <UserTokenDto> LoginUserAsync(UserLoginDto loginDto, CancellationToken ct = default) { _logger.LogInformation("Login as user = {@User}", loginDto); GetUserDto user = await _userService.GetByEmailAsync(loginDto.Email, ct); if (user == null) { _logger.LogInformation("User with email {Email} not found", loginDto.Email); throw new UserNotFoundException(); } SignInResult result = await _signInManager .PasswordSignInAsync(loginDto.Email, loginDto.Password, loginDto.RememberMe, lockoutOnFailure : false); if (result.Succeeded) { return(GenerateToken(user)); } throw new UserLoginFailedException(); }
public async Task <GetUserDto> RegisterUserAsync(UserRegistrationDto registrationDto, CancellationToken ct = default) { _logger.LogInformation("Register new user = {@User}", registrationDto); User user = _mapper.Map <User>(registrationDto); GetUserDto dbUser = await _userService.GetByEmailAsync(registrationDto.Email, ct); if (dbUser != null) { _logger.LogInformation("User with email {Email} already exists", registrationDto.Email); throw new UserAlreadyExistsException(); } IdentityResult result = await _userManager.CreateAsync(user, registrationDto.Password); if (result.Succeeded) { return(_mapper.Map <GetUserDto>(user)); } throw new UserRegistrationFailedException(string.Join(" ", result.Errors.Select(t => t.Description))); }
/// <summary> /// Get User By PublicId /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task <GetUserDto> GetUserByPublicId(string id) { bool isValid = Guid.TryParse(id, out Guid userPublicId); if (!isValid) { _customExceptionValidationService.CustomValidation("Invalid user Id", HttpStatusCode.BadRequest); } var userDetails = _userRepository.GetUserByGuid(userPublicId); if (userDetails == null) { _customExceptionValidationService.CustomValidation("User doesn't exists!", HttpStatusCode.NotFound); } var userDto = new GetUserDto { Name = userDetails.Name, EmailId = userDetails.EmailId, MobileNo = userDetails.MobileNo, Address = userDetails.Address, ProfilePic = userDetails.ProfilePic, ActivationDate = userDetails.ActivationDate, City = userDetails.City, PinCode = userDetails.PinCode, AssociatedOrganization = new OrganizationDto { Name = userDetails.Organization.Name, PublicId = Convert.ToString(userDetails.Organization.PublicId), Address = userDetails.Organization.Address, PinCode = userDetails.Organization.PinCode, ActivationDate = userDetails.Organization.ActivationDate, City = userDetails.Organization.City, Description = userDetails.Organization.Description, IsActive = userDetails.Organization.IsActive }, }; return(await Task.FromResult(userDto)); }
public async Task <ActionResult <GetUserDto> > UpdateDataUser(string id, GetUserDto dto) { return(await _userRepository.UpdateDataUser(id, dto)); }
public static async Task <HttpResponseData> RunAsync( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "users/login")] HttpRequestData req, GetUserDto data ) { // Create response var response = req.CreateResponse(); // Validate params var valid = Validate(data); if (valid.Item1) { try { // Get container var userContainer = await CosmosDb.GetContainerAsync(CosmosDb.USER_CONTAINER_ID); // Get item var query = new QueryDefinition(@$ "SELECT * FROM c WHERE c.email = @email") .WithParameter("@email", data.Email.ToLower()); var user = await CosmosDb.GetItemByQueryAsync <User>(userContainer, query); if (user != null && Utils.VerifyPassword(data.Password, user.Salt, user.Password)) { var returnUser = new ReturnUserDto() { Id = user.Id, Name = user.Name, Email = user.Email }; // Write item to response await response.WriteAsJsonAsync(returnUser); } else { // Response not found message await response.WriteAsJsonAsync("Incorrect email or password"); } } catch (CosmosException ex) { // Response error message await response.WriteAsJsonAsync(ex.Message); // Set http status code response.StatusCode = (HttpStatusCode)ex.Status; } } else { // Response invalid await response.WriteAsJsonAsync(valid.Item2); // Set http status code response.StatusCode = HttpStatusCode.BadRequest; } return(response); }