Пример #1
0
		public User CreateUser(CreateUser request)
		{
			var httpRequest = RequestContext.Get<IHttpRequest>();
			
			var authRepo = httpRequest.TryResolve<IUserAuthRepository>();
			if(authRepo==null)
				throw HttpError.NotFound("AuthRepository NO found");
			
			var  user= new UserAuth
			{	
				FirstName= request.FirstName,
				LastName= request.LastName,
				Email= request.Email,
				UserName= request.UserName,
				DisplayName = request.FirstName +" "+ request.LastName
			};
			user.Set<UserMeta>( new UserMeta{
				Info= request.Info,
				IsActive=request.IsActive,
				ExpiresAt= request.ExpiresAt
			});
			
			user = authRepo.CreateUserAuth(user, request.Password);

			User u = new User();
			u.PopulateWith(user);
			return u;
		}
Пример #2
0
        static void Main(string[] args)
        {
            InitializeENodeFramework();

            var commandService = ObjectContainer.Resolve<ICommandService>();
            var noteId = ObjectId.GenerateNewStringId();
            var command1 = new CreateUser
            {
                AggregateRootId = ObjectId.GenerateNewStringId(),
                UserName = "******",
                Password = "******",
                Sex = Sex.男,
                Signature = "牛逼"
            };

            Console.WriteLine(string.Empty);

            commandService.ExecuteAsync(command1, CommandReturnType.EventHandled).Wait();
            //commandService.ExecuteAsync(command2, CommandReturnType.EventHandled).Wait();

            Console.WriteLine(string.Empty);

            _logger.Info("Press Enter to exit...");

            Console.ReadLine();
            _configuration.ShutdownEQueue();
        }
Пример #3
0
        public void IsInvalid_WhenName_AlreadyExists()
        {
            var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
            var validator = new ValidateCreateUserCommand(queries.Object);
            var command = new CreateUser
            {
                Name = "alreadyIn",
            };
            Expression<Func<UserBy, bool>> expectedQuery = x => x.Name == command.Name;
            var entity = new User { Name = "AlreadyIn" };
            queries.Setup(x => x.Execute(It.Is(expectedQuery))).Returns(Task.FromResult(entity));

            var result = validator.Validate(command);

            result.IsValid.ShouldBeFalse();
            Func<ValidationFailure, bool> targetError = x => x.PropertyName == command.PropertyName(y => y.Name);
            result.Errors.Count(targetError).ShouldEqual(1);
            result.Errors.Single(targetError).ErrorMessage.ShouldEqual(Resources.Validation_AlreadyExists
                .Replace("{PropertyName}", User.Constraints.NameLabel)
                .Replace("{PropertyValue}", command.Name)
            );
            queries.Verify(x => x.Execute(It.Is(expectedQuery)), Times.Once);
            //validator.ShouldHaveValidationErrorFor(x => x.Name, command.Name);
            //queries.Verify(x => x.Execute(It.Is(expectedQuery)), Times.Once);
        }
Пример #4
0
        public void SetsCreatedProperty_OnCommand()
        {
            var command = new CreateUser { Name = "new" };
            var entities = new Mock<IWriteEntities>(MockBehavior.Loose);
            var handler = new HandleCreateUserCommand(entities.Object);

            handler.Handle(command);

            command.CreatedEntity.ShouldNotBeNull();
            command.CreatedEntity.Name.ShouldEqual(command.Name);
        }
Пример #5
0
        public void CreatesUserEntity()
        {
            var command = new CreateUser { Name = "new" };
            var entities = new Mock<IWriteEntities>(MockBehavior.Strict);
            var handler = new HandleCreateUserCommand(entities.Object);
            Expression<Func<User, bool>> expectedEntity = x => x.Name.Equals(command.Name);
            entities.Setup(x => x.Create(It.Is(expectedEntity)));

            handler.Handle(command);

            entities.Verify(x => x.Create(It.Is(expectedEntity)), Times.Once);
        }
Пример #6
0
        // GET: Home
        public async Task<ActionResult> Index()
        {
            var command = new CreateUser
            {
                AggregateRootId = ObjectId.GenerateNewStringId(),
                UserName = "******",
                Password = "******",
                Sex = Sex.男,
                Signature = "牛逼"
            };
            await ExecuteCommandAsync(command, 5000);

            return Content("success");
        }
Пример #7
0
        public void IsInvalid_WhenName_IsEmpty(string name)
        {
            var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
            var validator = new ValidateCreateUserCommand(queries.Object);
            var command = new CreateUser { Name = name };

            var result = validator.Validate(command);

            result.IsValid.ShouldBeFalse();
            Func<ValidationFailure, bool> targetError = x => x.PropertyName == command.PropertyName(y => y.Name);
            result.Errors.Count(targetError).ShouldEqual(1);
            result.Errors.Single(targetError).ErrorMessage
                .ShouldEqual(Resources.notempty_error.Replace("{PropertyName}", User.Constraints.NameLabel));
            //validator.ShouldHaveValidationErrorFor(x => x.Name, command.Name);
            queries.Verify(x => x.Execute(It.IsAny<UserBy>()), Times.Never);
        }
        public async Task<HttpResponseMessage> Post(CreateUser model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, ModelState);
            }

            var email = model.Email.ToLower(CultureInfo.CurrentCulture);
            var requiresActivation = !IsDebuggingEnabled;

            try
            {
                var token = await membershipService.Signup(
                    email,
                    model.Password,
                    UserRoles.User,
                    requiresActivation);

                if (requiresActivation)
                {
                    var userConfirmationToken = new UserConfirmationToken
                                                    {
                                                        Email = email,
                                                        Token = token
                                                    };

                    var securedToken = urlSafeSecureDataSerializer.Serialize(
                        userConfirmationToken);

                    await mailer.UserConfirmationAsync(email, securedToken);
                }
                else
                {
                    await newUserConfirmedHandler.Handle(email);
                }

                return Request.CreateResponse(HttpStatusCode.NoContent);
            }
            catch (IdentityException e)
            {
                ModelState.AddModelError(string.Empty, e);

                return Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, ModelState);
            }
        }
Пример #9
0
        public void IsInvalid_WhenNameLength_IsGreaterThan_MaxLength()
        {
            var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
            var validator = new ValidateCreateUserCommand(queries.Object);
            var command = new CreateUser { Name = string.Format("{0} {1} {2}", Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()) };

            var result = validator.Validate(command);

            result.IsValid.ShouldBeFalse();
            Func<ValidationFailure, bool> targetError = x => x.PropertyName == command.PropertyName(y => y.Name);
            result.Errors.Count(targetError).ShouldEqual(1);
            result.Errors.Single(targetError).ErrorMessage.ShouldEqual(Resources.Validation_MaxLength
                .Replace("{PropertyName}", User.Constraints.NameLabel)
                .Replace("{MaxLength}", User.Constraints.NameMaxLength.ToString(CultureInfo.InvariantCulture))
                .Replace("{TotalLength}", command.Name.Length.ToString(CultureInfo.InvariantCulture))
            );
            //validator.ShouldHaveValidationErrorFor(x => x.Name, command.Name);
            queries.Verify(x => x.Execute(It.IsAny<UserBy>()), Times.Never);
        }
Пример #10
0
        public async Task<User> CreateUser(CreateUser createUser)
        {
            try
            {
                var user = new User()
                    {
                        Salary = createUser.Salary,
                        HourlyRate = createUser.HourlyRate
                    };

                user = _userRepository.Save(user);
                return await Task.FromResult(user);

            }
            catch (Exception exception)
            {
                Console.Out.WriteLine(exception.Message);
            }
            return await Task.FromResult<User>(null);
        }
        public async Task<IHttpActionResult> Create(CreateUser model)
        {
            if (model == null)
            {
                ModelState.AddModelError("", "Data required");
            }

            if (ModelState.IsValid)
            {
                var result = await this.userManager.CreateUserAsync(model.Username, model.Password);
                if (result.IsSuccess)
                {
                    return Ok(result.Result);
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }

            return BadRequest(ModelState.GetErrorMessage());
        }
Пример #12
0
        public async Task <IActionResult> CreateUser([FromBody] CreateUser model, CancellationToken ct)
        {
            using (var transaction = await _unit.BeginTransactionAsync(ct))
            {
                var user = new User
                {
                    Active        = true,
                    UserName      = model.Email,
                    Email         = model.Email,
                    CreatedAt     = DateTime.UtcNow,
                    LastUpdatedAt = DateTime.UtcNow
                };

                var result = await _userManager.CreateAsync(user, model.Password);

                if (!result.Succeeded)
                {
                    throw new ConflictException("dados de usuário já existentes na aplicação");
                }

                var basicProfile = "Basic";
                var adminProfile = "Administrator";

                if (!await _roleManager.RoleExistsAsync(basicProfile))
                {
                    var role = new Role();
                    role.Name          = basicProfile;
                    role.Active        = true;
                    role.LastUpdatedAt = DateTime.UtcNow;
                    role.CreatedAt     = DateTime.UtcNow;

                    IdentityResult roleResult = await _roleManager.CreateAsync(role);

                    if (!roleResult.Succeeded)
                    {
                        throw new InternalServerError("Erro ao criar perfil básico");
                    }
                }

                if (!await _roleManager.RoleExistsAsync(adminProfile))
                {
                    var role = new Role();
                    role.Name          = adminProfile;
                    role.Active        = true;
                    role.LastUpdatedAt = DateTime.UtcNow;
                    role.CreatedAt     = DateTime.UtcNow;

                    IdentityResult roleResult = await _roleManager.CreateAsync(role);

                    if (!roleResult.Succeeded)
                    {
                        throw new InternalServerError("Erro ao criar perfil administrator");
                    }
                }

                await _userManager.AddToRoleAsync(user, basicProfile);

                await transaction.CommitAsync(ct);
            }

            var response = new Sample
            {
                Message = "user created"
            };

            return(Ok(response));
        }
        public async Task<ActionResult> Index()
        {
            serviceId = "AC";
            serviceSort = 10000;
            if (serviceDao.Entities.Where(m => m.Id == serviceId).Count() > 0)
            {
                return Content("数据库中已经存在数据库,不需要重新生成。");
            }
            //部门
            CreateDepartment();

            var service = new CreateService(serviceId, "统一授权中心", 1, "http://int.zhongyi-itl.com/");
            await this.commandService.Execute(service);

            var user = new CreateUser("sysadmin", "系统管理员", "Sysadmin", "*****@*****.**", "15817439909", "系统管理员");
            await this.commandService.Execute(user);

            var role = new CreateRole("系统管理员", 0);
            await this.commandService.Execute(role);
            await this.commandService.Execute(new SetUserRoles(user.AggregateRootId, new string[] { role.AggregateRootId }));


            var menu = new CreateMenu("统一授权中心", (int)MenuType.Web, "", "", serviceSort);
            await this.commandService.Execute(menu);
            var menuRoot = menu.AggregateRootId;

            var module = new CreateModule(serviceId, "System", "系统管理", serviceSort);
            await this.commandService.Execute(module);
            var moduleId = module.AggregateRootId;

            menu = new CreateMenu("系统管理", (int)MenuType.Web, "", "", serviceSort + 10, menuRoot);
            await this.commandService.Execute(menu);
            var menuId = menu.AggregateRootId;

            string moduleId2 = await QuickModule("Sys", "Department", "部门信息", moduleId, menuId, 11);

            var permission = new CreatePermission("DepartmentUser", "设置用户", moduleId2);
            await this.commandService.Execute(permission);

            //角色管理
            module = new CreateModule(serviceId, "Role", "角色管理", serviceSort + 16, moduleId);
            await this.commandService.Execute(module);
            permission = new CreatePermission("ViewRole", "查看", module.AggregateRootId);
            await this.commandService.Execute(permission);
            var viewRolePermissionId = permission.AggregateRootId;
            menu = new CreateMenu("角色管理", (int)MenuType.Web, "Sys/RoleList.aspx", "", serviceSort + 16, menuId, permission.AggregateRootId);
            await this.commandService.Execute(menu);
            permission = new CreatePermission("NewRole", "新增", module.AggregateRootId);
            await this.commandService.Execute(permission);
            permission = new CreatePermission("ModifyRole", "编辑", module.AggregateRootId);
            await this.commandService.Execute(permission);
            permission = new CreatePermission("DeleteRole", "删除", module.AggregateRootId);
            await this.commandService.Execute(permission);
            permission = new CreatePermission("PermissionRole", "分配权限", module.AggregateRootId);
            await this.commandService.Execute(permission);
            await this.commandService.Execute(new SetRolePermissions(role.AggregateRootId, new string[] { viewRolePermissionId, permission.AggregateRootId }));

            //用户管理
            moduleId2 = await QuickModule("Sys", "User", "用户管理", moduleId, menuId, 21);
            await this.commandService.Execute(permission);
            permission = new CreatePermission("ChangePwdUser", "修改密码", moduleId2);
            await this.commandService.Execute(permission);
            permission = new CreatePermission("RoleUser", "分配角色", moduleId2);
            await this.commandService.Execute(permission);
            await QuickModule("Sys", "Service", "服务管理", moduleId, menuId, 26);
            await QuickModule("Sys", "Module", "模块管理", moduleId, menuId, 31);
            await QuickModule("Sys", "Menu", "菜单管理", moduleId, menuId, 36);
            await QuickModule("Sys", "Authority", "权限管理", moduleId, menuId, 41);

            CreateRole();
            return Content("");
        }
Пример #14
0
 private async static Task CreateUser(CreateUser item)
 {
     var handler = new CreateUserHandler(_db.Database);
     await handler.SendAsync(item);
 }
Пример #15
0
 public void CreateAccount(CreateUser cu)
 {
     repo.CreateAccount(cu);
 }
Пример #16
0
        public async Task <IActionResult> Post([FromBody] CreateUser command)
        {
            await _busClient.PublishAsync(command);

            return(Accepted());
        }
        /// <summary>
        /// Returns true if ComAdobeGraniteAuthSamlSamlAuthenticationHandlerProperties instances are equal
        /// </summary>
        /// <param name="other">Instance of ComAdobeGraniteAuthSamlSamlAuthenticationHandlerProperties to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(ComAdobeGraniteAuthSamlSamlAuthenticationHandlerProperties other)
        {
            if (other is null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Path == other.Path ||
                     Path != null &&
                     Path.Equals(other.Path)
                     ) &&
                 (
                     ServiceRanking == other.ServiceRanking ||
                     ServiceRanking != null &&
                     ServiceRanking.Equals(other.ServiceRanking)
                 ) &&
                 (
                     IdpUrl == other.IdpUrl ||
                     IdpUrl != null &&
                     IdpUrl.Equals(other.IdpUrl)
                 ) &&
                 (
                     IdpCertAlias == other.IdpCertAlias ||
                     IdpCertAlias != null &&
                     IdpCertAlias.Equals(other.IdpCertAlias)
                 ) &&
                 (
                     IdpHttpRedirect == other.IdpHttpRedirect ||
                     IdpHttpRedirect != null &&
                     IdpHttpRedirect.Equals(other.IdpHttpRedirect)
                 ) &&
                 (
                     ServiceProviderEntityId == other.ServiceProviderEntityId ||
                     ServiceProviderEntityId != null &&
                     ServiceProviderEntityId.Equals(other.ServiceProviderEntityId)
                 ) &&
                 (
                     AssertionConsumerServiceURL == other.AssertionConsumerServiceURL ||
                     AssertionConsumerServiceURL != null &&
                     AssertionConsumerServiceURL.Equals(other.AssertionConsumerServiceURL)
                 ) &&
                 (
                     SpPrivateKeyAlias == other.SpPrivateKeyAlias ||
                     SpPrivateKeyAlias != null &&
                     SpPrivateKeyAlias.Equals(other.SpPrivateKeyAlias)
                 ) &&
                 (
                     KeyStorePassword == other.KeyStorePassword ||
                     KeyStorePassword != null &&
                     KeyStorePassword.Equals(other.KeyStorePassword)
                 ) &&
                 (
                     DefaultRedirectUrl == other.DefaultRedirectUrl ||
                     DefaultRedirectUrl != null &&
                     DefaultRedirectUrl.Equals(other.DefaultRedirectUrl)
                 ) &&
                 (
                     UserIDAttribute == other.UserIDAttribute ||
                     UserIDAttribute != null &&
                     UserIDAttribute.Equals(other.UserIDAttribute)
                 ) &&
                 (
                     UseEncryption == other.UseEncryption ||
                     UseEncryption != null &&
                     UseEncryption.Equals(other.UseEncryption)
                 ) &&
                 (
                     CreateUser == other.CreateUser ||
                     CreateUser != null &&
                     CreateUser.Equals(other.CreateUser)
                 ) &&
                 (
                     UserIntermediatePath == other.UserIntermediatePath ||
                     UserIntermediatePath != null &&
                     UserIntermediatePath.Equals(other.UserIntermediatePath)
                 ) &&
                 (
                     AddGroupMemberships == other.AddGroupMemberships ||
                     AddGroupMemberships != null &&
                     AddGroupMemberships.Equals(other.AddGroupMemberships)
                 ) &&
                 (
                     GroupMembershipAttribute == other.GroupMembershipAttribute ||
                     GroupMembershipAttribute != null &&
                     GroupMembershipAttribute.Equals(other.GroupMembershipAttribute)
                 ) &&
                 (
                     DefaultGroups == other.DefaultGroups ||
                     DefaultGroups != null &&
                     DefaultGroups.Equals(other.DefaultGroups)
                 ) &&
                 (
                     NameIdFormat == other.NameIdFormat ||
                     NameIdFormat != null &&
                     NameIdFormat.Equals(other.NameIdFormat)
                 ) &&
                 (
                     SynchronizeAttributes == other.SynchronizeAttributes ||
                     SynchronizeAttributes != null &&
                     SynchronizeAttributes.Equals(other.SynchronizeAttributes)
                 ) &&
                 (
                     HandleLogout == other.HandleLogout ||
                     HandleLogout != null &&
                     HandleLogout.Equals(other.HandleLogout)
                 ) &&
                 (
                     LogoutUrl == other.LogoutUrl ||
                     LogoutUrl != null &&
                     LogoutUrl.Equals(other.LogoutUrl)
                 ) &&
                 (
                     ClockTolerance == other.ClockTolerance ||
                     ClockTolerance != null &&
                     ClockTolerance.Equals(other.ClockTolerance)
                 ) &&
                 (
                     DigestMethod == other.DigestMethod ||
                     DigestMethod != null &&
                     DigestMethod.Equals(other.DigestMethod)
                 ) &&
                 (
                     SignatureMethod == other.SignatureMethod ||
                     SignatureMethod != null &&
                     SignatureMethod.Equals(other.SignatureMethod)
                 ) &&
                 (
                     IdentitySyncType == other.IdentitySyncType ||
                     IdentitySyncType != null &&
                     IdentitySyncType.Equals(other.IdentitySyncType)
                 ) &&
                 (
                     IdpIdentifier == other.IdpIdentifier ||
                     IdpIdentifier != null &&
                     IdpIdentifier.Equals(other.IdpIdentifier)
                 ));
        }
Пример #18
0
        public ActionResult Create(CreateUser command)
        {
            var response = mediator.Send(command);

            return(Ok(response));
        }
Пример #19
0
 public static User CreateNew(CreateUser cmd, IValidator <CreateUser> validator)
 {
     validator.ValidateCommand(cmd);
     return(new User(cmd));
 }
Пример #20
0
        public async Task <IActionResult> Post([FromBody] CreateUser command)
        {
            await DispatchAsync(command);

            return(Created($"user/{command.Email}", null));
        }
Пример #21
0
        public async Task <IActionResult> Register([FromBody] CreateUser createUserCommand)
        {
            await this.busClient.PublishAsync(createUserCommand);

            return(Accepted());
        }
Пример #22
0
 public async Task <CreatedEntity <int> > CreateUserAsync([FromBody] CreateUser createUser)
 {
     return(await _mediator.Send(createUser));
 }
Пример #23
0
        private void btnCriarCliente_Click(object sender, EventArgs e)
        {
            CreateUser FormcreateUser = new CreateUser(networkStream, aes);

            FormcreateUser.ShowDialog();
        }
Пример #24
0
        public ActionResult RegisterSubmit(CreateUser data)
        {
            var result = UserLogic.AddUser(data, UserType.User);

            return(Json(result));
        }
Пример #25
0
        // GET: CreateAccount
        public ActionResult CreateAccount()
        {
            CreateUser student = new CreateUser();

            return(View("~/Views/Student/CreateAccount/CreateAccount.cshtml", student));
        }
Пример #26
0
        //Created by Niranjan
        //Modified by Sandeep
        //Modified by Niranjan - 20/7/2016
        public bool APICreateUser(object[] lStrvalue)
        {
            //UsersData odata = new UsersData();
            try
            {
                clsGlobalVariable.strExceptionReport = string.Empty;
                string statusCode = string.Empty;
                string result     = string.Empty;
                //string allCourseResultresult = string.Empty;
                //string singleCourseresult = string.Empty;
                clsGeneric oGeneric     = new clsGeneric();
                string     URI          = string.Empty;
                Hashtable  htblTestData = new Hashtable();
                htblTestData = oGeneric.GetTestData(lStrvalue);
                bool _Flag = false;

                User userID = new User();

                GetAPICredentials oGetAPICredentials = new GetAPICredentials();

                //Get Org ID at runtime
                clsPage oPage = new clsPage(iWebdriver);
                _orgID       = oPage.GetOrganizationID();
                clsAPI.orgID = _orgID;


                Thread.Sleep(clsGlobalVariable.iWaitHigh);

                oGeneric.GetApiResponseCodeData(out statusCode, out result, "GET", clsAPI.apiURI + clsAPI.orgCredential.Replace("$", clsAPI.orgID), oGetAPICredentials, "H2", "", "");

                var        orgCredential = JsonConvert.DeserializeObject <GetAPICredentials>(result);
                Crypto3DES _des          = new Crypto3DES(ApplicationSettings.EComModuleEncKey());

                _ecomTransactionKey = _des.Decrypt3DES(orgCredential.TransactionKey);
                _ecomLoginKey       = _des.Decrypt3DES(orgCredential.LoginID);

                UpdateUser ouser = new UpdateUser();
                CreateUser cuser = new CreateUser();

                XDocument doc = XDocument.Load(clsGlobalVariable.ProjectDirectory + htblTestData["FieldsToBeUpdated"].ToString());

                List <UpdateUser> oList = doc.Root.Elements()
                                          .Select(x => new UpdateUser()
                {
                    Key   = x.Attribute("Key").Value,
                    Value = x.Attribute("Value").Value
                }).ToList();

                for (int i = 0; i <= oList.Count; i++)
                {
                    cuser.userProfileData = oList;
                }
                cuser.sendRegistrationMail      = "true";
                cuser.changePasswordAtNextLogin = "******";

                //Update Fields Value
                oGeneric.GetApiResponseCodeData(out statusCode, out result, "POST", clsAPI.apiURI + clsAPI.user.Replace("{orgid}", clsAPI.orgID), cuser, "H1", _ecomLoginKey, _ecomTransactionKey);

                //1st code checks whether the test cases is Negative or Positive
                if (htblTestData["TestCaseType"].ToString().ToUpper() == "NEGATIVE")
                {
                    //If Negative then we expect an error code
                    if (result.Contains("ErrorCode") || result.Contains("Invalid URI."))
                    {
                        if (result.Contains("Invalid URI."))
                        {
                            return(true);
                        }
                        //The error code can be from API of Course Pushdown
                        SuperAdminCoursePushDownErrorCode oError = new SuperAdminCoursePushDownErrorCode();
                        var error = JsonConvert.DeserializeObject <List <SuperAdminCoursePushDownError> >(result);

                        foreach (string errorcode in oError.coursePushDownErrorCode)
                        {
                            for (int i = 0; i < error.Count; i++)
                            {
                                if (error[i].ErrorCode == errorcode)
                                {
                                    _Flag = true;
                                }
                                else
                                {
                                    _Flag = false;
                                }
                            }
                            if (_Flag == true)
                            {
                                break;
                            }
                        }

                        if (_Flag == false)
                        {
                            //If Not from Course Push Down then The error code can be from General APIs
                            GeneralAPIErrCodes oError1 = new GeneralAPIErrCodes();
                            var error1 = JsonConvert.DeserializeObject <List <GeneralAPIErrCodes> >(result);
                            foreach (string errorcode in oError1.allAPIErrorCodes)
                            {
                                for (int i = 0; i < error.Count; i++)
                                {
                                    if (error[i].ErrorCode == errorcode)
                                    {
                                        _Flag = true;
                                        if (_Flag == true)
                                        {
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        _Flag = false;
                                    }
                                }
                                if (_Flag == true)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    if (_Flag == true)
                    {
                        return(_Flag);
                    }
                }
                else
                {
                    //If the test case is positive control will come here and then user should be created without any error code
                    if (statusCode == "Created/201")
                    {
                        _Flag = true;
                    }
                    else
                    {
                        _Flag = false;
                    }
                }
                return(_Flag);
            }
            catch (Exception e)
            {
                clsException.ExceptionHandler(e, iWebdriver, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name);

                return(false);
            }
        }
Пример #27
0
 public UsersController(CreateUser createUser)
 {
     _createUser = createUser;
 }
Пример #28
0
 public void UpdateAccount(CreateUser cu)
 {
     repo.UpdateAccount(cu);
 }
Пример #29
0
 public async Task Register(CreateUser command)
 {
     await DispatcheAsync <CreateUser>(command);
 }
Пример #30
0
        public async Task <IActionResult> RegisterAsync([FromBody] CreateUser command)
        {
            await _bus.PublishAsync(command);

            return(Accepted());
        }
Пример #31
0
 public async Task <CreateUserResponse> Create([FromBody] CreateUser dto)
 {
     return(await this.userService.Register(dto));
 }
Пример #32
0
        private void button1_Click(object sender, EventArgs e)
        {
            var addUser = new CreateUser();

            addUser.Show();
        }
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (Path != null)
         {
             hashCode = hashCode * 59 + Path.GetHashCode();
         }
         if (ServiceRanking != null)
         {
             hashCode = hashCode * 59 + ServiceRanking.GetHashCode();
         }
         if (IdpUrl != null)
         {
             hashCode = hashCode * 59 + IdpUrl.GetHashCode();
         }
         if (IdpCertAlias != null)
         {
             hashCode = hashCode * 59 + IdpCertAlias.GetHashCode();
         }
         if (IdpHttpRedirect != null)
         {
             hashCode = hashCode * 59 + IdpHttpRedirect.GetHashCode();
         }
         if (ServiceProviderEntityId != null)
         {
             hashCode = hashCode * 59 + ServiceProviderEntityId.GetHashCode();
         }
         if (AssertionConsumerServiceURL != null)
         {
             hashCode = hashCode * 59 + AssertionConsumerServiceURL.GetHashCode();
         }
         if (SpPrivateKeyAlias != null)
         {
             hashCode = hashCode * 59 + SpPrivateKeyAlias.GetHashCode();
         }
         if (KeyStorePassword != null)
         {
             hashCode = hashCode * 59 + KeyStorePassword.GetHashCode();
         }
         if (DefaultRedirectUrl != null)
         {
             hashCode = hashCode * 59 + DefaultRedirectUrl.GetHashCode();
         }
         if (UserIDAttribute != null)
         {
             hashCode = hashCode * 59 + UserIDAttribute.GetHashCode();
         }
         if (UseEncryption != null)
         {
             hashCode = hashCode * 59 + UseEncryption.GetHashCode();
         }
         if (CreateUser != null)
         {
             hashCode = hashCode * 59 + CreateUser.GetHashCode();
         }
         if (UserIntermediatePath != null)
         {
             hashCode = hashCode * 59 + UserIntermediatePath.GetHashCode();
         }
         if (AddGroupMemberships != null)
         {
             hashCode = hashCode * 59 + AddGroupMemberships.GetHashCode();
         }
         if (GroupMembershipAttribute != null)
         {
             hashCode = hashCode * 59 + GroupMembershipAttribute.GetHashCode();
         }
         if (DefaultGroups != null)
         {
             hashCode = hashCode * 59 + DefaultGroups.GetHashCode();
         }
         if (NameIdFormat != null)
         {
             hashCode = hashCode * 59 + NameIdFormat.GetHashCode();
         }
         if (SynchronizeAttributes != null)
         {
             hashCode = hashCode * 59 + SynchronizeAttributes.GetHashCode();
         }
         if (HandleLogout != null)
         {
             hashCode = hashCode * 59 + HandleLogout.GetHashCode();
         }
         if (LogoutUrl != null)
         {
             hashCode = hashCode * 59 + LogoutUrl.GetHashCode();
         }
         if (ClockTolerance != null)
         {
             hashCode = hashCode * 59 + ClockTolerance.GetHashCode();
         }
         if (DigestMethod != null)
         {
             hashCode = hashCode * 59 + DigestMethod.GetHashCode();
         }
         if (SignatureMethod != null)
         {
             hashCode = hashCode * 59 + SignatureMethod.GetHashCode();
         }
         if (IdentitySyncType != null)
         {
             hashCode = hashCode * 59 + IdentitySyncType.GetHashCode();
         }
         if (IdpIdentifier != null)
         {
             hashCode = hashCode * 59 + IdpIdentifier.GetHashCode();
         }
         return(hashCode);
     }
 }
Пример #34
0
        public void IsValid_WhenAllRulesPass()
        {
            var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
            var validator = new ValidateCreateUserCommand(queries.Object);
            var command = new CreateUser { Name = "valid" };
            Expression<Func<UserBy, bool>> expectedQuery = x => x.Name == command.Name;
            queries.Setup(x => x.Execute(It.Is(expectedQuery))).Returns(Task.FromResult(null as User));

            var result = validator.Validate(command);

            result.IsValid.ShouldBeTrue();
            queries.Verify(x => x.Execute(It.Is(expectedQuery)), Times.Once);
            //validator.ShouldNotHaveValidationErrorFor(x => x.Name, command.Name);
            //queries.Verify(x => x.Execute(It.Is(expectedQuery)), Times.Once);
        }
Пример #35
0
        public async Task <IActionResult> Post([FromBody] CreateUser command)
        {
            await CommandDispatcher.DispatchAsync(command);

            return(CreatedAtAction($"users/{command.Email}", new Object()));
        }
Пример #36
0
        public void PostUpdateUser([FromBody] CreateUser userBeingUpdated)
        {
            int userid = 0;

            if (Auth.IsAuthenticated())
            {
                userid = Auth.GetUserId();
            }

            // If an edit is happening to a brand-new user, it is possible that the UI does not yet
            // know its UserId. In that case we will attempt to determine it via the primary email.
            using (CSET_Context context = new CSET_Context())
            {
                if (userBeingUpdated.UserId == 0 || userBeingUpdated.UserId == 1)
                {
                    var u = context.USERS.Where(x => x.PrimaryEmail == userBeingUpdated.saveEmail).FirstOrDefault();
                    if (u != null)
                    {
                        userBeingUpdated.UserId = u.UserId;
                    }
                }
            }

            int assessmentId = -1;

            try
            {
                assessmentId = Auth.AssessmentForUser();
            }
            catch (HttpResponseException)
            {
                // The user is not currently 'in' an assessment
            }

            if (userid != userBeingUpdated.UserId)
            {
                if (assessmentId >= 0)
                {
                    // Updating a Contact in the context of the current Assessment.
                    Auth.AuthorizeAdminRole();

                    ContactsManager cm = new ContactsManager();
                    cm.UpdateContact(new ContactDetail
                    {
                        AssessmentId     = assessmentId,
                        AssessmentRoleId = userBeingUpdated.AssessmentRoleId,
                        FirstName        = userBeingUpdated.FirstName,
                        LastName         = userBeingUpdated.LastName,
                        PrimaryEmail     = userBeingUpdated.PrimaryEmail,
                        UserId           = userBeingUpdated.UserId,
                        Title            = userBeingUpdated.Title,
                        Phone            = userBeingUpdated.Phone
                    });
                    BusinessLogic.Helpers.AssessmentUtil.TouchAssessment(assessmentId);
                }
            }
            else
            {
                // Updating myself
                using (CSET_Context context = new CSET_Context())
                {
                    // update user detail
                    var user = context.USERS.Where(x => x.UserId == userBeingUpdated.UserId).FirstOrDefault();
                    user.FirstName    = userBeingUpdated.FirstName;
                    user.LastName     = userBeingUpdated.LastName;
                    user.PrimaryEmail = userBeingUpdated.PrimaryEmail;


                    // update my email address on any ASSESSMENT_CONTACTS
                    var myACs = context.ASSESSMENT_CONTACTS.Where(x => x.UserId == userBeingUpdated.UserId).ToList();
                    foreach (var ac in myACs)
                    {
                        ac.PrimaryEmail = userBeingUpdated.PrimaryEmail;
                    }

                    context.SaveChanges();


                    // update security questions/answers
                    var sq = context.USER_SECURITY_QUESTIONS.Where(x => x.UserId == userid).FirstOrDefault();
                    if (sq == null)
                    {
                        sq = new USER_SECURITY_QUESTIONS
                        {
                            UserId = userid
                        };
                        context.USER_SECURITY_QUESTIONS.Attach(sq);
                        context.SaveChanges();
                    }
                    sq.SecurityQuestion1 = NullIfEmpty(userBeingUpdated.SecurityQuestion1);
                    sq.SecurityAnswer1   = NullIfEmpty(userBeingUpdated.SecurityAnswer1);
                    sq.SecurityQuestion2 = NullIfEmpty(userBeingUpdated.SecurityQuestion2);
                    sq.SecurityAnswer2   = NullIfEmpty(userBeingUpdated.SecurityAnswer2);

                    // don't store a question or answer without its partner
                    if (sq.SecurityQuestion1 == null || sq.SecurityAnswer1 == null)
                    {
                        sq.SecurityQuestion1 = null;
                        sq.SecurityAnswer1   = null;
                    }
                    if (sq.SecurityQuestion2 == null || sq.SecurityAnswer2 == null)
                    {
                        sq.SecurityQuestion2 = null;
                        sq.SecurityAnswer2   = null;
                    }

                    // delete or add/update the record
                    if (sq.SecurityQuestion1 != null || sq.SecurityQuestion2 != null)
                    {
                        context.USER_SECURITY_QUESTIONS.AddOrUpdate(sq, x => x.UserId);
                    }
                    else
                    {
                        // both questions are null -- remove the record
                        context.USER_SECURITY_QUESTIONS.Remove(sq);
                    }

                    try
                    {
                        context.SaveChanges();
                        // Only touch the assessment if the user is currently in one.
                        if (assessmentId >= 0)
                        {
                            BusinessLogic.Helpers.AssessmentUtil.TouchAssessment(assessmentId);
                        }
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        // this can happen if there is no USER_SECURITY_QUESTIONS record
                        // but the code tries to delete it.
                    }
                }
            }
        }
Пример #37
0
        public async Task <HttpResponseMessage> Post(CreateUser model)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest, ModelState));
            }

            var statusCode = MembershipCreateStatus.Success;
            var userName   = model.Email.ToLowerInvariant();
            var token      = string.Empty;

            var requireConfirmation = !IsDebuggingEnabled;

            try
            {
                token = signup(userName, model.Password, requireConfirmation);
            }
            catch (MembershipCreateUserException e)
            {
                statusCode = e.StatusCode;
            }

            if (statusCode == MembershipCreateStatus.Success)
            {
                if (requireConfirmation)
                {
                    await mailer.UserConfirmationAsync(userName, token);
                }

                return(Request.CreateResponse(HttpStatusCode.NoContent));
            }

            switch (statusCode)
            {
            case MembershipCreateStatus.DuplicateUserName:
            case MembershipCreateStatus.DuplicateEmail:
            case MembershipCreateStatus.DuplicateProviderUserKey:
                ModelState.AddModelError(
                    "email",
                    "User with same email already exits.");
                break;

            case MembershipCreateStatus.InvalidUserName:
            case MembershipCreateStatus.InvalidEmail:
                ModelState.AddModelError(
                    "email",
                    "Invalid email address.");
                break;

            case MembershipCreateStatus.InvalidPassword:
                ModelState.AddModelError("password", "Invalid password.");
                break;

            default:
                ModelState.AddModelError(
                    string.Empty,
                    "Unexpected error.");
                break;
            }

            return(Request.CreateErrorResponse(
                       HttpStatusCode.BadRequest, ModelState));
        }
Пример #38
0
 private static string GetErrorMessage(CreateUser message, string field = "")
 {
     switch (message)
     {
         case CreateUser.Deletedaccount:
             return string.Format("The account for username '{0}' has been deleted.", field);
         case CreateUser.DuplicateUsername:
             return string.Format("The username '{0}' is unavailable.", field);
         case CreateUser.DuplicateEmail:
             return string.Format("The email address '{0}' is already registered to an account.", field);
         case CreateUser.Error:
             goto default;
         default:
             return "An error occured. An administrator has been notified of this issue.";
     }
 }
Пример #39
0
        public static User Create(CreateUser command)
        {
            User user = new User();
            user.State = UserState.Initial;

            user.EnsoureAndUpdateState(command);
            user.UserId = command.UserId;
            user.Name = command.Name;
            user.Email = command.Email;
            user.CreateAt = command.CreateAt;
            user.CreateBy = command.CreateBy;
            user.UpdateAt = command.CreateAt;
            user.UpdateBy = command.CreateBy;

            return user;
        }
Пример #40
0
        public HttpResponseMessage Post(UserApiModel model)
        {
            //System.Threading.Thread.Sleep(2000); // test api latency

            var command = new CreateUser(User, model.Name);
            Mapper.Map(model, command);

            try
            {
                _createUser.Handle(command);
            }
            catch (ValidationException ex)
            {
                var badRequest = Request.CreateResponse(HttpStatusCode.BadRequest,
                    ex.Errors.First().ErrorMessage, "text/plain");
                return badRequest;
            }

            var response = Request.CreateResponse(HttpStatusCode.Created, "User was successfully created.");
            var url = Url.Link(null, new
            {
                controller = "Users",
                action = "Get",
                userId = command.CreatedUserId,
            });
            Debug.Assert(url != null);
            response.Headers.Location = new Uri(url);

            return response;
        }
Пример #41
0
 public void CreateAccount(CreateUser cu, ref string errorMessage)
 {
     repo.CreateAccount(cu, ref errorMessage);
 }
Пример #42
0
        public async Task <IActionResult> Post([FromBody] CreateUser command)
        {
            await _busClient.PublishAsync(command); //how we can send message to bus, by invoking this method

            return(Accepted());                     //return without endpoint- relative turl to endpoint hwere activity will be fetch from
        }
Пример #43
0
        public async Task<HttpResponseMessage> Post(CreateUser model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, ModelState);
            }

            var statusCode = MembershipCreateStatus.Success;
            var userName = model.Email.ToLowerInvariant();
            var token = string.Empty;

            var requireConfirmation = !IsDebuggingEnabled;

            try
            {
                token = signup(userName, model.Password, requireConfirmation);
            }
            catch (MembershipCreateUserException e)
            {
                statusCode = e.StatusCode;
            }

            if (statusCode == MembershipCreateStatus.Success)
            {
                if (requireConfirmation)
                {
                    await mailer.UserConfirmationAsync(userName, token);
                }

                return Request.CreateResponse(HttpStatusCode.NoContent);
            }

            switch (statusCode)
            {
                case MembershipCreateStatus.DuplicateUserName:
                case MembershipCreateStatus.DuplicateEmail:
                case MembershipCreateStatus.DuplicateProviderUserKey:
                    ModelState.AddModelError(
                        "email",
                        "User with same email already exits.");
                    break;
                case MembershipCreateStatus.InvalidUserName:
                case MembershipCreateStatus.InvalidEmail:
                    ModelState.AddModelError(
                        "email",
                        "Invalid email address.");
                    break;
                case MembershipCreateStatus.InvalidPassword:
                    ModelState.AddModelError("password", "Invalid password.");
                    break;
                default:
                    ModelState.AddModelError(
                        string.Empty,
                        "Unexpected error.");
                    break;
            }

            return Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, ModelState);
        }
Пример #44
0
 void IAdminService.UpdateAccount(CreateUser cu)
 {
     throw new NotImplementedException();
 }
 public void When(CreateUser c)
 {
     Update(c, ar => ar.Create(c.Id, c.SecurityId));
 }
Пример #46
0
        /// <summary>
        /// Note that for now we are limiting the number of questions to two.
        /// </summary>
        /// <param name="userid">THIS VALUE SHOULD NEVER COME FROM THE POST OR URL ONLY THE AUTHTOKEN</param>
        /// <param name="user"></param>
        public void UpdateUser(int userid, string PrimaryEmail, CreateUser user)
        {
            using (CSET_Context db = new CSET_Context())
            {
                var dbuser = db.USERS.Where(x => x.UserId == userid).FirstOrDefault();
                TinyMapper.Map(user, dbuser);
                var details = db.USER_DETAIL_INFORMATION.Where(x => x.PrimaryEmail == PrimaryEmail).FirstOrDefault();
                if (details != null)
                {
                    TinyMapper.Map <CreateUser, USER_DETAIL_INFORMATION>(user, details);
                }

                /**
                 * Some things to think about
                 * they have existing questions and are updating them
                 * they don't have existing questions and are reusing and existing provided question
                 * they are giving us a new custom question
                 */

                // RKW - 9-May-2018 - Commenting out the question logic until we know if we are doing it or not
                #region Security Question Logic
                //List<int> processedQuestions = new List<int>();
                //Dictionary<int, USER_SECURITY_QUESTIONS> existingQuestions = (from a in db.USER_SECURITY_QUESTIONS
                //                                           join b in db.SECURITY_QUESTION on a.SecurityQuestionID equals b.SecurityQuestionId
                //                                           where a.UserId == userid
                //                                           select a
                //                                           ).ToDictionary(x => x.SecurityQuestionID, x => x);
                //USER_SECURITY_QUESTIONS question;
                //if(existingQuestions.TryGetValue(user.CustomQuestion.SecurityQuestionId, out question))
                //{
                //    question.SecurityAnswer = user.CustomQuestion.Answer;
                //    processedQuestions.Add(user.CustomQuestion.SecurityQuestionId);
                //}
                //else
                //{
                //    SECURITY_QUESTION sq= new SECURITY_QUESTION()
                //    {
                //        SecurityQuestion = user.CustomQuestion.SecurityQuestion,
                //        IsCustomQuestion = true
                //    };
                //    db.USER_SECURITY_QUESTIONS.Add(new USER_SECURITY_QUESTIONS()
                //    {
                //        SecurityAnswer = user.CustomQuestion.Answer,
                //        SECURITY_QUESTION = sq,
                //        UserId = userid
                //    });
                //    db.SECURITY_QUESTION.Add(sq);
                //}
                //if(existingQuestions.TryGetValue(user.SelectedQuestion.SecurityQuestionId,out question))
                //{
                //    question.SecurityAnswer = user.SelectedQuestion.Answer;
                //    processedQuestions.Add(user.SelectedQuestion.SecurityQuestionId);
                //}
                //else
                //{
                //    db.USER_SECURITY_QUESTIONS.Add(new USER_SECURITY_QUESTIONS()
                //    {
                //        SecurityQuestionID = user.SelectedQuestion.SecurityQuestionId,
                //        SecurityAnswer = user.SelectedQuestion.Answer,
                //        UserId = userid
                //    });
                //}
                ////remove all the others;
                //foreach(KeyValuePair<int,USER_SECURITY_QUESTIONS> pair in existingQuestions)
                //{
                //    if (!processedQuestions.Contains(pair.Key))
                //    {
                //        db.USER_SECURITY_QUESTIONS.Remove(pair.Value);
                //    }
                //}
                #endregion

                db.SaveChanges();
            }
        }
Пример #47
0
        public HttpResponseMessage ValidateName(int userId, UserApiModel model)
        {
            //System.Threading.Thread.Sleep(10000); // test api latency

            model.Id = userId;

            var command = new CreateUser(User, model.Name);
            var validationResult = _createValidator.Validate(command);
            var propertyName = command.PropertyName(y => y.Name);

            Func<ValidationFailure, bool> forName = x => x.PropertyName == propertyName;
            if (validationResult.Errors.Any(forName))
                return Request.CreateResponse(HttpStatusCode.BadRequest,
                    validationResult.Errors.First(forName).ErrorMessage, "text/plain");

            return Request.CreateResponse(HttpStatusCode.OK);
        }
Пример #48
0
        /// <summary>
        /// Opens the create teacher window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateTeacherBtn_Click(object sender, EventArgs e)
        {
            CreateUser teacherCreationWindow = new CreateUser(connection, "Faculty", admin);

            teacherCreationWindow.Show();
        }
 public void SetUp()
 {
     theModel = new CreateUser { Username = "******" };
     theService = MockRepository.GenerateStub<IUserService>();
 }
Пример #50
0
        /// <summary>
        /// Opens the student creation window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateStudentButton_Click(object sender, EventArgs e)
        {
            CreateUser studentCreationWindow = new CreateUser(connection, "Student", admin);

            studentCreationWindow.Show();
        }
Пример #51
0
 static string When(CreateUser e)
 {
     return string.Format("Create user {0} for security {1}", e.Id.Id, e.SecurityId.Id);
 }
 public virtual string Generate(CreateUser createUser)
 {
     return (createUser.Email + createUser.DateOfBirth).GetHashCode().ToString();
 }