Пример #1
0
        public ApplicationResult GetOtherUserProfile(string search, int pageSize, int pageIndex, string id)
        {
            if (search == null)
            {
                search = "";
            }
            var data = _userRepository.GetUsersIncludeDeviceAndHobby(search, pageSize, pageIndex, id);

            var content = data.Select(x => new UserOtherViewModel()
            {
                Id       = x.Id,
                UserName = x.UserName,
                SexType  = x.SexType,
                Hobbies  = string.Join(',', x.Hobbies.Select(y => y.Name)),
                Country  = x.Country,
                Avatar   = x.Avatar,
                Status   = x.Status
            }).ToList();

            var total = _userRepository.CountGetUsersIncludeDeviceAndHobby(search, id);

            var results = new PagingModel <UserOtherViewModel>(content, pageSize, pageIndex, total);

            return(ApplicationResult.Ok(results));
        }
Пример #2
0
        public ApplicationResult InsertRoleForAccount(int accountId, string roleName)
        {
            var queryInsert = @"DECLARE @roleId INT = (SELECT Id FROM [dbo].[Roles] (NOLOCK) WHERE Name=@roleName)
                                IF(NOT EXISTS(
                                SELECT 1 FROM [dbo].[AccountRoles] (NOLOCK) AR WHERE AR.AccountId =@accountId AND RoleId=@roleId))
                                BEGIN
	                                INSERT INTO [dbo].[AccountRoles]
                                           ([AccountId]
                                           ,[RoleId])
                                     VALUES
                                           (@accountId,@roleId)
	                                SELECT 1
                                END
                                ELSE 
                                BEGIN 
	                                SELECT 0
                                END";
            var result      = Connection.Execute(queryInsert, new { accountId, roleName });

            if (result > 0)
            {
                return(ApplicationResult.Ok());
            }
            return(ApplicationResult.Fail("Không thể cấp quyền cho tài khoản này"));
        }
Пример #3
0
        public ApplicationResult <Account> Login(string username, string password)
        {
            var account = _accountRepository.Gets(new { Username = username })
                          .FirstOrDefault();

            if (account == null)
            {
                return(ApplicationResult.Fail <Account>(ApplicationErrorCode.ErrorIsExist, "Account"));
            }
            var isValidPassword = account.IsValidPassword(password);

            if (isValidPassword == false)
            {
                return(ApplicationResult.Fail <Account>(ApplicationErrorCode.ErrorIsNotValid, "Password"));
            }
            if (account.Status != AccountStatus.Active)
            {
                return(ApplicationResult.Fail <Account>("The account does not active yet"));
            }

            var role = _roleRepository.GetByName(ApplicationConstant.Role.User);

            account.Roles = new List <Role> {
                role
            };
            return(ApplicationResult.Ok(account));
        }
Пример #4
0
        public async Task <ApplicationResult <LoginResponseModel> > Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var user = await _userService.GetUserAsync(request.Email);

            if (user == null)
            {
                return(ApplicationResult <LoginResponseModel> .Fail(PowerChatError.Create(UserErrorCodes.UserNotFound,
                                                                                          $"User with email '{request.Email}' was not found.")));
            }

            var result = await _authService.LoginAsync(request.Email, request.Password);

            if (result.Succeeded)
            {
                var userLoggedInEvent = new UserLoggedInEvent {
                    UserId = user.Id
                };
                await _mediator.Publish(userLoggedInEvent, cancellationToken);

                var loginResponse = new LoginResponseModel
                {
                    UserId  = user.Id,
                    Token   = result.Value.Token,
                    Expires = result.Value.Expires
                };

                return(ApplicationResult <LoginResponseModel> .Ok(loginResponse));
            }

            return(ApplicationResult <LoginResponseModel> .Fail(result.Error));
        }
Пример #5
0
        public ApplicationResult <List <User> > GetAllUser()
        {
            var t = _userGenericRepository.Gets(x => true);
            var m = _messageGenericRepository.Gets(x => true);

            return(ApplicationResult.Ok(_userRepository.Gets(x => true)));
        }
Пример #6
0
        public async Task <ApplicationResult> EnqueueToDownloadAsync(string userId, int submissionId)
        {
            var(acountId, accountName) = await _accountBusiness.GetSpojAccountUsernameAsync(userId);

            await _submissionBusiness.InstantDownLoadSubmissionAsync(acountId, accountName, submissionId);

            return(ApplicationResult.Ok());
        }
Пример #7
0
        public static ApplicationResult <long> ToApplicationResult(this IdentityResult identityResult, User user)
        {
            if (identityResult.Succeeded)
            {
                return(ApplicationResult <long> .Ok(user.Id));
            }

            return(ApplicationResult <long> .Fail(identityResult.Errors.Select(e => PowerChatError.Create(e.Code, e.Description)).First()));
        }
Пример #8
0
        public ApplicationResult <long> GetResultUserId()
        {
            if (UserId == null || IsAuthenticated == false)
            {
                return(ApplicationResult <long> .Fail(PowerChatError.Create("Unauthorized", "Unauthorized")));
            }

            return(ApplicationResult <long> .Ok(UserId.Value));
        }
Пример #9
0
        public virtual ApplicationResult <T> GetById <T>(object id)
        {
            var entity = _repository.GetById(id);

            if (entity == null)
            {
                return(ApplicationResult.Fail <T>($"Cannot find {typeof(T)} with Id:{id} in the system"));
            }
            return(ApplicationResult.Ok(Mapper.Map <T>(entity)));
        }
Пример #10
0
        public ApplicationResult GetUserById(string id, string currentUserId)
        {
            var relate = _relationShipRepository.Gets(x => x.CurrentUserId == currentUserId && x.OtherUserId == id);
            var result = Mapper.Map <UserOtherViewModel>(_userRepository.GetById(id));

            result.IsFriend = relate.Any(x => x.IsFriend);
            result.IsBan    = relate.Any(x => x.IsBlock);
            result.IsAway   = relate.Any(x => x.Ignored);
            return(ApplicationResult.Ok(result));
        }
Пример #11
0
        public ApplicationResult Delete(object id)
        {
            var result = _repository.DeleteById(id);

            if (result <= 0)
            {
                return(ApplicationResult.Fail("Cannot delete the record in the database"));
            }
            return(ApplicationResult.Ok());
        }
Пример #12
0
        public ApplicationResult Update(TEntity value)
        {
            var result = _repository.Update(value);

            if (result <= 0)
            {
                return(ApplicationResult.Fail("Cannot update the record in the database"));
            }
            return(ApplicationResult.Ok());
        }
Пример #13
0
        public ApplicationResult UpdateUserProfile(UserEditProfile model, string userId)
        {
            var user = _userRepository.GetById(userId);

            if (user == null)
            {
                return(ApplicationResult.Fail("User does not found"));
            }
            Mapper.Map(model, user);
            _userRepository.Update(user);
            return(ApplicationResult.Ok(Mapper.Map <UserViewProfile>(user)));
        }
Пример #14
0
        public ApplicationResult AddNewDevice(DeviceViewModel model, string userId)
        {
            var user = _userRepository.GetById(userId);

            if (user == null)
            {
                return(ApplicationResult.Fail("User does not exist"));
            }
            model.UserId = userId;
            var device = _deviceRepository.Insert(Mapper.Map <Device>(model));

            return(ApplicationResult.Ok(Mapper.Map <DeviceViewModel>(device)));
        }
Пример #15
0
        public ApplicationResult ConfirmEmail(string token)
        {
            var account = _accountRepository.Gets(new { TokenConfrimEmail = token }).FirstOrDefault();

            if (account == null)
            {
                return(ApplicationResult.Fail(ApplicationErrorCode.ErrorIsNotValid, "Wrong token"));
            }
            account.Status = AccountStatus.Active;
            account.ConfirmEmail();
            _accountRepository.Update(account);
            return(ApplicationResult.Ok());
        }
Пример #16
0
        public ApplicationResult GetAllMessageWithUser(string userId, string withUser)
        {
            var user = _userRepository.GetById(userId);

            if (user == null)
            {
                return(ApplicationResult.Fail("User does not found"));
            }
            var results = _messageRepository.Gets(x => (x.ToUser == user.UserName && x.FromUser == withUser) ||
                                                  (x.FromUser == user.UserName && x.ToUser == withUser));

            return(ApplicationResult.Ok(results.Select(Mapper.Map <MessageViewModel>)));
        }
Пример #17
0
        public ApplicationResult UpdateDevice(DeviceEditModel model)
        {
            var device = _deviceRepository.GetById(model.Id);

            if (device == null)
            {
                return(ApplicationResult.Fail("Device not found"));
            }

            Mapper.Map(model, device);

            _deviceRepository.Update(device);
            return(ApplicationResult.Ok());
        }
Пример #18
0
        public async Task <ApplicationResult <JwtDto> > LoginAsync(string email, string password)
        {
            var user = await _userManager.FindByEmailAsync(email);

            var loginResult = await _signInManager.PasswordSignInAsync(email, password, false, false);

            if (loginResult.Succeeded)
            {
                var token = _jwtGenerator.Generate(user.Id, email);
                return(ApplicationResult <JwtDto> .Ok(token));
            }

            return(TranslateSignInResult(loginResult, email));
        }
Пример #19
0
        public ApplicationResult <UserViewModel> GetUserByRefreshToken(string refreshToken)
        {
            var user = _userRepository.Get(x => x.RefreshToken == refreshToken);

            if (user == null || user.RefreshTokenExpireDate < DateTimeOffset.Now)
            {
                return(ApplicationResult.Fail <UserViewModel>("The refresh token is not valid, or expired"));
            }

            if (user.IsDeleted)
            {
                return(ApplicationResult.Fail <UserViewModel>("The user is deleted"));
            }

            return(ApplicationResult.Ok(Mapper.Map <UserViewModel>(user)));
        }
Пример #20
0
        public ApplicationResult GetBlackList(string currentUserId)
        {
            var data = _relationShipRepository.GetBlackList(currentUserId);

            var result = data.Select(x => new UserOtherViewModel()
            {
                Id       = x.OtherUserId,
                UserName = x.OtherUser.UserName,
                SexType  = x.OtherUser.SexType,
                Country  = x.OtherUser.Country,
                Avatar   = x.OtherUser.Avatar,
                Status   = x.OtherUser.Status
            });

            return(ApplicationResult.Ok(result));
        }
Пример #21
0
        public async Task <ApplicationResult <TestCaseResponseModel> > SearchSubmssionAsync(string userId, int submissionId)
        {
            var response = await _testCaseBusiness.SearchFirstFailForFailerAsync(submissionId, userId);

            if (response == null)
            {
                await EnqueueToDownloadAsync(userId, submissionId);
            }
            else
            {
                return(ApplicationResult <TestCaseResponseModel> .Ok(response));
            }

            response = await _testCaseBusiness.SearchFirstFailForFailerAsync(submissionId, userId);

            return(ApplicationResult <TestCaseResponseModel> .Ok(response));
        }
        public async Task <ApplicationResult <long> > Handle(SendChannelMessageCommand request, CancellationToken cancellationToken)
        {
            var currentUserResult = _currentUserService.GetResultUserId();

            if (!currentUserResult.Succeeded)
            {
                return(ApplicationResult <long> .Fail(currentUserResult.Error));
            }

            var channel = await _dbContext.Channels.FindAsync(new object[] { request.ChannelId }, cancellationToken);

            var sender = await _dbContext.Users.FindAsync(new object[] { currentUserResult.Value }, cancellationToken);

            var interlocutorUserId = await _dbContext.Interlocutors
                                     .Where(i => i.ChannelId == channel.Id)
                                     .Where(i => i.UserId != currentUserResult.Value)
                                     .Select(i => i.UserId)
                                     .SingleAsync(cancellationToken);

            var message = new Message
            {
                Channel = channel,
                Sender  = sender,
                Content = request.Content
            };

            await _dbContext.Messages.AddAsync(message, cancellationToken);

            await _dbContext.SaveChangesAsync(cancellationToken);

            await _connectedUsersService.SendAsync(interlocutorUserId, "ReceiveMessage", new
            {
                message = new MessageModel
                {
                    Id       = message.Id,
                    AuthorId = sender.Id,
                    Content  = message.Content,
                    Own      = false,
                    Seen     = message.Seen,
                    SentDate = message.CreatedDate
                },
                channelId = channel.Id
            });

            return(ApplicationResult <long> .Ok(message.Id));
        }
Пример #23
0
        public ApplicationResult <UserViewModel> SignUp(UserViewModel model)
        {
            model.UserName = model.UserName.ToLower();
            model.Email    = model.Email.ToLower();
            var users     = _userRepository.Gets(x => true);
            var existUser = users.FirstOrDefault(x => model.UserName == x.UserName);

            if (existUser != null)
            {
                return(ApplicationResult.Fail <UserViewModel>("The user already exists"));
            }
            var user = Mapper.Map <User>(model);

            SetPassword(user, model.PasswordHash);
            _userRepository.Insert(user);

            return(ApplicationResult.Ok(Mapper.Map <UserViewModel>(user)));
        }
Пример #24
0
        public ApplicationResult <UserViewModel> GetUserByCredential(string username, string password)
        {
            username = username.ToLower();
            var user = _userRepository.Get(x => x.UserName == username);

            if (user == null)
            {
                return(ApplicationResult.Fail <UserViewModel>("The username does not exist"));
            }
            var isValidPassword = ValidatePassword(user, password);

            if (isValidPassword == false)
            {
                return(ApplicationResult.Fail <UserViewModel>("The password is not valid"));
            }

            if (user.IsDeleted)
            {
                return(ApplicationResult.Fail <UserViewModel>("The user is deleted"));
            }

            return(ApplicationResult.Ok(Mapper.Map <UserViewModel>(user)));
        }
Пример #25
0
        public ApplicationResult <Account> Create(RegisterBindingModel model)
        {
            var account = _accountRepository.Gets(new { Username = model.Email, IsDeleted = false }).FirstOrDefault();

            if (account != null)
            {
                return(ApplicationResult.Fail <Account>("The account already exists"));
            }
            account = new Account {
                UserName = model.Email, Email = model.Email, DisplayName = model.DisplayName
            };
            account.SetPassword(model.Password);
            account.GenerateActiveToken();

            var accountResult    = _accountRepository.Insert(account);
            var insertRoleResult = _roleRepository.InsertRoleForAccount(accountResult.Id, ApplicationConstant.Role.User);

            if (insertRoleResult.IsFailure)
            {
                return(ApplicationResult.Fail <Account>(insertRoleResult.Errors));
            }
            return(ApplicationResult.Ok(account));
        }
        public async Task <ApplicationResult <long> > Handle(CreateUserChannelCommand request, CancellationToken cancellationToken)
        {
            var currentUserResult = _currentUserService.GetResultUserId();

            if (!currentUserResult.Succeeded)
            {
                return(ApplicationResult <long> .Fail(currentUserResult.Error));
            }

            var user = await _dbContext.Users.FindAsync(new object[] { request.UserId }, cancellationToken);

            var currentUser = await _dbContext.Users.FindAsync(new object[] { currentUserResult.Value }, cancellationToken);

            var channel          = new Channel();
            var userInterlocutor = new Interlocutor
            {
                Channel = channel,
                User    = user
            };
            var currentUserInterlocutor = new Interlocutor
            {
                Channel = channel,
                User    = currentUser
            };

            await _dbContext.Channels.AddAsync(channel, cancellationToken);

            await _dbContext.Interlocutors.AddAsync(userInterlocutor, cancellationToken);

            await _dbContext.Interlocutors.AddAsync(currentUserInterlocutor, cancellationToken);

            await _dbContext.SaveChangesAsync(cancellationToken);

            await _mediator.Publish(new ChannelCreatedEvent { ChannelId = channel.Id }, cancellationToken);

            return(ApplicationResult <long> .Ok(channel.Id));
        }
Пример #27
0
        public ApplicationResult ActionUser(RelationAction action, string userId, string currentUserId)
        {
            var message = _userRepository.ActionUser(action, userId, currentUserId);

            return(string.IsNullOrEmpty(message) ? ApplicationResult.Ok() : ApplicationResult.Fail(message));
        }
Пример #28
0
        public ApplicationResult GetUserProfile(string userId)
        {
            var user = _userRepository.GetById(userId);

            return(ApplicationResult.Ok(Mapper.Map <UserViewProfile>(user)));
        }
Пример #29
0
        public ApplicationResult UpdateSpojAccount(AdminSettingSpojAccountUpdateModel model)
        {
            _adminSettingBusiness.UpdateSpojAccount(model);

            return(ApplicationResult.Ok());
        }
Пример #30
0
        public async Task <ApplicationResult <AdminSettingSpojAccountResponseModel> > GetSpojAccountAsync()
        {
            var response = await _adminSettingBusiness.GetSpojAccountAsync();

            return(ApplicationResult <AdminSettingSpojAccountResponseModel> .Ok(response));
        }