Exemplo n.º 1
0
        public void UpdateUserTest()
        {
            // Arrange
            var repoMock = new Mock <IUserRepo>();
            var userDTO  = new UserDto
            {
                id       = 1,
                name     = "test1",
                surname  = "test1",
                email    = "test1",
                verified = false,
                admin    = false
            };
            var inputDTO = new UserInputDto
            {
                name     = "test1",
                surname  = "test1",
                email    = "test1",
                verified = false,
                admin    = false
            };

            repoMock.Setup(p => p.UpdateUserById(1, inputDTO)).Returns(userDTO);
            var service = new AdminManageUserServices(repoMock.Object);
            var ctl     = new AdminManageUserController(service);

            // Act
            var result = ctl.updateUser(1, inputDTO).Result as OkObjectResult;

            // Assert
            result.Value.Should().BeEquivalentTo(userDTO, options => options.ComparingByMembers <UserDto>());
        }
Exemplo n.º 2
0
        public async Task <UserLoginOutputDto> Login(UserInputDto inputDto)
        {
            if (userRepository.GetQuery().Select(x => x.Email != inputDto.Email).FirstOrDefault())
            {
                throw new InvalidValuesException("Wrong Email");
            }


            var getUser = userRepository.GetQuery().
                          Where(x => x.Email == inputDto.Email && x.Password == inputDto.Password).FirstOrDefault();

            var token           = Guid.NewGuid().ToString();
            var expireLoginDate = DateTime.UtcNow.AddDays(1);

            UserLoginInputDto tempUserLogin = new UserLoginInputDto();

            tempUserLogin.UserId          = getUser.Id;
            tempUserLogin.Token           = token;
            tempUserLogin.ExpireLoginDate = expireLoginDate;

            var mappedUserLogin = mapper.Map <UserLogin>(tempUserLogin);

            userLoginRepository.Insert(mappedUserLogin);

            await userLoginRepository.Save();

            var mappedUserLoginOutput = mapper.Map <UserLoginOutputDto>(mappedUserLogin);

            return(mappedUserLoginOutput);
        }
Exemplo n.º 3
0
        public void updateUser_Test()
        {
            // Arrange
            var userDTO = new UserDto
            {
                id       = 1,
                name     = "test1",
                surname  = "test1",
                email    = "test1",
                verified = false,
                admin    = false
            };
            var user = new UserInputDto
            {
                name     = "test1",
                surname  = "test1",
                email    = "test1",
                verified = false,
                admin    = false
            };

            _userRepoMock.Setup(p => p.UpdateUserById(1, user)).Returns(userDTO);
            _userRepoMock.Setup(p => p.GetUserById(1)).Returns(userDTO);



            // Act
            var result = _sut.ServiceUpdateUserById(1, user);

            // Assert
            result.Should().BeEquivalentTo(userDTO, options => options.ComparingByMembers <UserDto>());
        }
Exemplo n.º 4
0
        //[ServiceFilter(typeof(ValidationFilterAttribute))]
        public async Task <AjaxResult> CreateAsync([FromBody] UserInputDto dto)
        {
            //var validator = _serviceProvider.GetService<IModelValidator<UserInputDto>>();

            //var failures = validator.Validate(new UserInputDto());
            return((await _userService.CreateAsync(dto)).ToAjaxResult());
        }
Exemplo n.º 5
0
        /// <summary>
        /// Создает документ (патент или сертификат) и прикрепляет его к охранному документу.
        /// </summary>
        /// <param name="id">Идентификатор охранного документа.</param>
        /// <param name="userId">Идентификатор исполнителя.</param>
        /// <returns>Асинхронная операция.</returns>
        private async Task CreatePatentOrCertificate(int id, int?userId)
        {
            var protectionDoc = await Executor
                                .GetQuery <GetProtectionDocByIdQuery>()
                                .Process(q => q.ExecuteAsync(id));

            if (protectionDoc is null)
            {
                throw new DataNotFoundException(nameof(ProtectionDoc), DataNotFoundException.OperationType.Read, 0);
            }

            string patentCode = GetPatentCode(protectionDoc);

            var userInputDto = new UserInputDto
            {
                Code      = patentCode,
                Fields    = new List <KeyValuePair <string, string> >(),
                OwnerId   = id,
                OwnerType = Owner.Type.ProtectionDoc
            };

            var documentId = await CreateDocument(id, Owner.Type.ProtectionDoc, patentCode, DocumentType.Outgoing, userInputDto, userId);

            var documentGenerator = _templateGeneratorFactory.Create(patentCode);

            if (documentGenerator != null)
            {
                protectionDoc.PageCount = GenerateDocumentAndGetPagesCount(documentGenerator, documentId, userInputDto);
            }

            await Executor.GetCommand <UpdateProtectionDocCommand>().Process(c => c.ExecuteAsync(id, protectionDoc));
        }
Exemplo n.º 6
0
        public void createUser_Test()
        {
            // Arrange
            var userinthelist = new UserDto
            {
                id       = 1,
                name     = "test1",
                surname  = "test1",
                email    = "test1",
                verified = false,
                admin    = false
            };
            var returnedList = new List <UserDto> {
                userinthelist
            };
            var user = new UserInputDto
            {
                name     = "test1",
                surname  = "test1",
                email    = "test1",
                verified = false,
                admin    = false
            };

            _userRepoMock.Setup(p => p.CreateUser(user)).Returns(returnedList);
            _userRepoMock.Setup(p => p.GetUserById(1)).Returns(userinthelist);
            _userRepoMock.Setup(p => p.GetUsers()).Returns(returnedList);


            // Act
            var result = _sut.ServiceCreateUser(user);

            // Assert
            result.Should().BeEquivalentTo(returnedList, options => options.ComparingByMembers <UserDto>());
        }
Exemplo n.º 7
0
        public async Task Insert(UserInputDto inputDto)
        {
            var RegisterUser = mapper.Map <User>(inputDto);

            userRepository.Insert(RegisterUser);
            await userRepository.Save();
        }
Exemplo n.º 8
0
    public IActionResult Moves([FromRoute] Guid gameId, [FromBody] UserInputDto userInputDto)
    {
        if (userInputDto == null || gameId == Guid.Empty)
        {
            return(BadRequest());
        }

        var userMove = Mapper.MapFromUserInputDtoToUserMove(userInputDto);

        var game = gameRepository.GetGame(gameId);

        if (userMove is null)
        {
            return(CreatedAtRoute(
                       nameof(Moves),
                       new { gameId },
                       Mapper.MapFromGameToGameDto(game)));
        }

        game = game2048Handler.MakeMove(game, userMove);
        gameRepository.Update(game);

        var gameDto = Mapper.MapFromGameToGameDto(game);

        return(CreatedAtRoute(
                   nameof(Moves),
                   new { gameId },
                   gameDto));
    }
Exemplo n.º 9
0
        public async Task <ActionResult <UserViewDto> > CreateUser([FromBody] UserInputDto userInputDto)
        {
            if (userInputDto == null)
            {
                return(BadRequest());
            }

            //model state validation is not required due to the [ApiController] attribute automatically returning UnprocessableEntity (see startup.cs)
            //when model binding fails

            //fetch the user id from the JWT via HttpContext. Then get the user from the repository. This is to ensure that an authorized user
            //is calling the API with a valid user id
            var user = await _userRepository.GetUserAsync(User.GetUserId());

            if (user != null)
            {
                return(new ConflictObjectResult(new { Error = "The user already exists in the system. You cannot add the same user again." }));
            }

            var userToAdd = _mapper.Map <User>(userInputDto); //map UserInputDto to User

            userToAdd.SocialId = User.GetUserId();            //map social Id as it will be null otherwise
            _userRepository.AddUser(userToAdd);

            if (!await _userRepository.SaveChangesAsync())
            {
                throw new Exception($"Error saving User {userToAdd.Id} to the database");
            }

            var userToReturn = _mapper.Map <UserViewDto>(userToAdd);

            return(CreatedAtRoute("GetUser", new { id = userToAdd.Id }, userToReturn));
        }
Exemplo n.º 10
0
        /// <summary>
        /// 获取所有用户列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public IQueryable <UserDto> GetAll(UserInputDto dto)
        {
            var query = _userRepository.GetAll();

            if (string.IsNullOrEmpty(dto?.SearchInputStr))
            {
                query = query.Where(u => u.Email == dto.SearchInputStr || u.PhoneNum == dto.SearchInputStr || u.UserName == dto.SearchInputStr);
            }
            query = query.Include(r => r.UserRoles);
            var model = query.Select(r =>
                                     new UserDto
            {
                Address                = r.Address,
                CreationTime           = r.CreationTime,
                CreatorUserId          = r.CreatorUserId,
                Email                  = r.Email,
                Id                     = r.Id,
                IsDelete               = r.IsDelete,
                LastLoginErrorDateTime = r.LastLoginErrorDateTime,
                LoginErrorTimes        = r.LoginErrorTimes,
                Password               = r.Password,
                PasswordSalt           = r.PasswordSalt,
                PhoneNum               = r.PhoneNum,
                UserName               = r.UserName,
                RoleIds                = r.UserRoles.Select(t => t.RoleId).ToList(),
                RoleNames              = r.UserRoles.Select(t => t.Role.RoleName).ToList()
            });

            return(model);//AutoMapperExtension.MapTo<User, UserDto>(query).AsQueryable();
        }
Exemplo n.º 11
0
        public string AddUser(UserInputDto userInputDto)
        {
            userInputDto.RegDate    = DateTime.Now;
            userInputDto.CreateTime = DateTime.Now;
            userInputDto.LoginNum   = 0;
            string ip           = HttpContext.Connection.RemoteIpAddress.ToString();
            string validateCode = MemoryCacheHelper.GetCache(ip).ToString();
            //if (!string.IsNullOrEmpty(validateCode) && validateCode.ToLower() == userInputDto.validateCode)
            //{
            Users user;

            user = _accountService.GetUserByQQ(userInputDto.QQ);
            if (user != null)
            {
                HttpContext.Response.StatusCode = 214;
                return("hasQQ");
            }
            int row = _accountService.CreateAndUpdateUsers(userInputDto);

            if (row >= 1)
            {
                return("success");
            }
            else
            {
                HttpContext.Response.StatusCode = 214;
                return("UnknowErr");
            }
            //}
            //else
            //{
            //    HttpContext.Response.StatusCode = 214;
            //    return "ValidateErr";
            //}
        }
Exemplo n.º 12
0
        /// <summary>
        /// Authenticates the specified input.
        /// </summary>
        /// <param name="input">UserInputDto contains user information.</param>
        /// <returns>UserOutputDto</returns>
        public UserOutputDto Authenticate(UserInputDto input)
        {
            var user = _userRepository.GetUserByNameAndPassword(input.User.Username, input.User.Password);

            if (user != null)
            {
                if (user.Password.Equals(input.User.Password))
                {
                    user.LastLoginDate = DateTime.Now;
                    var result = _userRepository.UpdateEntity(user);

                    if (!result)
                    {
                        return(null);
                    }


                    var role = _roleRepository.GetOne(user.RoleId);

                    return(new UserOutputDto
                    {
                        UserId = user.Id,
                        Name = user.Name,
                        Gender = Enum.GetName(typeof(Gender), user.Gender),
                        Occupation = user.Occupation,
                        LastLoginDate = user.CreatedDateTime,
                        Role = role.Name
                    });
                }
            }

            return(null);
        }
Exemplo n.º 13
0
        public UserOutputDto Register(UserInputDto input)
        {
            // create user record
            var record = new EUser
            {
                Gender     = Gender.Male,
                Occupation = input.User.Occupation,
                UserName   = input.User.Username,
                Password   = input.User.Password,
                IsActive   = true,
                Name       = input.User.Name,

                // set role to USER role
                ERole = _roleRepository.GetOne(2)
            };

            // create record
            var user = _userRepository.CreateEntity(record);

            if (user != null)
            {
                return(new UserOutputDto
                {
                    UserId = user.Id,
                    Name = user.Name,
                    Gender = Enum.GetName(typeof(Gender), user.Gender),
                    Occupation = user.Occupation,
                    LastLoginDate = user.CreatedDateTime,
                    Role = user.ERole.Name
                });
            }

            return(null);
        }
        public ActionResult Register(UserRegistrationModel model)
        {
            // validation of the model
            bool isModelValid = Validate(model);


            if (isModelValid)
            {
                // create user input dto
                var uid = new UserInputDto
                {
                    User = new UserDto()
                    {
                        Name       = model.Name,
                        Username   = model.Username,
                        Occupation = model.Occupation,
                        Password   = model.Password.HashMd5()
                    }
                };

                // send registeration request
                var response = Services.AuthService.Register(uid);

                if (response != null)
                {
                    return(RedirectToAction("Index"));
                }
            }

            return(RedirectToAction("Register"));
        }
Exemplo n.º 15
0
        public async Task <ActionResult> Index()
        {
            if (IdentityContract.Users.Count() <= 2)
            {
                UserInputDto dto = new UserInputDto()
                {
                    RecommendId    = 0,
                    UserName       = "******",
                    NickName       = "管理员",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                    PhoneNumber    = "13561962764",
                    Password       = "******"
                };
                OperationResult result = await IdentityContract.CreateUsers(dto);

                if (!result.Successed)
                {
                    return(Content("创建初始用户失败:" + result.Message));
                }
                UserRoleMapInputDto mapDto = new UserRoleMapInputDto()
                {
                    UserId = 1, RoleId = 1
                };
                result = await IdentityContract.CreateUserRoleMaps(mapDto);

                if (!result.Successed)
                {
                    return(Content("给初始用户赋角色失败:" + result.Message));
                }
            }

            return(View());
        }
Exemplo n.º 16
0
 public OperationResult UpdatedUser(UserInputDto inputDto)
 {
     if (!UserLoginRepository.CheckExists(m => m.Id == inputDto.Id))
     {
         throw new Exception("id:用户信息不存在");
     }
     else
     {
         var result      = UserLoginRepository.TrackEntities.First(m => m.Id == inputDto.Id);
         var result_user = result.UserMany.First();
         result_user.Email             = inputDto.Email;
         result_user.PhoneNumber       = inputDto.PhoneNumber;
         result_user.WeChat            = inputDto.WeChat;
         result_user.Remark            = inputDto.Remark;
         result_user.Theme             = inputDto.Theme;
         result_user.RealName          = inputDto.RealName;
         result_user.NickName          = inputDto.NickName;
         result_user.Sex               = inputDto.Sex;
         result_user.IsAlarm           = inputDto.IsAlarm;
         result_user.IsSysReceive      = inputDto.IsSysReceive;
         result_user.Language          = inputDto.Language;
         result_user.LastUpdatedTime   = DateTime.Now;
         result_user.LastUpdatorUserId = result.UserName;
         int n = UserLoginRepository.Update(result);
         if (n > 0)
         {
             return(new OperationResult(OperationResultType.Success, "更新用户基本信成功!"));
         }
         else
         {
             throw new Exception("id:更新用户数据失败");
         }
     }
 }
Exemplo n.º 17
0
        /// <summary>
        /// 微信注册普通会员用户
        /// </summary>
        /// <param name="userInPut">第三方类型</param>
        /// <returns></returns>
        public bool CreateUserByWxOpenId(UserInputDto userInPut)
        {
            User        user            = userInPut.MapTo <User>();
            UserLogOn   userLogOnEntity = new UserLogOn();
            UserOpenIds userOpenIds     = new UserOpenIds();

            user.Id              = user.CreatorUserId = GuidUtils.CreateNo();
            user.Account         = "Wx" + GuidUtils.CreateNo();
            user.CreatorTime     = userLogOnEntity.FirstVisitTime = DateTime.Now;
            user.IsAdministrator = false;
            user.EnabledMark     = true;
            user.Description     = "第三方注册";
            user.IsMember        = true;
            user.UnionId         = userInPut.UnionId;
            user.ReferralUserId  = userInPut.ReferralUserId;
            if (userInPut.NickName == "游客")
            {
                user.RoleId = _roleService.GetRole("guest").Id;
            }
            else
            {
                user.RoleId = _roleService.GetRole("usermember").Id;
            }

            userLogOnEntity.UserId = user.Id;

            userLogOnEntity.UserPassword = GuidUtils.NewGuidFormatN() + new Random().Next(100000, 999999).ToString();
            userLogOnEntity.Language     = userInPut.language;

            userOpenIds.OpenId     = userInPut.OpenId;
            userOpenIds.OpenIdType = userInPut.OpenIdType;
            userOpenIds.UserId     = user.Id;
            return(_userRepository.Insert(user, userLogOnEntity, userOpenIds));
        }
Exemplo n.º 18
0
        public IActionResult Moves(Guid gameId, [FromBody] UserInputDto userInput)
        {
            var game           = gamesRepo.GetGameById(gameId);
            var playerPosition = GetCellPlayer(game);
            var deltaMove      = new VectorDto(0, 0);

            if (game.MonitorKeyboard)
            {
                deltaMove = GetDeltaMove(userInput.KeyPressed);
            }
            else if (game.MonitorMouseClicks && userInput.ClickedPos != null)
            {
                foreach (var neighbor in GetNeighborsPoints(playerPosition.Pos))
                {
                    if (EqualsVectorsDto(neighbor, userInput.ClickedPos))
                    {
                        deltaMove = new VectorDto(userInput.ClickedPos.X - playerPosition.Pos.X, userInput.ClickedPos.Y - playerPosition.Pos.Y);
                        break;
                    }
                }
            }

            var newGame = MovePlayer(game, playerPosition.Pos, deltaMove);

            newGame.Score += game.Score;

            gamesRepo.AddGame(newGame);

            var gameDto = mapper.Map <GameDto>(newGame);

            return(Ok(gameDto));
        }
Exemplo n.º 19
0
        public bool Execute(int requestId)
        {
            var rules   = Executor.GetQuery <GetNotificationAutoGenerationRulesQuery>().Process(q => q.Execute());
            var request = Executor.GetQuery <GetRequestByIdQuery>().Process(q => q.Execute(requestId));

            var documentCodes = rules.Where(r => r.StageId == request.CurrentWorkflow.CurrentStageId).Select(r => r.NotificationType.Code);

            foreach (var documentCode in documentCodes)
            {
                if (!string.IsNullOrEmpty(documentCode))
                {
                    var userInputDto = new UserInputDto
                    {
                        Code      = documentCode,
                        Fields    = new List <KeyValuePair <string, string> >(),
                        OwnerId   = requestId,
                        OwnerType = Owner.Type.Request
                    };
                    Executor.GetHandler <CreateDocumentHandler>().Process(h =>
                                                                          h.Execute(requestId, Owner.Type.Request, documentCode, DocumentType.Outgoing, userInputDto));
                }
            }

            return(false);
        }
Exemplo n.º 20
0
        private static User InitUserNameAndPassword(UserInputDto authDto)
        {
            var user = Mapper.Map <User>(authDto);

            user.UserName = authDto.Email;
            user.EncodePassword("Sioux@Asia");
            return(user);
        }
Exemplo n.º 21
0
        public BaseResponse <UserOutputDto> Update(Guid userId, UserInputDto userInput)
        {
            var newUser = Mapper.Map <User>(userInput);
            var oldUser = First(u => u.Id == userId);

            oldUser = UpdateUserInformationIfChanged(oldUser, newUser);
            return(new SuccessResponse <UserOutputDto>(Mapper.Map <UserOutputDto>(oldUser)));
        }
Exemplo n.º 22
0
        /// <summary>
        /// 用户验证
        /// </summary>
        /// <param name="entity">用户对象</param>
        public static string ValidateUserInputDto(UserInputDto entity)
        {
            //基础验证
            StringBuilder sb = BasicValidate <UserInputDto>(entity);

            //额外验证
            return(sb.ToString());
        }
Exemplo n.º 23
0
 public async Task <AjaxResult> AddOrUpdateAsync([FromBody] UserInputDto dto)
 {
     if (dto.Id == Guid.Empty)
     {
         return((await _userService.CreateAsync(dto)).ToAjaxResult());
     }
     return((await _userService.UpdateAsync(dto)).ToAjaxResult());
 }
Exemplo n.º 24
0
        private void CreatePatentOrCertificate(int protectionDocid)
        {
            var protectionDoc = Executor.GetQuery <GetProtectionDocByIdQuery>().Process(q => q.Execute(protectionDocid));

            if (protectionDoc == null)
            {
                throw new DataNotFoundException(nameof(ProtectionDoc), DataNotFoundException.OperationType.Read, 0);
            }
            string patentCode = null;

            switch (protectionDoc?.Type?.Code)
            {
            case DicProtectionDocTypeCodes.ProtectionDocTypeTrademarkCode:
                patentCode = DicDocumentTypeCodes.TrademarkCertificate;
                break;

            case DicProtectionDocTypeCodes.ProtectionDocTypeNameOfOriginCode:
                patentCode = DicDocumentTypeCodes.NmptCertificate;
                break;

            case DicProtectionDocTypeCodes.ProtectionDocTypeInventionCode:
                patentCode = DicDocumentTypeCodes.InventionPatent;
                break;

            case DicProtectionDocTypeCodes.ProtectionDocTypeSelectionAchieveCode:
                switch (protectionDoc?.SelectionAchieveType?.Code)
                {
                case DicSelectionAchieveTypeCodes.AnimalHusbandry:
                    patentCode = DicDocumentTypeCodes.SelectiveAchievementsAnimalHusbandryPatent;
                    break;

                case DicSelectionAchieveTypeCodes.Agricultural:
                case DicSelectionAchieveTypeCodes.VarietiesPlant:
                    patentCode = DicDocumentTypeCodes.SelectiveAchievementsAgriculturalPatent;
                    break;
                }
                break;

            case DicProtectionDocTypeCodes.ProtectionDocTypeUsefulModelCode:
                patentCode = DicDocumentTypeCodes.UsefulModelPatent;
                break;

            case DicProtectionDocTypeCodes.ProtectionDocTypeIndustrialSampleCode:
                patentCode = DicDocumentTypeCodes.IndustrialDesignsPatent;
                break;
            }
            var userInputDto = new UserInputDto
            {
                Code      = patentCode,
                Fields    = new List <KeyValuePair <string, string> >(),
                OwnerId   = protectionDocid,
                OwnerType = Owner.Type.ProtectionDoc
            };

            Executor.GetHandler <CreateDocumentHandler>().Process <Document>(h =>
                                                                             h.Execute(protectionDocid, Owner.Type.ProtectionDoc, patentCode, DocumentType.Outgoing, userInputDto));
        }
Exemplo n.º 25
0
        public UserInputDto GetUserInputValues(string filePath, char seperator)
        {
            var userInputDto = new UserInputDto();

            userInputDto.InputFilePath   = GetInputFilePath(filePath);
            userInputDto.OutputDirectory = _fileService.GetOutputDirectory(userInputDto.InputFilePath);
            userInputDto.RowSeparator    = GetRowSeperator(seperator);
            return(userInputDto);
        }
Exemplo n.º 26
0
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task <StatusResult> AddAsync(UserInputDto input)
        {
            var entity = input.Adapt <User>();

            entity.Id = Snowflake.GenId();
            var result = await _userRepository.InsertAsync(entity);

            return(new StatusResult(result == null, "添加失败"));
        }
Exemplo n.º 27
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            model.CheckNotNull(nameof(model));

            if (Session["Reg_EmailCode"] == null || Session["Reg_EmailCode"].ToString() != model.EmailCode)
            {
                return(Json(new AjaxResult("验证码错误", AjaxResultType.Error)));
            }

            UserInputDto dto = model.MapTo <UserInputDto>();

            dto.NickName       = dto.UserName;
            dto.RecommendId    = dto.RecommendId == 0 ? 1 : dto.RecommendId;
            dto.EmailConfirmed = true; //邮箱通过验证

            OperationResult result = await IdentityContract.CreateUsers(dto);

            if (result.ResultType == OperationResultType.Success)
            {
                //初始化用户角色
                User newuser = IdentityContract.Users.SingleOrDefault(u => u.UserName == dto.UserName);
                if (newuser != null)
                {
                    UserRoleMapInputDto mapDto = new UserRoleMapInputDto()
                    {
                        UserId = newuser.Id, RoleId = 2
                    };
                    result = await IdentityContract.CreateUserRoleMaps(mapDto);

                    if (!result.Successed)
                    {
                        return(Json(new AjaxResult(result.Message, AjaxResultType.Error)));
                    }
                }
                #region 用户登录
                LoginInfo loginInfo = new LoginInfo
                {
                    UserName = dto.UserName,
                    Password = dto.Password,
                    Remember = false
                };
                OperationResult <User> loginresult = await IdentityContract.Login(loginInfo, true);

                if (loginresult.ResultType == OperationResultType.Success)
                {
                    User user = loginresult.Data;
                    AuthenticationManager.SignOut();
                    await SignInManager.SignInAsync(user, loginInfo.Remember, true);
                }
                #endregion
                return(Json(new AjaxResult("登录成功", AjaxResultType.Success)));
            }
            else
            {
                return(Json(new AjaxResult(result.Message, AjaxResultType.Error)));
            }
        }
Exemplo n.º 28
0
        public BaseResponse <string> Register(UserInputDto authDto)
        {
            var user = InitUserNameAndPassword(authDto);

            CheckIfAccountExisted(user.UserName);
            CreateUser(user);
            SetRoleForUser(user.Id, DefaultRole.User);
            return(new BaseResponse <string>(HttpStatusCode.OK, data: "Registered successfully"));
        }
        /// <summary>
        /// Выполнение обработчика.
        /// </summary>
        /// <param name="ownerId">Идентификатор родительской сущности.</param>
        /// <param name="ownerType">Тип родительской сущности.</param>
        /// <param name="documentTypeCode">Код типа документа.</param>
        /// <param name="type">Тип документа.</param>
        /// <param name="userInput">Пользовательский ввод.</param>
        /// <param name="executorId">Идентификатор исполнителя.</param>
        /// <returns>Идентификатор созданного документа.</returns>
        public async Task <int> ExecuteAsync(
            int ownerId,
            Owner.Type ownerType,
            string documentTypeCode,
            DocumentType type,
            UserInputDto userInput,
            int executorId)
        {
            DicDocumentType documentType = GetDocumentTypeWithValidation(documentTypeCode);

            int?addresseeId = await GetAddresseeId(ownerId, ownerType);

            Document document = new Document
            {
                TypeId       = documentType.Id,
                AddresseeId  = addresseeId,
                DocumentType = type,
                DateCreate   = DateTimeOffset.Now
            };

            int documentId = await Executor
                             .GetCommand <CreateDocumentCommand>()
                             .Process(command => command.ExecuteAsync(document));

            await AddDocumentToOwner(ownerId, ownerType, documentId);

            DocumentWorkflow documentWorkflow = await Executor
                                                .GetQuery <GetInitialDocumentWorkflowQuery>()
                                                .Process(query => query.ExecuteAsync(documentId, executorId));

            await Executor
            .GetCommand <ApplyDocumentWorkflowCommand>()
            .Process(command => command.ExecuteAsync(documentWorkflow));

            await Executor
            .GetCommand <UpdateDocumentCommand>()
            .Process(command => command.Execute(document));

            await Executor
            .GetHandler <GenerateDocumentBarcodeHandler>()
            .Process(handler => handler.ExecuteAsync(documentId));

            await Executor
            .GetHandler <GenerateRegisterDocumentNumberHandler>()
            .Process(handler => handler.ExecuteAsync(documentId));

            await Executor
            .GetCommand <CreateUserInputCommand>()
            .Process(command => command.ExecuteAsync(documentId, userInput));

            await Executor
            .GetHandler <ProcessWorkflowByDocumentIdHandler>()
            .Process(handler => handler.ExecuteAsync(documentId));

            return(document.Id);
        }
Exemplo n.º 30
0
        public BaseResponse <UserOutputDto> Update(Guid userId, UserInputDto userInput)
        {
            var newUser = Mapper.Map <User>(userInput);
            var oldUser = Include(u => u.UserRoles).ThenInclude(ur => ur.Role).FirstOrDefault(u => u.Id == userId);

            oldUser = UpdateUserInformationIfChanged(oldUser, newUser);
            oldUser = UpdateUserRoleIfChanged(oldUser, oldUser.GetRoles(), userInput.Roles);
            return(new BaseResponse <UserOutputDto>(statusCode: HttpStatusCode.OK,
                                                    data: Mapper.Map <UserOutputDto>(oldUser)));
        }
Exemplo n.º 31
0
 // POST: api/User
 //[Route("post/api/user")]
 public async Task<IHttpActionResult> Post()
 {
     UserInputDto dto = new UserInputDto();
     dto.Email = "*****@*****.**";
     dto.NickName = "zfnglin";
     dto.IsLocked = false;
     dto.Password = "******";
     dto.PhoneNumber = "1232323";
     dto.PhoneNumberConfirmed = true;
     dto.RegistedIp = "1271.2.12";
     dto.UserName = "******";
     dto.EmailConfirmed = true;
     UserInputDto[] dtos = new UserInputDto[1] { dto };
     var v = await identity.AddUsers(dtos);
     return Ok(v);
 }
Exemplo n.º 32
0
 //[Route("put/api/user")]
 // PUT: api/User/5
 public async Task<OperationResult> Put(int id)
 {
     UserInputDto dto = new UserInputDto();
     dto.Id = id;
     dto.Email = "*****@*****.**";
     dto.NickName = "zfnglin";
     dto.IsLocked = false;
     dto.Password = "******";
     dto.PhoneNumber = "1232323";
     dto.PhoneNumberConfirmed = true;
     dto.RegistedIp = "1271.2.12";
     dto.UserName = "******";
     dto.EmailConfirmed = true;
     UserInputDto[] dtos = new UserInputDto[1] { dto };
     var v = await identity.EditUsers(dtos);
     return v;
 }
Exemplo n.º 33
0
 public async Task<ActionResult> Edit(UserInputDto[] dtos)
 {
     dtos.CheckNotNull("dtos");
     OperationResult result = await IdentityContract.EditUsers(dtos);
     return Json(result.ToAjaxResult());
 }