예제 #1
0
        public async Task <IActionResult> CreateUser([FromBody] UserCreateRequestModel user)
        {
            if (user == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var existingAccount = await _userService.GetAsync(user.AccountNumber);

            if (existingAccount != null)
            {
                return(GetBadRequest(user, $"User with account number {user.AccountNumber} already exists."));
            }

            var userDto = Mapper.Map <UserCreateModel>(user);

            var newUserId = await _userService.AddAsync(userDto);

            return(await GetCreatedRequestModel(user, newUserId, "GetUser"));
        }
예제 #2
0
 public UserRequestModel InsertUser([FromBody] UserCreateRequestModel user)
 {
     try
     {
         _ = _userDataService.InsertUser(user).Result;
     }
     catch (Exception e)
     {
         UserRequestModel model = new UserRequestModel();
         if (e.Message.Contains("Incorrect Data!"))
         {
             Response.StatusCode = 400;
             model.Status        = (System.Net.HttpStatusCode) 400;
             model.ErrorMessage  = e.Message;
             return(model);
         }
         else if (e.Message.Contains("already exist"))
         {
             Response.StatusCode = 409;
             model.Status        = (System.Net.HttpStatusCode) 409;
             model.ErrorMessage  = e.Message;
             return(model);
         }
         else
         {
             Response.StatusCode = 500;
             model.Status        = (System.Net.HttpStatusCode) 500;
             model.ErrorMessage  = e.Message;
             return(model);
         }
     }
     Response.StatusCode = 200;
     return(new UserRequestModel());
 }
예제 #3
0
        public async Task <ActionResult <UserModel> > Initialize([FromBody] UserCreateRequestModel user)
        {
            var usersCount = await database.Count <UserModel>();

            if (usersCount > 0L)
            {
                return(BadRequest(new ErrorModel(400, "already initialized")));
            }

            if (!user.IsValidUsername())
            {
                return(BadRequest(new ErrorModel(400, "invalid username")));
            }

            if (!user.IsValidPassword())
            {
                return(BadRequest(new ErrorModel(400, "invalid new password")));
            }

            user.AfterCreate();
            user.LastLogin    = default;
            user.IsAdmin      = true;
            user.DisplayName  = user.DisplayName.IsNullOrEmpty() ? user.UserName : user.DisplayName;
            user.PasswordHash = hasher.Create(user.Password);

            await database.Put(user);

            var resUser = new UserModel(user);

            return(Created("user", resUser));
        }
예제 #4
0
        public async Task <int> InsertUser(UserCreateRequestModel user)
        {
            Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
            Match match = regex.Match(user.Email);

            if (!match.Success)
            {
                throw new BadRequestException("Incorrect Data! Email must have '@' and after that <string>.<string>, e.g. [email protected]");
            }
            validateString(user.Username, "Incorrect Data! Username must between " + _minCharValidationUsername + " and " + _maxCharValidationUsername + " symbols!");
            validateString(user.Username, "Incorrect Data! Password must between " + _minCharValidationPassword + " and " + _maxCharValidationPassword + " symbols!");
            if (!user.Password.Contains(user.Password2))
            {
                throw new BadRequestException("Incorrect Data! Entered Password and Confirm password do not match");
            }
            if (await IsUserExistingByName(user.Username))
            {
                throw new AlreadyExistException("User with username: "******" already exist!");
            }

            using var conn = await _database.CreateConnectionAsync();

            string hashedPassword = BCrypt.HashPassword(user.Password);

            var parameters = new
            {
                Username = user.Username,
                Email    = user.Email,
                Password = hashedPassword,
            };

            return(await conn.ExecuteAsync("INSERT INTO [USER](Username, Email, Password) VALUES (@Username, @Email, @Password); SELECT SCOPE_IDENTITY();", parameters));
        }
예제 #5
0
        public async Task <IHttpActionResult> UpdateUser(UserCreateRequestModel model)
        {
            model.ModifiedBy = User.Identity.GetUserId();
            model.Modified   = DateTime.Now;

            var isInSystemAdminRole = User.IsInRole(StaticRoles.SystemAdmin.Name);

            if (isInSystemAdminRole)
            {
                return(Ok(await _service.UpdateUserAsync(model)));
            }

            if (string.IsNullOrWhiteSpace(model.TenantId))
            {
                model.TenantId   = User.Identity.GetTenantId();
                model.TenantName = User.Identity.GetTenantName();
                model.CompanyId  = User.Identity.GetCompanyId();
            }
            else
            {
                var tenant = await _tenantProvider.GetTenantAsync(model.TenantId);

                model.TenantName = tenant.TenancyName;
                model.CompanyId  = _companyProvider.GetAll().FirstOrDefault(x => x.TenantId == tenant.Id)?.Id;
            }


            return(Ok(await _service.UpdateUserAsync(model)));
        }
예제 #6
0
        public async Task <IActionResult> UpdateUser(Guid id, [FromBody] UserCreateRequestModel user)
        {
            if (user == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userExists = await _userService.ExistsAsync(id);

            if (!userExists)
            {
                return(GetNotFound());
            }


            var userDto = Mapper.Map <UserCreateModel>(user);
            await _userService.UpdateAsync(id, userDto);

            return(NoContent());
        }
예제 #7
0
        public async Task <ActionResult <UserModel> > Create([FromBody] UserCreateRequestModel user)
        {
            // Validation is done by MVC request model.

            //if (!user.IsValidUsername())
            //    return BadRequest(new ErrorModel(400, "invalid username"));

            //if (!user.IsValidPassword())
            //    return BadRequest(new ErrorModel(400, "invalid new password"));

            if (await database.GetUserByUserName(user.UserName) != null)
            {
                return(BadRequest(new ErrorModel(400, "username already taken")));
            }

            user.AfterCreate();
            user.LastLogin    = default;
            user.DisplayName  = user.DisplayName.IsNullOrEmpty() ? user.UserName : user.DisplayName;
            user.PasswordHash = hasher.Create(user.Password);
            // TODO: Replace with mail confirmation
            user.EmailAddress = null;

            await database.Put(user);

            var resUser = new UserModel(user);

            return(Created("user", resUser));
        }
예제 #8
0
        public ActionResult <CommonResponeModel> Create(UserCreateRequestModel model)
        {
            if (userRepository.IsExistUsername(model.Username))
            {
                string message = UserMessageGlobal.ExistUsername;
                Result = new ErrorResult(ActionType.Login, message);
            }
            else
            {
                var databaseObject = model.MapTo <User>();
                databaseObject.InitBeforeSave(RequestUsername, InitType.Create);
                databaseObject.InitDefault();
                databaseObject.SetPassword();
                int result = userRepository.Insert(databaseObject);

                if (result > 0)
                {
                    Result = new SuccessResult(ActionType.Insert, AppGlobal.CreateSucess);
                    Data   = databaseObject;
                }
                else
                {
                    Result = new ErrorResult(ActionType.Insert, AppGlobal.CreateError);
                    Data   = databaseObject;
                }
            }

            return(GetCommonRespone());
        }
예제 #9
0
        private UserModel fromDtoToUser(UserCreateRequestModel userRequestModel)
        {
            UserModel userModel = new UserModel();

            userRequestModel.Username = userModel.Username;
            userRequestModel.Email    = userModel.Email;
            userRequestModel.Password = userModel.Password;
            return(userModel);
        }
예제 #10
0
        public string CreateTenantAdminUser(TenantViewModel model, string tenantId, string companyId, string branchId, string adminRoleId)
        {
            string employeeId = CreateTenantAdminEmployee(model, tenantId, companyId, branchId);

            var userId = Guid.NewGuid().ToString();

            var adminUser = new UserCreateRequestModel
            {
                Id             = userId,
                FirstName      = model.FirstName,
                LastName       = model.LastName,
                Email          = model.Email,
                UserName       = model.Email,
                PhoneNumber    = model.PhoneNumber,
                PasswordHash   = model.PasswordHash,
                RetypePassword = model.RetypePassword,
                SecurityStamp  = Guid.NewGuid().ToString(),

                RoleId = !string.IsNullOrWhiteSpace(adminRoleId) ? adminRoleId : _roleManager.GetByName(StaticRoles.Admin.Name)?.Id,

                //EmailConfirmationCode = emailConfirmationCode,
                //PhoneConfirmationCode = phoneNumberConfirmationCode,

                TenantId   = tenantId,
                TenantName = model.TenancyName,
                CompanyId  = companyId,
                BranchId   = branchId,
                EmployeeId = employeeId,

                IsActive  = true,
                CreatedBy = null,
                Created   = DateTime.Now,
                IsShouldChangedPasswordOnNextLogin = false,
            };

            _userService.CreateTenantAdminUser(adminUser);

            var emailCode = _userManager.GenerateEmailConfirmationToken <User, string>(userId);
            var phoneCode = _userManager.GenerateChangePhoneNumberToken(userId, model.PhoneNumber);

            var user = _userManager.FindById(userId);

            user.EmailConfirmationCode = emailCode;
            user.PhoneConfirmationCode = phoneCode;

            _userService.Update(user);

            var task = Task.Run(async() => await _userService.SendEmailConfirmationLinkAsync(userId, user.FullName(), model.Email, emailCode));

            task.Wait();

            return(model.Id);
        }
예제 #11
0
        // take in user model to create a user entity and send to repository
        public async Task <bool> CreateUser(UserCreateRequestModel model)
        {
            var user = new User
            {
                Email    = model.Email,
                Password = model.Password,
                Fullname = model.Fullname,
                JoinedOn = model.JoinedOn
            };
            var createduser = await _userRepository.AddAsync(user);

            return(true);
        }
예제 #12
0
        public async Task <IActionResult> CreatePrincipal(UserCreateRequestModel model)
        {
            var schoolId = await this.userService.GetSchoolIdForUser(UserId);

            model.SchoolId = schoolId;

            if (!ModelState.IsValid)
            {
                return(View(nameof(CreatePrincipal)));
            }

            await this.userService.Create(model);

            return(RedirectToAction("School", "Administrator", new { schoolId = schoolId }));
        }
예제 #13
0
        public async Task <IdentityResult> UpdateUserAsync(UserCreateRequestModel model)
        {
            var user = await UserManager.FindByIdAsync(model.Id);

            var oldRoleId = user.Roles.FirstOrDefault()?.RoleId;

            if (oldRoleId != model.RoleId)
            {
                await UpdateUserRoleAsync(user.Id, oldRoleId, model.RoleId);
            }

            if (model.PasswordHash != model.RetypePassword)
            {
                return(await UpdateUserAsync(user));
            }

            user.FirstName   = model.FirstName;
            user.LastName    = model.LastName;
            user.Email       = model.Email;
            user.PhoneNumber = model.PhoneNumber;
            if (!string.IsNullOrEmpty(model.PasswordHash))
            {
                user.PasswordHash = new PasswordHasher().HashPassword(model.PasswordHash);
            }

            user.TenantId   = model.TenantId;
            user.TenantName = model.TenantName;
            user.CompanyId  = model.CompanyId;
            user.BranchId   = model.BranchId;


            user.IsChangeEmail        = model.ChangeEmailAddress;
            user.AwaitingConfirmEmail = model.AwaitingVerifyEmailAddress;
            user.EmployeeId           = model.EmployeeId;
            user.IsActive             = model.IsActive;
            user.IsShouldChangedPasswordOnNextLogin = model.IsShouldChangedPasswordOnNextLogin;
            user.Created    = model.Created.GetValueOrDefault();
            user.CreatedBy  = model.CreatedBy;
            user.Modified   = model.Modified;
            user.ModifiedBy = model.ModifiedBy;

            if (!user.Email.IsNullOrWhiteSpace() && !user.UserName.IsReservedUsername())
            {
                user.UserName = user.Email;
            }

            return(await UpdateUserAsync(user));
        }
예제 #14
0
        //POST : /api/User/Register
        public async Task <IActionResult> Register(UserCreateRequestModel model)
        {
            var createUSer = new User();

            createUSer.FirstName = model.FirstName;
            createUSer.LastName  = model.LastName;
            createUSer.Email     = model.Email;
            createUSer.IsOnline  = model.IsOnline;
            var emailAlreadyExist = await _service.GetByEmail(createUSer.Email);

            if (emailAlreadyExist != null)
            {
                return(Ok(null));
            }
            return(Ok(await _service.Add(createUSer)));
        }
예제 #15
0
        public async Task <IdentityResult> CreateUserAsync(UserCreateRequestModel model)
        {
            if (model.PasswordHash != model.RetypePassword)
            {
                return(new IdentityResult("Password does not match!"));
            }

            string id = model.Id;

            if (string.IsNullOrWhiteSpace(model.Id))
            {
                id = Guid.NewGuid().ToString();
            }

            var applicationUser = GetReadyUserForCreate(model, id);

            return(await CreateUserAsync(applicationUser));
        }
예제 #16
0
        public async Task <IdentityResult> CreateTenantAdminUserAsync(UserCreateRequestModel model)
        {
            if (model.PasswordHash != model.RetypePassword)
            {
                return(null);
            }

            string id = model.Id;

            if (string.IsNullOrWhiteSpace(model.Id))
            {
                id = Guid.NewGuid().ToString();
            }
            User user = GetReadyUserForCreate(model, id);

            var applicationUser = user;

            return(await CreateTenantAdminUserAsync(applicationUser));
        }
예제 #17
0
        public async Task <User> Create(UserCreateRequestModel model)
        {
            var user = new User
            {
                UserName   = model.UserName,
                Email      = model.Email,
                FirstName  = model.FirstName,
                MiddleName = model.MiddleName,
                LastName   = model.LastName,
                Role       = model.Role,
                SchoolId   = model.SchoolId
            };

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

            if (!result.Succeeded)
            {
                throw new Exception("Unnable to create user!");
            }

            return(user);
        }
예제 #18
0
        private static User GetReadyUserForCreate(UserCreateRequestModel model, string id)
        {
            return(new User()
            {
                Id = id,
                FirstName = model.FirstName,
                LastName = model.LastName,
                Email = model.Email,
                PhoneNumber = model.PhoneNumber,
                UserName = model.UserName,
                PasswordHash = new PasswordHasher().HashPassword(model.PasswordHash),
                SecurityStamp = Guid.NewGuid().ToString(),
                Roles = { new UserRole()
                          {
                              RoleId = model?.RoleId, UserId = id, TenantId = model?.TenantId, CompanyId = model?.CompanyId
                          } },

                EmailConfirmed = model.EmailConfirmed,
                EmailConfirmationCode = model.EmailConfirmationCode,
                PhoneConfirmationCode = model.PhoneNumberConfirmationCode,

                TenantId = model.TenantId,
                TenantName = model.TenantName,
                CompanyId = model.CompanyId,
                BranchId = model.BranchId,


                IsChangeEmail = model.ChangeEmailAddress,
                AwaitingConfirmEmail = model.AwaitingVerifyEmailAddress,
                EmployeeId = model.EmployeeId,
                IsActive = model.IsActive,
                IsShouldChangedPasswordOnNextLogin = model.IsShouldChangedPasswordOnNextLogin,
                Created = DateTime.Now,
                CreatedBy = model.CreatedBy,
                //Modified= model.Modified,
                //ModifiedBy= model.ModifiedBy,
            });
        }
예제 #19
0
 public IActionResult Create(UserCreateRequestModel request)
 {
     return(View(request));
 }
예제 #20
0
        public async Task <IActionResult> CreateUser(UserCreateRequestModel user)
        {
            await _userService.CreateUser(user);

            return(Ok());
        }
예제 #21
0
        public async Task <IHttpActionResult> CreateUser(UserCreateRequestModel model)
        {
            if (string.IsNullOrWhiteSpace(model.Id))
            {
                model.Id = Guid.NewGuid().ToString();
            }
            model.UserName = model.Email;

            if (!string.IsNullOrWhiteSpace(model.UserName))
            {
                ModelState.Remove("model.UserName");
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (_service.IsEmailExist(model.Email))
            {
                return(BadRequest($"{model.Email} email address already exist."));
            }


            if (string.IsNullOrWhiteSpace(model.TenantId))
            {
                model.TenantId   = User.Identity.GetTenantId();
                model.TenantName = User.Identity.GetTenantName();
                model.CompanyId  = User.Identity.GetCompanyId();
            }
            else
            {
                var tenant = await _tenantProvider.GetTenantAsync(model.TenantId);

                var company = await _tenantProvider.GetTenantCompanyAsync(model.TenantId);

                model.TenantName = tenant.TenancyName;
                model.CompanyId  = company?.Id;
            }

            model.CreatedBy      = User.Identity.GetUserId();
            model.IsActive       = !model.SendActivationEmailToUser;
            model.EmailConfirmed = !model.SendActivationEmailToUser;

            var  featureUsers = _featureProvider.GetEditionFeatureValue(model.TenantId, StaticFeature.Users.Name);
            bool isReachedMaximumUsersCount =
                _service.IsReachedMaximumUsersCount(model.TenantId, Convert.ToInt32(featureUsers));

            if (isReachedMaximumUsersCount)
            {
                return(BadRequest("You already have added " + featureUsers + " users. You can not add more user with your current subscription."));
            }

            var identityResult = await _service.CreateUserAsync(model);

            if (model.SendActivationEmailToUser)
            {
                var user = await _service.GetUserAsync(model.Id);

                user.EmailConfirmationCode = await UserManager.GenerateEmailConfirmationTokenAsync(model.Id);

                user.EmailConfirmed = false;
                user.EmailConfirmationCodeExpireTime = DateTime.Now.AddMinutes(30);
                user.PhoneConfirmationCode           = await UserManager.GenerateChangePhoneNumberTokenAsync(model.Id, model.PhoneNumber);

                user.PhoneNumberConfirmed            = false;
                user.PhoneConfirmationCodeExpireTime = DateTime.Now.AddMinutes(30);

                await _service.UpdateUserAsync(user);

                await _service.SendEmailConfirmationLinkAsync(model.Id, model.FullName(), model.Email, user.EmailConfirmationCode);
            }

            return(Ok(identityResult));
        }
예제 #22
0
        public async Task <ActionResult <UserModel> > UpdateUser(
            [FromRoute] Guid?uid, [FromBody] UserCreateRequestModel newUser)
        {
            if (uid == null)
            {
                return(NotFound());
            }

            var user = await database.Get <UserModel>(uid.Value);

            // Update Username
            if (user.UserName != newUser.UserName && !newUser.UserName.IsNullOrEmpty())
            {
                if (await database.GetUserByUserName(user.UserName) != null)
                {
                    return(BadRequest(new ErrorModel(400, "username already taken")));
                }

                user.UserName = newUser.UserName;
            }

            // Update Displayname
            if (!newUser.DisplayName.IsNullOrEmpty())
            {
                user.DisplayName = newUser.DisplayName;
            }

            // Update Email Address
            if (newUser.EmailAddress != null && newUser.EmailAddress != user.EmailAddress)
            {
                user.EmailAddress = newUser.EmailAddress;
                if (user.EmailAddress.Length > 0)
                {
                    await SendMailConfirm(user);
                }
                else
                {
                    user.EmailConfirmStatus = EmailConfirmStatus.UNSET;
                }
            }

            // Update Username
            if (newUser.Description != null)
            {
                user.Description = newUser.Description;
            }

            // Update Admin Status
            if (newUser.IsAdmin != null)
            {
                if (!authClaims.User.IsAdmin.Equals(true))
                {
                    return(BadRequest(new ErrorModel(400, "you need to be admin to change the admin state of a user")));
                }

                user.IsAdmin = newUser.IsAdmin.Equals(true);
            }

            // Update Password
            if (!newUser.Password.IsNullOrEmpty())
            {
                if (!newUser.IsValidPassword())
                {
                    return(BadRequest(new ErrorModel(400, "invalid new password")));
                }

                if (newUser.OldPassword.IsNullOrEmpty())
                {
                    return(BadRequest(new ErrorModel(400, "old password is required")));
                }

                if (!hasher.Validate(newUser.OldPassword, user.PasswordHash))
                {
                    return(BadRequest(new ErrorModel(400, "invalid old password")));
                }

                user.PasswordHash = hasher.Create(newUser.Password);
            }

            await database.Update(user);

            return(Ok(user));
        }
예제 #23
0
 public Task <ActionResult <UserModel> > UpdateSelfUser([FromBody] UserCreateRequestModel newUser) =>
 UpdateUser(authClaims.User?.Uid, newUser);