public async Task <List <Currency> > GetUserDefaultCurrencies(string username) { var userSpec = new UserSpecification(username, true); var user = (await _userRepository.ListAsync(userSpec)).FirstOrDefault(); return(user?.UserCurrencyMapping.Select(x => x.Currency).ToList()); }
public async Task <List <UserSpecification> > GetShopFavouriteSpecificationAsync(string ShopId, string openIds) { EnsureConnectionOpen(); SqlParameter[] sql = new SqlParameter[] { new SqlParameter("@ShopId", ShopId), new SqlParameter("@OpenIdIds", openIds) }; //using (var command = CreateCommand("select* from(select ROW_NUMBER() over(partition by NickName order by num desc) gnum, *from(select WeChatUsers.NickName, PurchaseRecords.Specification, sum(PurchaseRecords.Quantity) num from PurchaseRecords inner join WeChatUsers on PurchaseRecords.OpenId = WeChatUsers.OpenId where ShopId = @ShopId group by WeChatUsers.NickName, PurchaseRecords.Specification)temp) temp2 where gnum = 1", CommandType.Text, sql)) using (var command = CreateCommand("select * from(select ROW_NUMBER() over(partition by OpenId order by Num desc) gnum, * from (select OpenId,Specification, sum(Quantity) Num from PurchaseRecords where ShopId = @ShopId and charindex(','+OpenId+',',','+@OpenIdIds+',') > 0 group by OpenId,Specification )temp) temp2 where gnum = 1", CommandType.Text, sql)) //using (var command = CreateCommand("select * from PurchaseRecords where ShopName like @ShopName", CommandType.Text,sql)) { using (var dataReader = await command.ExecuteReaderAsync()) { var result = new List <UserSpecification>(); while (dataReader.Read()) { var userSpecification = new UserSpecification(); userSpecification.OpenId = dataReader["OpenId"].ToString(); userSpecification.Specification = dataReader["Specification"].ToString(); userSpecification.Num = (int)dataReader["Num"]; result.Add(userSpecification); } return(result); } } }
static void Main(string[] args) { // Cat cat = new Dog(); // Cat cat = (Cat)new Dog(); // Cat cat = new Dog().AsCat(); Cat cat = new WrappedDog(new Dog()); IExpectAlternateContact spec = UserSpecification .ForPerson() .WithName("Max") .WithSurname("Planck") .WithPrimaryContact( ContactSpecification.ForEmailAddress("*****@*****.**")); IBuildingSpecification <EmailAddress> contact = ContactSpecification.ForEmailAddress("*****@*****.**"); if (!spec.CanAdd(contact)) { Console.WriteLine("Cannot add desired contact..."); } else { spec = spec.WithAlternateContact(contact); IUser user = spec.AndNoMoreContacts().Build(); Console.WriteLine(user); } Console.ReadLine(); }
/// <summary> /// Resets user's photo to default one /// </summary> public ResetPhotoResponse ResetPhoto(ISession session, ResetPhotoRequest request) { var response = request.CreateResponse <ResetPhotoResponse>(); try { using (var uow = UnitOfWorkFactory.Create()) { var target = uow.UsersRepository.FirstMatching(UserSpecification.Id(request.TargetId)); if (target != null) { response.NewPhotoId = target.ResetPhoto(session.User); uow.Commit(); response.Success = true; } } } catch (ModeratorsRightsRequiredException) { response.Success = false; } if (response.Success) { _profileChangesNotificator.NotifyEverybodyInChatAboutProfileChanges(request.TargetId, new Dictionary <string, object> { { "PhotoId", response.NewPhotoId } }); } return(response); }
public async Task <User> GetUserByUsernameAsync(string username) { var userSpec = new UserSpecification(username); var user = (await _userRepository.ListAsync(userSpec)).FirstOrDefault(); return(user); }
public async Task <UserDto> Handle(GetUserDtoByIdQuery request, CancellationToken cancellationToken) { var userSpecification = new UserSpecification(request.UserId); var userDto = await _userRepository.FindAsync(userSpecification).Select(MapFromUserDtoToUser); return(userDto); }
public GetUserDetailsResponse GetUserDetails(ISession session, GetUserDetailsRequest request) { var response = request.CreateResponse <GetUserDetailsResponse>(); using (var uow = UnitOfWorkFactory.Create()) { Specification <User> spec = null; if (request.UserId != 0) { spec = UserSpecification.Id(request.UserId); } else if (!string.IsNullOrEmpty(request.Name)) { spec = UserSpecification.Name(request.Name); } else { return(response); //invalid request } var user = uow.UsersRepository.FirstMatching(spec); if (user != null) { response.User = user.ProjectedAs <UserDto>(); response.IsFriend = session.User.Friends.Any(p => p.Id == user.Id); uow.Attach(session.User); } } return(response); }
static void Main(string[] args) { IUser user = UserSpecification .ForMachine() .ProducedBy( ProducerSpecification .WithName("Big Co.")) .WithModel("Shiny one") .OwnedBy( LegalEntitySpecification .Initialize() .WithCompanyName("Properties Co.") .WithEmailAddress( ContactSpecification.ForEmailAddress("one@prop")) .WithPhoneNumber( ContactSpecification .ForPhoneNumber() .WithCountryCode(1) .WithAreaCode(23) .WithNumber(456)) .WithOtherContact( ContactSpecification.ForEmailAddress("two@prop")) .AndNoMoreContacts()) .Build(); Console.WriteLine(user); Console.WriteLine(); Console.ReadLine(); }
public User GetUser(string username) { var specification = new UserSpecification(username: username); var user = _userRepository.Query(specification).First(); return(user); }
public async Task <User> Handle(GetUserByIdQuery request, CancellationToken cancellationToken) { var userSpecification = new UserSpecification(request.UserId); var user = await _userRepository.FindAsync(userSpecification); return(user); }
public RemoveFromFriendsResponse RemoveFromFriends(ISession session, RemoveFromFriendsRequest request) { var response = request.CreateResponse <RemoveFromFriendsResponse>(); response.Success = true; if (session.User.Friends.All(i => i.Id != request.TargetUserId)) { response.Success = false; return(response); } using (var uow = UnitOfWorkFactory.Create()) { uow.Attach(session.User); var friend = uow.UsersRepository.FirstMatching(UserSpecification.Id(request.TargetUserId)); if (friend == null) { response.Success = false; } else { session.User.Friends.Remove(friend); uow.Commit(); } } return(response); }
/// <summary> /// </summary> public RegistrationResponse RegisterNewUser(ISession session, RegistrationRequest request) { var response = request.CreateResponse(new RegistrationResponse { Result = RegistrationResponseType.Success }); User user = null; try { user = new User(request.Name, request.Password, request.Huid, request.Sex, request.Age, request.PushUri, request.Country, request.Platform); } catch (InvalidUserRegistrationDataException) { response.Result = RegistrationResponseType.InvalidData; return(response); } using (var uow = UnitOfWorkFactory.Create()) { if (uow.UsersRepository.AnyMatching(UserSpecification.Name(user.Name))) { response.Result = RegistrationResponseType.NameIsInUse; return(response); } uow.UsersRepository.Add(user); uow.Commit(); } response.User = user.ProjectedAs <UserDto>(); session.SetUser(user); return(response); }
public async Task <UserDto> CreateUser(UserDto userDto) { var authenticationDto = new AuthenticationDto(); var userSpecification = new UserSpecification(). And(new UserNameSpecification()). And(new PasswordSpecification()). And(new UniqueUserSpecification(this.userRepository)); if (userSpecification.IsSatisfiedBy(userDto)) { string passwordSalt = ""; string passwordHash = ""; ECWRNGRfcSaltedHashManager.GenrateSaltedHash(userDto.Password, out passwordHash, out passwordSalt); var newUser = new Logins { UserName = userDto.UserName, PasswordSalt = passwordSalt, PasswordHash = passwordHash }; int identity = await this.userRepository.CreateLogin(newUser); if (identity <= 0) { userDto.AddRule("User", "Creation faild!"); } else { userDto.AddRule("Success", "Authentication is successfull."); } } return(userDto); }
public async Task <ServiceResult <UserDto> > LoginAsync(LoginDto model) { var userSpecification = new UserSpecification(model.Email, true); var user = await _userRepository.GetBySpecAsync(userSpecification); if (user == null) { var result = new ServiceResult <UserDto>(); result.ErrorMessages.Add(string.Empty, Messages.CheckYourEmailAddressOrPassword); return(result); } if (!VerifyPasswordHash(model.Password, user.PasswordHash, user.PasswordSalt)) { var result = new ServiceResult <UserDto>(); result.ErrorMessages.Add(string.Empty, Messages.CheckYourEmailAddressOrPassword); return(result); } var userDto = _mapper.Map <UserDto>(user); _logger.LogInformation("User was logged in with id: {0} at {1}", userDto.Id, DateTime.Now); return(new ServiceResult <UserDto> { Result = userDto }); }
public async Task <IActionResult> SignIn(SignInViewModel data) { ViewData["Email"] = data.Email; if (!ModelState.IsValid) { return(PartialView()); } var userSpecification = new UserSpecification() { Email = data.Email }; AuthenticationUser = await _userRepository.ReadAsync(userSpecification); if (AuthenticationUser is null) { ModelState.AddModelError("Invalid", _localizer[AuthenticationErrorMessages.InvalidData]); return(PartialView()); } var passwordVerification = _passwordHasherService.VerifyHashedPassword( user: AuthenticationUser, hashedPassword: AuthenticationUser.PassHash, providedPassword: SignInData.Password); if (passwordVerification == PasswordVerificationResult.Failed) { ModelState.AddModelError("Invalid", _localizer[AuthenticationErrorMessages.InvalidData]); return(PartialView()); } var identity = new ClaimsIdentity( authenticationType: CookieAuthenticationDefaults.AuthenticationScheme, nameType: ClaimTypes.Name, roleType: ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, AuthenticationUser.ID.ToString())); identity.AddClaim(new Claim(ClaimTypes.Name, AuthenticationUser.FullName)); identity.AddClaim(new Claim(ClaimTypes.Email, AuthenticationUser.Email)); foreach (var role in AuthenticationUser.Roles.Where(r => r.HasRole)) { identity.AddClaim(new Claim(ClaimTypes.Role, role.Name)); } var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync( scheme : CookieAuthenticationDefaults.AuthenticationScheme, principal : principal, properties : new AuthenticationProperties { IsPersistent = data.RememberMe }); return(Json(new { Route = Url.RouteUrl("default") })); }
public async Task <IActionResult> CreateAsync(UserViewModel <TUser> userModel) { var roles = await _userRoleRepository.ListAsync(); // populate the role list data not returned in post request foreach (var userRole in userModel.User.Roles) { var role = roles.Where(r => r.ID == userRole.ID).FirstOrDefault(); userRole.Name = role.Name; userRole.DisplayTitle = role.DisplayTitle; } string email = userModel.User.Email; // validate user e-mail address if (email.HasValue()) { if (!_emailValidatorService.IsValidEmail(email)) { ModelState.AddModelError("InvalidEmail", _localizer[UserErrorMessages.InvalidEmail]); } var userSpecification = new UserSpecification() { Email = email }; var duplicateUser = await _userRepository.ReadAsync(userSpecification); if (duplicateUser != null) { ModelState.AddModelError("DuplicateUser", _localizer[UserErrorMessages.DuplicateUser]); } } if (!ModelState.IsValid) { return(PartialView("_Editor", userModel)); } // persist new user to data store var newUserID = await _userRepository.CreateAsync(userModel.User, UserID); if (newUserID == 0) { return(NoContent()); } // publish user creation and invitation events so notification services can be called userModel.User.ID = newUserID; var userDTO = new UserDTO(userModel.User); var userCreatedEvent = new UserCreated(userDTO); await _mediator.Publish(userCreatedEvent); var uri = Url.Action("ReadAsync", "User", new { id = newUserID }); return(Created(uri, newUserID)); }
public void MatchesNoBasketsIfIdNotPresent() { var badId = Guid.Empty; var spec = new UserSpecification(badId); GetTestUsersCollection() .AsQueryable() .Any(spec.Criteria).ShouldBeFalse(); }
public async Task <PagedResult <UserDto> > Handle(GetUserPagedResultQuery request, CancellationToken cancellationToken) { var pagedUserSpecification = new UserSpecification(request, request.Email, request.Name); var result = await _userRepository.GetAllPagedAsync(pagedUserSpecification, request); var usersDto = result.Items.Select(MapFromUserDtoToUser); return(PagedResult <UserDto> .Create(usersDto, request.Page, request.PageSize, result.TotalPages, result.TotalItems)); }
public async Task Handle(UpdateUserRefreshTokenCommand notification, CancellationToken cancellationToken) { var userSpecification = new UserSpecification(notification.UserId); var user = await _userRepository.FindAsync(userSpecification); user.AddRefreshToken(notification.RefreshToken, notification.UserId, notification.RemoteIpAddress); await _userRepository.UpdateAsync(user, notification.UserId); await _unitOfWork.CommitAsync(); }
public void MatchesUserWithGivenId() { var spec = new UserSpecification(_userId); var result = GetTestUsersCollection() .AsQueryable() .FirstOrDefault(spec.Criteria); result.ShouldNotBeNull(); result.Id.ShouldBe(_userId); }
public async Task Handle(ExchangeRefreshTokenCommand notification, CancellationToken cancellationToken) { var userSpecification = new UserSpecification(notification.UserId); var user = await _userRepository.FindAsync(userSpecification); user.RemoveRefreshToken(notification.OldRefreshToken); user.AddRefreshToken(notification.NewRefreshToken, user.Id, ""); await _userRepository.UpdateAsync(user, user.Id); await _unitOfWork.CommitAsync(); }
public UsersSearchResponse SearchUser(ISession session, UsersSearchRequest request) { var response = request.CreateResponse <UsersSearchResponse>(); using (var uow = UnitOfWorkFactory.Create()) { var users = uow.UsersRepository.AllMatching(UserSpecification.NameLike(request.QueryString), 20); var userDtos = users.ProjectedAsCollection <UserDto>(); response.Result = userDtos.ToArray(); } return(response); }
public async Task <IActionResult> Get(string name = null) { // var queryOptions = QueryOptionsExtensions.GetFromRequest(Request); var specification = new UserSpecification(name); var result = await _queryBus.ExecuteAsync(new UserQuery(specification)); var count = await _queryBus.ExecuteAsync(new UserTotalQuery(specification)); return(Ok(new PageableCollection <UserQueryModel>() { Results = result, Total = count })); }
public BanResponse Ban(ISession session, BanRequest request) { var response = request.CreateResponse <BanResponse>(); User targetUser = null; using (var uow = UnitOfWorkFactory.Create()) { targetUser = uow.UsersRepository.FirstMatching(UserSpecification.Id(request.TargetUserId)); if (targetUser != null) { try { if (request.Ban) { targetUser.Ban(session.User); } else { targetUser.UnBan(session.User); } response.Result = BanResponseType.Success; uow.Commit(); } catch (ModeratorsRightsRequiredException) { response.Result = BanResponseType.Failed; } } } if (response.Result == BanResponseType.Success && targetUser != null) { //let's kick him\her from the server! _sessionManager.CloseSessionByUserId(targetUser.Id); //send a notification to everybody that we've banned him\her _sessionManager.SendToEachChatSessions( new BanNotification { Ban = request.Ban, ActorName = session.User.Name, Reason = request.Reason, TargetId = session.User.Id, TargetName = targetUser.Name }); } return(response); }
public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel data) { ViewData["Email"] = data.Email; if (!ModelState.IsValid) { return(PartialView(data)); } if (!_emailValidatorService.IsValidEmail(data.Email)) { ModelState.AddModelError("InvalidEmail", _localizer[AuthenticationErrorMessages.InvalidEmail]); return(PartialView(data)); } var userSpecification = new UserSpecification() { Email = data.Email }; AuthenticationUser = await _userRepository.ReadAsync(userSpecification); if (AuthenticationUser is null) { ModelState.AddModelError("UserDoesNotExist", _localizer[AuthenticationErrorMessages.UserDoesNotExist]); return(PartialView(data)); } string token = Convert.ToBase64String(Guid.NewGuid().ToByteArray()); var userDTO = new UserDTO(AuthenticationUser); var saveToken = await _userPasswordRepository.SavePasswordTokenAsync(userDTO, token); if (!saveToken) { ModelState.AddModelError("ReminderFailed", _localizer[AuthenticationErrorMessages.PasswordReminderFailed]); return(PartialView(data)); } var domain = Request.Host.Value; domain += (Request.PathBase.Value.HasValue()) ? Request.PathBase.Value : string.Empty; var emailSubject = _forgotPasswordEmail.Subject(); var emailBody = _forgotPasswordEmail.Body(AuthenticationUser, domain, emailSubject, token); await _emailSenderService.SendEmailAsync(data.Email, emailSubject, emailBody); data.SendReminderSuccess = true; return(PartialView(data)); }
public async Task <IActionResult> InviteAsync(int userID) { var userSpecification = new UserSpecification() { ID = userID }; var user = await _userRepository.ReadAsync(userSpecification); var userDTO = new UserDTO(user); var userInvitationEvent = new UserInvitation(userDTO); await _mediator.Publish(userInvitationEvent); return(Ok()); }
public async Task <Token> Handle(LogInUserCommand request, CancellationToken cancellationToken) { var passwordHash = _hashingService.GenerateHash(request.Password, _configuration.SaltString); var spec = UserSpecification.GetByCredentials(request.UserName, passwordHash); var user = await _data.Users.SingleOrDefaultAsync(spec); if (user == null) { throw new AuthenticationApplicationException(ErrorMessagesConstants.InvalidCredentials); } var token = await _tokenService.GenerateAsync(user); return(token); }
public async Task <User> Login(string username, string password) { var userSpec = new UserSpecification(username); User user = await _userRepository.FirstOrDefaultAsync(userSpec); if (user == null) { return(null); } if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt)) { return(null); } return(user); }
public bool LoginAccount(string userName, string pwd) { UserSpecification spec = new UserSpecification(new UserInfo { UserName = userName.ToLower(), UserPwd = pwd }); var users = _userInfoRepository.GetBySpec(spec); if (users != null && users.Any()) { return(true); } else { return(false); } }
public async Task Handle(UpdateProjectParticipantsCommand command, CancellationToken cancellationToken) { var specification = new UserSpecification(command.Participants); var users = await _useRepository.GetAllAsync(specification); var projectSpecification = new ProjectSpecification(command.Id); var project = await _projectRepository.GetSingleOrDefaultAsync(projectSpecification); var existingParticipant = project.Participants.Select(user => user).ToArray(); var newParticipants = users.Except(existingParticipant).ToArray(); var deletedParticipants = existingParticipant.Except(users).ToArray(); var participants = existingParticipant.Except(deletedParticipants).Concat(newParticipants).ToArray(); project.UpdateProjectParticipants(participants); await _unitOfWork.SaveChangesAsync(); }
/// <summary> /// Initializes a new instance of the <see cref="HomeQuery"/> class. /// </summary> /// <param name="status">The status.</param> /// <param name="sort">The sort.</param> /// <param name="order">The order.</param> /// <param name="page">The page.</param> public HomeQuery(string status, SortUser sort, SortOrder order, int? page) { IUserSpecification specification = null; if (!string.IsNullOrEmpty(status)) { specification = new UserStatusSpecification(status.AsEnum<UserStatus>()); } if (specification == null) { specification = new UserSpecification(); } specification.Page = page; specification.Limit = Setting.UserPageLimit.Value; specification.Sort = sort; specification.Order = order; this.Specification = specification; }