public UserServiceTests()
 {
     this.service = new UserService();
     service.Add(new User { Login = "******" }
         );
     service.Add(new User { Login = "******" }
         );
 }
示例#2
0
 public UserServiceTests()
 {
     this.service = new UserService();
     service.Add(new User { Name = "John" }
         );
     service.Add(new User { Name = "Mike" }
         );
 }
        public IActionResult RegisterUser(UserViewmodel userViewModel)
        {
            var users = _userService.GetAll().ToArray();

            if (userViewModel.Password != userViewModel.ConfirmPassword)
            {
                return(BadRequest("Lösenorden matchar inte."));
            }
            bool emailExist = _authControllerServices.CheckMailAddress(users, userViewModel);

            if (emailExist == false)
            {
                var user = Mapper.ViewModelToModelMapping.UserViewModelToUser(userViewModel);
                user.Password = _hashPassword.Hash(userViewModel.Password);
                _userService.Add(user);
                return(Ok("Användaren har sparats, du skickas till login sidan inom 5 sekunder!"));
            }
            return(BadRequest("Mailadressen är redan registerad."));
        }
示例#4
0
        public IDataResult <User> Register(UserForRegisterDto userForRegisterDto, string password)
        {
            byte[] passwordHash;
            byte[] passwordSalt;

            HashingHelper.CreatePasswordHash(password, out passwordHash, out passwordSalt);
            var user = new User
            {
                Email        = userForRegisterDto.Email,
                FirstName    = userForRegisterDto.FirstName,
                LastName     = userForRegisterDto.LastName,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                Status       = true
            };

            _userService.Add(user);
            return(new SuccessDataResult <User>(user, Messages.UserRegistered));
        }
示例#5
0
        public ActionResult Contact(GuestUserVM guestUser)
        {
            if (ModelState.IsValid)
            {
                User user;
                bool result = false;
                try
                {
                    user = SendMessageToCompany(guestUser);

                    result = _userService.Add(user);
                    guestUser.GuestUserID = user.ID;

                    Company currentCompany = _companyService.GetCompanyByName("Transivo");

                    Message currentMessage = new Message();
                    currentMessage.Detail  = guestUser.Message;
                    currentMessage.User    = _userService.Get(guestUser.GuestUserID);
                    currentMessage.Company = currentCompany;
                    bool resultMessage = _messageService.Add(currentMessage);

                    if (result && resultMessage)
                    {
                        ViewBag.result = "Mesajınız Başarılı Bir Şekilde İletildi Size En Kısa Zamanda Dönüş Yapacağız";
                        ViewBag.isSend = "Gönderildi";
                    }
                    else
                    {
                        ViewBag.result = "Bir Hata Oluştu. İlgili Alanların Doğruluğunu Kontrol Ediniz.";
                    }
                }
                catch (Exception)
                {
                    ViewBag.result = "Bir Hata Oluştu";
                }
                return(View());
            }
            else
            {
                return(View());
            }
        }
        public ActionResult Index()
        {
            IList <UserDTO> userList = IUser.GetList().ToList();

            if (!userList.Any())
            {
                IUser.Add(new UserDTO {
                    UserName = "******"
                });
            }
            else
            {
                IUser.Renew(userList.First());
            }
            string randomName = RandomData.GetRandomName();

            return(View(new HomeModel {
                UserList = userList
            }));
        }
示例#7
0
        public JsonResult Add(UserViewModel model)
        {
            if (ModelState.IsValid)
            {
                //if password null set defualt value
                if (string.IsNullOrEmpty(model.Password))
                {
                    var defualtPassword = _systemSettingService.GetById((int)SystemSettingEnum.DefualtPassword).Value;
                    model.Password = defualtPassword;
                }
                var EntityMapped = Mapper.Map <User>(model);
                EntityMapped.CreatedDate = DateTime.Now;

                _UserService.Add(EntityMapped);
                return(Json(new { data = model, success = true }, JsonRequestBehavior.AllowGet));
            }
            var errors = ModelState.GetDistinctModelErrors();

            return(Json(new { data = model, success = false, ErrorsList = errors }, JsonRequestBehavior.AllowGet));
        }
示例#8
0
		public virtual ActionResult Create(UserModel model)
		{
			if (string.IsNullOrWhiteSpace(model.Authentication.NewPassword))
				ModelState.AddModelError("NewPassword", Validation.EmplyPassword);

			if (!ModelState.IsValid) return View();

			try
			{
				_userService.Add(model);

				return RedirectToAction(MVC.User.Index(model.RoleType));
			}
			catch (DublicateLoginException)
			{
				ModelState.AddModelError("Authentication.Login", Validation.LoginExists);

				return View();
			}
		}
示例#9
0
        public ActionResult AddEdit(UserDto model)
        {
            if (!ModelState.IsValid)
            {
                model.UserTypes = _userTypeService.GetAll();
                return(View(model));
            }


            if (model.Id > 0)
            {
                _userService.Update(model);
            }
            else
            {
                _userService.Add(model);
            }

            return(RedirectToAction("Index", "User"));
        }
示例#10
0
        public IDataResult <User> Register(UserForRegisterDto userForRegisterDto, string password)
        {
            byte[] passwordHash, passwordSalt;
            HashingHelper.CreatePasswordHash(password, out passwordHash, out passwordSalt);
            var user = new User
            {
                Email        = userForRegisterDto.Email,
                FirstName    = userForRegisterDto.FirstName,
                LastName     = userForRegisterDto.LastName,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                Status       = true
            };

            _userService.Add(user);
            _userOperationClaimService.Add(new UserOperationClaim {
                UserId = user.Id, OperationClaimId = 2
            });
            return(new SuccessDataResult <User>(user, "Basarili"));
        }
示例#11
0
        public async Task <IActionResult> AddUser([FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Ingrese un usuario correcto"));
            }
            else
            {
                var response = await _userService.Add(user);

                if (!response.status)
                {
                    return(NotFound(response.message));
                }
                else
                {
                    return(Ok(response.data));
                }
            }
        }
示例#12
0
        public IDataResult <User> Register(UserForRegisterDto userForRegisterDto, string password)
        {
            byte[] passwordHash, passwordSalt;
            HashingHelper.CreatePasswordHash(password, out passwordHash, out passwordSalt); //şifre hashlaniyor
            var user = new User                                                             //biligiler ile yeni kullanıcı oluşuyor
            {
                Email            = userForRegisterDto.Email,
                FirstName        = userForRegisterDto.FirstName,
                LastName         = userForRegisterDto.LastName,
                PasswordHash     = passwordHash,
                PasswordSalt     = passwordSalt,
                UserName         = userForRegisterDto.UserName,
                TCIdentityNumber = userForRegisterDto.TCIdentityNumber,
                PhoneNumber      = userForRegisterDto.PhoneNumber,
                Address          = userForRegisterDto.Address
            };

            _userService.Add(user);//user tablosuna ekleniyor
            return(new SuccessDataResult <User>(user, "Kayıt oldu"));
        }
示例#13
0
        public static void SeedData(IUserService userService, IRoleService roleService)
        {
            List <User> users = userService.GetByRoleName(ConstRoles.ADMIN);

            //Admin rolüne sahip kullanıcı yoksa
            if (users?.Count <= 0)
            {
                User user = new User();
                user.Name      = ConstUser.NAME;
                user.Surname   = ConstUser.SURNAME;
                user.Username  = ConstUser.USERNAME;
                user.Password  = ConstUser.PASSWORD;
                user.UserRoles = new List <UserRole>();
                user.UserRoles.Add(new UserRole {
                    RoleId = roleService.GetByName(ConstRoles.ADMIN).Id
                });

                userService.Add(user);;
            }
        }
示例#14
0
        public async Task <IActionResult> Add(UserAdd param)
        {
            if (ModelState.IsValid)
            {
                var temp = await service.Add(param, Url);

                if (temp.Success)
                {
                    return(Ok(mapper.Map <UserResource>(temp.Resource)));
                }
                else
                {
                    return(BadRequest(new { Message = temp.Message }));
                }
            }
            else
            {
                return(BadRequest(new  { Message = "Invalid parameters supplied" }));
            }
        }
示例#15
0
        public Task <IActionResult> Add([FromBody] RegisterUserModel userModel)
        {
            IActionResult result;

            try
            {
                _service.Add(userModel);
                result = Ok(new ResultViewModel {
                    Success = true, Message = "Usuário cadastrado com sucesso"
                });
            }
            catch (Exception ex)
            {
                result = BadRequest(new ResultViewModel {
                    Success = false, Message = ex.Message, Docs = ex
                });
            }

            return(GetResult(result));
        }
示例#16
0
        public async Task <IDataResult <UserDetailsDto> > UserRegister(UserForRegisterDto userForRegisterDto, string password)
        {
            var user = new User()
            {
                Password = CryptoHelper.HashPassword(password),
                Email    = userForRegisterDto.Email,
            };

            user.UserOperationClaims = SetUserClaims(user);
            var addResult = await _userService.Add(user);

            if (addResult.Success)
            {
                var result = await _userService.GetUserById(user.Id);

                return(new SuccessDataResult <UserDetailsDto>(result.Data, Messages.RegisterSucessfull));
            }

            return(new ErrorDataResult <UserDetailsDto>(Messages.RegisterFailed));
        }
示例#17
0
 public ActionResult <User> AddUser(User user)
 {
     try{
         IQueryable <User> query = _userService.SelectAll();
         if (query.Count() != 0)
         {
             user.Uid = query.ToList().First().Uid + 1;
         }
         else
         {
             user.Uid = 000000;
         }
         _userService.Add(user);
     }
     catch (Exception e)
     {
         return(BadRequest(e.InnerException.Message));
     }
     return(user);
 }
示例#18
0
        public IDataResult <User> Register(UserForRegisterDTO userForRegisterDto, string password)
        {
            byte[] passwordHash, passwordSalt;
            HashingHelper.CreatePasswordHash(password, out passwordHash, out passwordSalt);
            var user = new User
            {
                Email        = userForRegisterDto.Email,
                FirstName    = userForRegisterDto.FirstName,
                LastName     = userForRegisterDto.LastName,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                UserImage    = userForRegisterDto.UserImage,
                Status       = true,
                //phone number sonradan eklendi
                PhoneNumber = userForRegisterDto.PhoneNumber
            };

            _userService.Add(user);
            return(new SuccessDataResult <User>(user, "Kayıt oldu"));
        }
示例#19
0
 public async Task <IActionResult> OnPost()
 {
     if (!ModelState.IsValid)
     {
         return(Page());
     }
     _User.Pwd      = Input.Password;
     _User.UserName = Input.UserName;
     if (!await _userService.Add(_User))
     {
         retype = true;
         return(Page());
     }
     else
     {
         retype = false;
         Ok     = true;
     }
     return(Page());
 }
        public async Task <IActionResult> UserAdd([FromBody] UserAddRequest request)
        {
            try
            {
                var result = await UserService.Add(request);

                if (result.Status)
                {
                    return(Ok(result));
                }

                return(BadRequest(result));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, ex.Message);

                return(BadRequest(ex.Message));
            }
        }
示例#21
0
        //burada henüz validation yapılmamış
        public IDataResult <User> Register(UserForRegisterDto userForRegisterDto, string password)//+password
        {
            byte[] passwordHash, passwordSalt;
            HashingHelper.CreatePasswordHash(password, out passwordHash, out passwordSalt);//kullanıcı şifresi tuzlanır(yorumlanır) ve şifrelenir

            //UserForRegisterDtokarşıdan aldığımız veri, burada ise kullanıcı nesnesi oluşturuluyor

            var user = new User
            {
                Email        = userForRegisterDto.Email,
                FirstName    = userForRegisterDto.FirstName,
                LastName     = userForRegisterDto.LastName,
                PasswordHash = passwordHash, //
                PasswordSalt = passwordSalt, //
                Status       = true
            };

            _userService.Add(user);
            return(new SuccessDataResult <User>(user, "Kayıt edildi"));
        }
示例#22
0
        public JsonResult Add(UserViewModel usrVM)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new { code = OperationResultType.ParamError, message = base.ParseModelStateErrorMessage(ModelState) }));
            }

            var usr = OOMapper.Map <UserViewModel, User>(usrVM);

            usr.Creator    = HttpContext.Session.GetUserId();
            usr.CreateTime = DateTime.Now;

            OperationResult result = _userSrv.Add(usr);

            if (result.ResultType != OperationResultType.Success)
            {
                return(Json(new { code = result.ResultType, message = result.Message }));
            }
            return(Json(new { code = OperationResultType.Success, message = "添加成功" }));
        }
示例#23
0
        public async Task <IActionResult> CreateAccount([FromBody] UserResource accountResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            User user = _mapper.Map <UserResource, User>(accountResource);

            try
            {
                _userService.Add(user);
                _userService.Save();
                return(Created(nameof(CreateAccount), _mapper.Map <User, UserResourceResult>(user)));
            }
            catch
            {
                return(BadRequest("Could not Create the User account"));
            }
        }
示例#24
0
        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="userDto"></param>
        /// <param name="saveState"></param>
        /// <param name="array"></param>
        public void HttpPostSave(UserDto userDto, SaveState saveState, int[] array)
        {
            switch (saveState.OperationState)
            {
            case OperationState.Add:
                var salt = Encrypt.GetCheckCode(5);
                userDto.Salt     = salt;
                userDto.Password = DesEncrypt.Encrypt(userDto.Password, salt);    //盐值加密
                _userService.Add(userDto, array);
                break;

            case OperationState.Update:
                userDto.Password = DesEncrypt.Encrypt(userDto.Password, userDto.Salt);     //盐值加密
                _userService.Update(userDto, array);
                break;

            default:
                break;
            }
        }
示例#25
0
        public IActionResult Post(CACI.DAL.Models.User _obj)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    return(Ok(_service.Add(_obj)));
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to post User: {ex}", ex);
            }

            return(BadRequest("Failed to post User"));
        }
        public ActionResult Put(UserModel request)
        {
            if (ModelState.IsValid)
            {
                _userService.Add(new Users
                {
                    UserId   = request.UserId,
                    Username = request.Username,
                    Email    = request.Email,
                    Password = request.Password,
                    Status   = request.Status
                });

                return(Ok(new ResponseModel <Users> {
                    Status = true, Message = "New user inserted.", Object = null
                }));
            }

            return(ValidationProblem());
        }
示例#27
0
        public User Register(string login,
                             string password,
                             string firstName,
                             string lastName,
                             string surName,
                             Genders gender, DateTime?birthDate,
                             string snils,
                             string email,
                             string phone,
                             string registrationAddress,
                             string factAddress,
                             string otherPhones,
                             IEnumerable <Role> roles)
        {
            var person = _personService.Add(firstName, lastName, surName, gender, birthDate, snils, email, phone, registrationAddress, factAddress, otherPhones);

            var user = _userService.Add(person.Id, login, password, roles);

            return(user);
        }
示例#28
0
        /// <summary>
        /// Registers the user. Generates hashed and salted versions of user's password and register the user.
        /// </summary>
        /// <param name="userForRegisterDto"></param>
        /// <param name="password"></param>
        /// <returns>Return success with the registered user.</returns>
        public IDataResult <User> Register(UserForRegisterDto userForRegisterDto, string password)
        {
            byte[] passwordHash, passwordSalt;
            HashingHelper.CreatePasswordHash(password, out passwordHash, out passwordSalt);

            var user = new User
            {
                UserName = userForRegisterDto.UserName,
                Email    = userForRegisterDto.Email,
                //FirstName = userForRegisterDto.FirstName,
                //LastName = userForRegisterDto.LastName,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                Status       = true,
                JoinDate     = DateTime.Now
            };

            _userService.Add(user);
            return(new SuccessDataResult <User>(user, Messages.Authentication.UserRegistered));
        }
示例#29
0
        public string Create(UserInfo userInfo)
        {
            if (!ModelState.IsValid)
            {
                ErrorModel modelIsInvalidError = new ErrorModel("Error", new List <string>(), new List <string>());

                foreach (var item in ModelState)
                {
                    foreach (var error in item.Value.Errors)
                    {
                        modelIsInvalidError.ErrorKeysList.Add(item.Key);
                        modelIsInvalidError.ErrorMessagesList.Add(error.ErrorMessage);
                    }
                }

                return(modelIsInvalidError.ToJson());
            }

            userInfo.Id = 1; //temporary user's id for testing DB.

            try
            {
                _userService.Add(userInfo);
                db.Commit();
            }
            catch (Exception)
            {
                var errorAddingtoDB = new ErrorModel("Error", new List <string>()
                {
                    "Some troubles with DB happened, try to add your info later."
                }, new List <string>()
                {
                    "DataBaseError"
                });
                return(errorAddingtoDB.ToJson());
            }

            var succesResult = new JsonNetResult(new { header = "Succes", message = "Resources added succesfully" });

            return(succesResult.ToJson());
        }
示例#30
0
        public ActionResult <AuthDataDto> Register([FromBody] RegisterDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!_userService.IsEmailUniq(model.Email))
            {
                return(BadRequestCustom("Email already exists"));
            }

            if (!_userService.IsUsernameUniq(model.Username))
            {
                return(BadRequestCustom("User name already exists"));
            }

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

            var user = new User
            {
                UserName   = model.Username,
                Email      = model.Email,
                Password   = _authService.HashPassword(model.Password),
                Active     = false,
                ActiveCode = activeCode
            };

            _userService.Add(user);

            try
            {
                _emailService.Send(BuildEmailMessage(model.Username, model.Email, activeCode, "N"));
            }
            catch (Exception ex)
            {
                //Log somewhere
            }

            return(_authService.GetAuthData(user));
        }
        public virtual ActionResult SaveUser(UserVM vm)
        {
            if (!User.IsAdministrator())
            {
                throw new ApplicationException(AppConstants.ERR_ACCESS_DENIED);
            }
            var currentUser = this.GetCurrentUser(_userService);
            var dto         = _mapper.Map <UserVM, UserDto>(vm);

            if (vm.RoleSelection == null)
            {
                vm.RoleSelection = new List <RoleSelection>();
            }
            dto.Roles = vm.RoleSelection.Where(x => x.Selected).Select(x => x.Role).ToList();
            try
            {
                if (vm.Id > 0)
                {
                    _userService.Update(dto, currentUser.Id);
                }
                else
                {
                    dto = _userService.Add(dto, vm.InitialPassword, currentUser.Id);
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null &&
                    ex.InnerException.Message.ToLower().Contains("cannot insert duplicate key"))
                {
                    return(this.FailureResult(
                               String.Format(
                                   "{0} {1} [{2}] has already been defined and cannot be added a second time.\nPlease find and update the existing user if changes need to be made.",
                                   dto.FirstName, dto.LastName, dto.Username)
                               ));
                }
                // _logger.Error("error during AdministrationController.SaveUser", ex);
                return(this.FailureResult(ex.Message));
            }
            return(this.SuccessResult());
        }
示例#32
0
        public ActionResult Add([FromBody] UserModel userModel)
        {
            if (_userService.UserExists(userModel.UserName))
            {
                ModelState.AddModelError("UserName", "Username already exists");
            }

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

            var userToCreate = new User
            {
                Name = userModel.UserName
            };

            var createdUser = _userService.Add(userToCreate, userModel.Password);

            return(StatusCode(201));
        }
示例#33
0
        public UserModule(IUserService userService, IMappingEngine mappingEngine)
            : base("data/users", mappingEngine, UserRole.Admin)
        {
            Get["/"] = args =>
            {
                var entities = userService.Search(
                    Context.RequestedPage(),
                    null,
                    Context.SortCriteria<User>(),
                    Context.SearchTerms<User>());

                return MapToResultList<SystemUser, Encore.Web.Models.User>(entities);
            };

            Get["/{id}"] = args =>
            {
                var entity = userService.Get(new Guid(args.id));

                if (entity == null)
                {
                    return Negotiate.WithStatusCode(HttpStatusCode.NotFound);
                }

                return MapTo<Encore.Web.Models.User>(entity);
            };

            Put["/{id}"] = args =>
            {
                var model = this.BindAndValidate<Models.User>();

                if (!ModelValidationResult.IsValid)
                {
                    return RespondWithValidationFailure(ModelValidationResult);
                }

                var authorizedUser = Context.GetAuthorizedUser();

                var updateEntity = MapTo<SystemUser>(model);
                var updateId = new Guid(args.id);
                var updatedUser = userService.UpdateUser(authorizedUser.Id, updateId, updateEntity);

                if (authorizedUser.Id == updateId)
                {
                    Context.SetupSession(updatedUser);
                }

                return MapTo<User>(updatedUser);
            };

            Post["/"] = args =>
            {
                var model = this.BindAndValidate<Models.User>();

                if (!ModelValidationResult.IsValid)
                {
                    return RespondWithValidationFailure(ModelValidationResult);
                }

                var addEntity = MapTo<SystemUser>(model);
                var user = userService.Add(addEntity);

                if (user == null)
                {
                    return HttpStatusCode.Unauthorized;
                }

                return MapTo<User>(user);
            };

            Delete["/{id}"] = args =>
            {
                var authorizedUser = Context.GetAuthorizedUser();
                var deleteId = new Guid(args.id);

                return userService.DeleteUser(authorizedUser.Id, deleteId);
            };
        }