public async Task <IActionResult> CreateUser([FromBody] CreateUserInputModel inputModel)
        {
            var command = new CreateUserCommand(inputModel.Name, inputModel.Email, inputModel.BirthDate, inputModel.Password, inputModel.Role);
            var result  = await _mediator.Send(command);

            return(CreatedAtAction(nameof(GetUser), new { id = result.Id }, result));
        }
示例#2
0
        public async Task <IActionResult> Create(CreateUserInputModel input)
        {
            var managerId = this.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

            await this.usersService.CreateAsync(managerId, input);

            return(this.Redirect("/"));
        }
示例#3
0
        public int Create(CreateUserInputModel inputModel)
        {
            var user = new User(inputModel.FullName, inputModel.Email, inputModel.BirthDate);

            _dbContext.Users.Add(user);

            return(user.Id);
        }
示例#4
0
        public int Create(CreateUserInputModel inputModel)
        {
            var user = new User(inputModel.FullName, inputModel.Email, inputModel.BirthDate, inputModel.Password, inputModel.Role);

            _dbContext.Users.Add(user);
            _dbContext.SaveChanges();

            return(user.Id);
        }
示例#5
0
        public async Task <IActionResult> Create(
            [Bind("Username", "Email", "Password",
                  "ConfirmPassword", "RoleType", "RecaptchaValue")]
            CreateUserInputModel input)
        {
            if (!this.ModelState.IsValid)
            {
                this.ViewData["Roles"] = this.userService.Roles();
                return(this.View(input ?? new CreateUserInputModel()));
            }

            var result = await this.userService.Create(input);

            if (!result.Succeeded)
            {
                this.AddErrors(result);
                return(this.ShowErrorLocal(this.sharedLocalizer.GetHtmlString(ErrorMessages.UnsuccessfulCreate), ViewUsersUrl));
            }

            var user = await this.userService.ByUsername(input.Username);

            string code = await this.userService.GenerateEmailToken(user);

            string callbackUrl = this.Url.Page(
                EmailConfirmationUrl,
                pageHandler: null,
                values: new { area = "Identity", userId = user.Id, code },
                protocol: this.Request.Scheme);

            //Upon creation send email confirmation to new user
            string emailMessage = string.Format(GlobalConstants.EmailConfirmationMessage, user.UserName, HtmlEncoder.Default.Encode(callbackUrl));

            await this.emailSender.SendEmailAsync(
                this.configuration.GetValue <string>($"{AppSettingsSections.EmailSection}:{EmailOptions.Address}"),
                this.configuration.GetValue <string>($"{AppSettingsSections.EmailSection}:{EmailOptions.Sender}"),
                user.Email,
                GlobalConstants.ConfirmEmailSubject,
                emailMessage);

            var dto = new NotificationDto
            {
                Arg     = input.Username,
                Message = InfoMessages.CreateUserNotification,
                User    = this.User,
                Link    = ViewUsersUrl,
            };

            await this.notificationHelper.SendToAdmin(dto);

            string infoMessage = string.Format(this.sharedLocalizer
                                               .GetHtmlString(InfoMessages.AddUser),
                                               user.UserName,
                                               input.RoleType);

            return(this.ShowInfoLocal(infoMessage, ViewUsersUrl));
        }
示例#6
0
        //[Authorize(Policy = "AdminOnly")]
        public IActionResult CreateUser(CreateUserInputModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            _userAppServices.CreateUser(model);
            return(Ok());
        }
示例#7
0
        private async Task AssignRole(CreateUserInputModel input, ApplicationUser user)
        {
            var role      = input.RoleType;
            var roleExist = await this.roleManager.RoleExistsAsync(role);

            if (roleExist)
            {
                await this.userManager.AddToRoleAsync(user, role);
            }
        }
        public async Task CreateUser(CreateUserInputModel input)
        {
            var hashandSalt = PasswordHelper.HashPassword(input.Password);

            string[] splitData = hashandSalt.Split(':');
            var      model     = _mapper.Map <User>(input);

            model.PasswordHash = splitData[2];
            model.PasswordSalt = splitData[1];
            await _userRepository.Insert(model);
        }
示例#9
0
        public async Task <ActionResult <UserOutputModel> > Register(CreateUserInputModel input)
        {
            var result = await this.identity.Register(input);

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors));
            }

            return(await Login(input));
        }
示例#10
0
        public void RegisterUser(CreateUserInputModel model)
        {
            var user = new User()
            {
                Username = model.Username,
                Email    = model.Email,
                Password = ComputeHash(model.Password)
            };

            this.db.Users.Add(user);
            this.db.SaveChanges();
        }
示例#11
0
        public async Task <IActionResult> CreateUser(
            [Bind("Username", "Email", "Password", "ConfirmPassword", "RoleType", "RecaptchaValue")]
            CreateUserInputModel inputModel)
        {
            string returnUrl = ViewUsersUrl;

            if (!this.ModelState.IsValid)
            {
                this.ViewData["Roles"] = this.roleManager.Roles.ToList();
                return(this.View(inputModel ?? new CreateUserInputModel()));
            }

            var user = new ApplicationUser
            {
                UserName = inputModel.Username,
                Email    = inputModel.Email,
            };

            var result = await this.userManager.CreateAsync(user, inputModel.Password);

            if (result.Succeeded)
            {
                this.logger.LogInformation("User created a new account with password.");
                await this.AssignRoleToUser(inputModel, user);

                // Upon creation send email confirmation to new user
                string code = await this.userManager.GenerateEmailConfirmationTokenAsync(user);

                string callbackUrl = this.Url.Page(
                    EmailConfirmationUrl,
                    pageHandler: null,
                    values: new { area = "Identity", userId = user.Id, code },
                    protocol: this.Request.Scheme);

                string emailMessage = string.Format(GlobalConstants.EmailConfirmationMessage, HtmlEncoder.Default.Encode(callbackUrl));
                await this.emailSender.SendEmailAsync(
                    "*****@*****.**",
                    "Pharus Management Lux SA",
                    inputModel.Email,
                    GlobalConstants.ConfirmEmailSubject,
                    emailMessage);

                string infoMessage = string.Format(this.sharedLocalizer.GetHtmlString(InfoMessages.AddUser), user.UserName, inputModel.RoleType);

                return(this.ShowInfoLocal(infoMessage, returnUrl));
            }

            this.AddErrors(result);

            return(this.ShowErrorLocal(this.sharedLocalizer.GetHtmlString(ErrorMessages.UnsuccessfulCreate), returnUrl));
        }
        public void CreateUser([FromBody] CreateUserInputModel model)
        {
            byte[] passwordHashUser, passwordSaltUser;
            _service.CreatePassword(model.Password, out passwordHashUser, out passwordSaltUser);
            User user = new User
            {
                PasswordHash = passwordHashUser,
                PasswordSalt = passwordSaltUser,
                IsAdmin      = model.IsAdmin,
                Username     = model.Username
            };

            _service.Add(user);
        }
示例#13
0
        public ActionResult <ApiResultModel <int> > Create([FromForm] CreateUserInputModel inputModel)
        {
            if (!this.TryValidateModel(inputModel))
            {
                return(Ok(new ApiResultModel <int>(200, 10)));
            }
            var row    = _userRepository.Create(inputModel);
            int status = 0;

            if (row == null)
            {
                status = 1;
            }
            return(Ok(new ApiResultModel <int>(200, status)));
        }
示例#14
0
        public async Task <IdentityResult> Create(CreateUserInputModel input)
        {
            var user = new ApplicationUser
            {
                UserName = input.Username,
                Email    = input.Email,
            };

            var result = await this.userManager.CreateAsync(user, input.Password);

            if (result.Succeeded)
            {
                await this.AssignRole(input, user);
            }

            return(result);
        }
示例#15
0
        public User CreateUser(CreateUserInputModel input)
        {
            var user = new User
            {
                Name  = input.Name,
                Color = input.Color,

                CreatedDateTime = DateTime.UtcNow,
                UpdatedDateTime = DateTime.UtcNow,
            };

            DbContext.Users.Add(user);

            DbContext.SaveChanges();

            return(user);
        }
示例#16
0
        /// <summary>
        /// Executes the command
        /// </summary>
        /// <returns>created user</returns>
        public async Task <User> Execute(CreateUserInputModel model)
        {
            // Check access rights: Admin
            await accessRightChecker.CheckUserIsAdmin();

            // pretreatment of model
            model.CheckAndPrepare();

            // specific validation

            if (model.Password != model.PasswordConfirmation)
            {
                throw new BusinessException("Password and confirmation password do not match");
            }
            if (model.Password.Length < 6)
            {
                throw new BusinessException("Length of password must be at least 6 symbols");
            }

            model.Email = model.Email.ToLower(); // making lowercase
            if (!EmailValidationUtility.CheckIsValidEmail(model.Email))
            {
                throw new BusinessException("Email specified not correctly");
            }

            if (await userRepository.AnyAsync(a => a.Email == model.Email))
            {
                throw new BusinessException("User with specified email already exists");
            }

            // creating object
            User user = new User
            {
                Name                  = model.Name,
                Email                 = model.Email,
                PasswordHash          = HashHelper.GetHashString(model.Password),
                AuthenticationTokenId = Guid.NewGuid()
            };
            await userRepository.AddAsync(user);

            // saving made changes
            await changesSaver.SaveChangesAsync();

            return(user);
        }
示例#17
0
        public HttpResponse Register(CreateUserInputModel model)
        {
            if (IsUserSignedIn())
            {
                return(this.Redirect("/"));
            }

            if (string.IsNullOrEmpty(model.Username) ||
                model.Username.Length < 5 ||
                model.Username.Length > 20)
            {
                return(this.Error("Username is required and should be between 5 and 20 characters long."));
            }

            if (!this.usersService.IsUsernameAvailable(model))
            {
                return(this.Error("Username is not available."));
            }

            if (string.IsNullOrEmpty(model.Email) ||
                !new EmailAddressAttribute().IsValid(model.Email) ||
                model.Email.Length < 5 ||
                model.Email.Length > 20)
            {
                return(this.Error("Email is required and should be between 5 and 20 characters long."));
            }

            if (!this.usersService.IsEmailAvailable(model))
            {
                return(this.Error("Email is not available."));
            }

            if (string.IsNullOrEmpty(model.Password))
            {
                return(this.Error("Password is required."));
            }

            if (model.ConfirmPassword != model.Password)
            {
                return(this.Error("Passwords do not match."));
            }

            this.usersService.CreateUser(model);
            return(this.Redirect("/Users/Login"));
        }
        public async Task <Result <User> > Register(CreateUserInputModel userInput)
        {
            var user = new User
            {
                Email     = userInput.Email,
                UserName  = userInput.Email,
                FirstName = userInput.FirstName,
                LastName  = userInput.LastName
            };

            var identityResult = await this.userManager.CreateAsync(user, userInput.Password);

            var errors = identityResult.Errors.Select(e => e.Description);

            return(identityResult.Succeeded
                ? Result <User> .SuccessWith(user)
                : Result <User> .Failure(errors));
        }
示例#19
0
        public UtUsers Create(CreateUserInputModel model)
        {
            UtUsers row = new UtUsers()
            {
                Email       = model.Email,
                Username    = model.UserName,
                Userpws     = model.UserPassword,
                UserGroupId = model.GroupId,
                ColorId     = model.ColorId,
                CompanyName = model.CompanyName,
                FullName    = model.FullName,
                Id          = LastId() + 1
            };

            _context.Add(row);
            _context.SaveChanges();
            return(row);
        }
示例#20
0
        public async Task <object> JoinRoom(CreateUserInputModel userInput, string roomId)
        {
            User user;

            if (userInput.Id.HasValue)
            {
                if (_connectionService.CheckIfUserAlreadyConnected(roomId, userInput.Id.Value))
                {
                    return(new { success = false, message = "User already connected." });
                }
                user = _userService.GetUser(userInput.Id.Value);
            }
            else
            {
                // Create user and add to room
                user = _userService.CreateUser(userInput);
                _roomService.AddUserToRoom(roomId, user);
            }

            // Add connection
            var room = _roomService.GetRoom(roomId);

            _connectionService.AddConnection(user, room, Context.ConnectionId);
            var connections = _connectionService.GetRoomConnections(roomId);

            await Clients.Group(roomId).SendAsync("UserJoin", new { user });

            await Groups.AddToGroupAsync(Context.ConnectionId, roomId);

            await Clients.Caller.SendAsync("AllowedIn", user);

            await Clients.Caller.SendAsync("UserList", connections.Select(c => c.User).ToList());

            await Clients.Caller.SendAsync("AllUsersList", _userService.GetUsersInRoom(roomId));

            await Clients.Caller.SendAsync("NewSpeaker", new { userId = room.CurrentSpeakerUserId, endTime = room.CurrentSpeakerEndTime, duration = room.CurrentSpeakerDuration });

            var chatHistory = _roomService.GetRoomChatHistory(room.Id, DateTime.UtcNow);

            return(new { success = true, chatHistory = chatHistory.Select(m => new { m.FromUserId, m.Text, m.CreatedDateTime }) });
        }
示例#21
0
        public async Task <IActionResult> Post([FromBody] CreateUserInputModel inputModel)
        {
            if (await _context.Users.AnyAsync(t => t.Account == inputModel.Account))
            {
                return(BadRequest("账号已存在"));
            }

            var dncUser = new DncUser
            {
                Account  = inputModel.Account,
                Password = inputModel.Password,
                NiName   = inputModel.NiName,
                Status   = inputModel.Status,
                Remark   = inputModel.Remark
            };

            await _context.Users.AddAsync(dncUser);

            await _context.SaveChangesAsync();

            return(Ok());
        }
        public ActionResult Create(CreateUserInputModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("Create", model));
            }

            var result = _userService.Create(new CreateUserParameters(model.EmailAddress, model.Password));

            if (result.Success)
            {
                ViewBag.Message = $"User {model.EmailAddress} created.";
                return(View(new CreateUserInputModel()
                {
                    EmailAddress = string.Empty,
                    Password = string.Empty
                }));
            }

            ViewBag.Message = $"Sorry something went wrong. Please try again.";
            return(View(model));
        }
        public async Task <ActionResult> Register(
            CreateUserInputModel input)
        {
            var result = await this.identity.Register(input);

            if (!result.Succeeded)
            {
                return(BadRequest(result));
            }

            var user = result.Data;

            var dealer = new Dealer
            {
                Name        = input.Name,
                PhoneNumber = input.PhoneNumber,
                UserId      = user.Id
            };

            await this.dealers.Save(dealer);

            return(Ok());
        }
示例#24
0
        public async Task <string> CreateUserAsync(CreateUserInputModel model)
        {
            var user = new User
            {
                UserName  = model.Username,
                Email     = model.Email,
                FirstName = model.FirstName,
                LastName  = model.LastName
            };

            var result = await this.UserManager.CreateAsync(user);

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

            var userCreated = this.UserManager.Users.FirstOrDefault(x => x.UserName == user.UserName);

            await this.UserManager.AddToRoleAsync(userCreated, SeedDataConstants.UserRole);

            return(userCreated.Id);
        }
        public async Task <IActionResult> Create(CreateUserInputModel model)
        {
            if (!ModelState.IsValid)
            {
                return(this.View(model));
            }

            var result = await this.UserService.CreateUserAsync(model);

            if (result != null)
            {
                return(RedirectToAction(nameof(Details), new { id = result }));
            }
            else
            {
                this.TempData.Put(MessageConstants.Name, new MessageModel
                {
                    Type    = MessageType.Danger,
                    Message = "The User has not been successfully created!"
                });

                return(View(model));
            }
        }
        public async Task <ActionResult> Create(CreateUserInputModel input)
        {
            var createdUserId = await this.usersService.CreateAsync(input.Username, input.Password);

            return(this.Created($"/users/{createdUserId}", null));
        }
 public bool IsEmailAvailable(CreateUserInputModel model)
 {
     return(!this.dbContext.Users.Any(x => x.Email == model.Email));
 }
示例#28
0
 public async Task Create([FromBody] CreateUserInputModel model) => await createUserCommand.Execute(model);
 public bool IsUsernameAvailable(CreateUserInputModel model)
 {
     return(!this.dbContext.Users.Any(x => x.Username == model.Username));
 }