private static void AddAdminUserIfNoUserFound(IUserRepository userRepository) { if (!userRepository.HasAdminUser) { userRepository.Add(new User { Name = "spiel", Password = "******", IsAdmin = true }); } }
protected override void CreateInitialData() { _userRepository = Locator.GetService<IUserRepository>(); var passwordSalt = PasswordMethods.CreateSalt(); var users = new[] { new User { Login = "******", Email = "*****@*****.**", CreatedDate = DateTime.Now, PasswordSalt = passwordSalt, Password = PasswordMethods.CreatePasswordHash("testtest", passwordSalt), IsActivated = true, IsLockedOut = false, LastLockedOutDate = null, LastLoginDate = null, }, new User { Login = "******", Email = "*****@*****.**", CreatedDate = DateTime.Now, PasswordSalt = passwordSalt, Password = PasswordMethods.CreatePasswordHash("testtest", passwordSalt), IsActivated = true, IsLockedOut = false, LastLockedOutDate = null, LastLoginDate = null, } }; foreach (var obj in users) { _userRepository.Add(obj); } _roleRepository = Locator.GetService<IRoleRepository>(); var roles = new[] { new Role { RoleName = "admin" }, new Role { RoleName = "user" } }; foreach (var obj in roles) { _roleRepository.Add(obj); } }
public static void AddUserAndCopyAccess(IUserRepository userRepository, INetworkRepository networkRepository, INetworkGuestRepository networkGuestRepository, string username, string password, string referenceUsername) { var user = User.Create(string.Join(":", "internal", username)); user.Secret = Web.Persistence.Helpers.Secrets.BCryptSecret.FromPassword(password); userRepository.Add(user); var referenceUser = userRepository.Get(string.Join(":", "internal", referenceUsername)); var networks = networkRepository.Get(referenceUser); foreach (var network in networks) { networkGuestRepository.Add(network, user); } }
public LoginModule(IUserRepository userRepository) { _user = userRepository; Post["/login/token"] = x => { if (string.IsNullOrWhiteSpace(Request.Form.token)) return View["Login/Error", new { Title = "Login Error", Message = "Bad response from login provider - could not find login token." }]; var response = new WebClient().DownloadString(string.Format("https://rpxnow.com/api/v2/auth_info?apiKey={0}&token={1}",apikey, Request.Form.token)); if (string.IsNullOrWhiteSpace(response)) return View["Login/Error", new { Title = "Login Error", Message = "Bad response from login provider - could not find user." }]; var j = JsonConvert.DeserializeObject<dynamic>(response); if (j.stat.ToString() != "ok") return View["Login/Error", new { Title = "Login Error", Message = "Bad response from login provider." }]; var userIdentity = j.profile.identifier.ToString(); var username = j.profile.preferredUsername.ToString(); string email = string.Empty; if (j.profile.email != null) email = j.profile.email.ToString(); var user = _user.GetUserFromUserIdentity(userIdentity); if (user == null) { var u = new User { Id = Guid.NewGuid(), Identity = userIdentity, UserName = (!string.IsNullOrEmpty(username)) ? username : "******" + _user.GetAll().Count(), Email = (!string.IsNullOrEmpty(email)) ? email : "*****@*****.**", Github = (!string.IsNullOrEmpty(username)) ? username : "", IsActive = true, }; if (!_user.GetAll().Any()) _user.AddRole(u, "Admin"); if (j.profile.photo != null) u.AvatarUrl = j.profile.photo.ToString(); _user.Add(u); return this.LoginAndRedirect(u.Id, DateTime.Now.AddDays(1), "/profile/edit"); } return ModuleExtensions.Login(this, user.Id, DateTime.Now.AddDays(1), "/"); }; Get["/logout/"] = parameters => this.LogoutAndRedirect("/"); }
public async Task <User> AddUser(User user) { var addedEntity = await _userRepository.Add(UserMapper.Map(user)); return(UserMapper.Map(addedEntity)); }
public void Save(User user) { //Saving data into database db.Add(user); db.Save(user); }
public void CreateUser(User user) { userRepository.Add(user); Save(); }
public IActionResult Post(User item) { _repository.Add(item); return(Ok("Record Added")); }
public User Adicionar(User user) { _userRepository.Add(user); return(user); }
public void Add() { Console.WriteLine("UserService Invoke Add Method"); userRepository.Add(); sendEmailService.SendEmail(); }
public AdminModule(IdeastrikeContext dbContext, Settings settings, IUserRepository users, IIdeaRepository ideas, IActivityRepository activities) : base("/admin") { this.RequiresAuthentication(); this.RequiresValidatedClaims(c => c.Contains("admin")); _settings = settings; _users = users; _ideas = ideas; _activities = activities; Get["/"] = _ => { var m = Context.Model(string.Format("Admin - {0}", (string)_settings.SiteTitle)); m.Name = _settings.Name; m.WelcomeMessage = _settings.WelcomeMessage; m.HomePage = _settings.HomePage; m.GAnalyticsKey = _settings.GAnalyticsKey; return View["Admin/Index", m]; }; Get["/users"] = _ => { var m = Context.Model(string.Format("Admin - {0}", (string)_settings.SiteTitle)); m.Name = _settings.Name; m.WelcomeMessage = _settings.WelcomeMessage; m.HomePage = _settings.HomePage; m.GAnalyticsKey = _settings.GAnalyticsKey; m.Users = users.GetAll(); return View["Admin/Users", m]; }; Get["/moderation"] = _ => { var m = Context.Model(string.Format("Admin - {0}", (string)_settings.SiteTitle)); m.Name = _settings.Name; m.WelcomeMessage = _settings.WelcomeMessage; m.HomePage = _settings.HomePage; m.GAnalyticsKey = _settings.GAnalyticsKey; return View["Admin/Moderation", m]; }; Get["/settings"] = _ => { var m = Context.Model(string.Format("Admin - {0}", (string)_settings.SiteTitle)); m.Name = _settings.Name; m.SiteTitle = _settings.SiteTitle; m.WelcomeMessage = _settings.WelcomeMessage; m.HomePage = _settings.HomePage; m.GAnalyticsKey = _settings.GAnalyticsKey; m.MaxThumbnailWidth = _settings.MaxThumbnailWidth; return View["Admin/Settings", m]; }; Post["/settings"] = _ => { _settings.WelcomeMessage = Request.Form.welcomemessage; _settings.SiteTitle = Request.Form.sitetitle; _settings.Name = Request.Form.yourname; _settings.HomePage = Request.Form.homepage; _settings.GAnalyticsKey = Request.Form.analyticskey; _settings.MaxThumbnailWidth = Request.Form.maxthumbnailwidth; return Response.AsRedirect("/admin/settings"); }; Get["/search"] = _ => ""; Get["/forums"] = _ => ""; Get["/forum/{forumId}"] = _ => ""; Get["/uservoice"] = _ => View["Admin/Uservoice", Context.Model("Admin")]; Post["/uservoice"] = _ => { var client = new WebClient(); var suggestions = GetSuggestions(client, Request.Form.channel, Request.Form.forumid, Request.Form.apikey, Request.Form.trusted); foreach (var s in suggestions) { string title = s.title; //If the idea exists, skip it if (ideas.FindBy(i => i.Title == title).Any()) continue; string date = s.created_at; var idea = new Idea { Title = title, Description = s.text, Time = DateTime.Parse(date.Substring(0, date.Length - 5)), }; string status = string.Empty; switch ((string)s.state) { case "approved": status = "Active"; break; case "closed" : if (s.status.key == "completed") status = "Completed"; else status = "Declined"; break; default: status = "New"; break; } idea.Status = status; //Get the author, or create string name = s.creator.name; var existing = users.FindBy(u => u.UserName == name).FirstOrDefault(); if (existing != null) idea.Author = existing; else { idea.Author = NewUser(s.creator); users.Add(idea.Author); } ideas.Add(idea); //Process all comments var comments = GetComments(client, (string)s.id, Request.Form.channel, Request.Form.forumid, Request.Form.apikey, Request.Form.trusted); List<Activity> ideaComments = new List<Activity>(); foreach (var c in comments) { string commentdate = c.created_at; var comment = new Comment { Time = DateTime.Parse(commentdate), Text = c.text }; string commentname = c.creator.name; existing = users.FindBy(u => u.UserName == commentname).FirstOrDefault(); if (existing != null) comment.User = existing; else { comment.User = NewUser(c.creator); users.Add(comment.User); } activities.Add(idea.Id, comment); } //Process all votes var votes = GetVotes(client, (string)s.id, Request.Form.channel, Request.Form.forumid, Request.Form.apikey, Request.Form.trusted); foreach (var v in votes) { string votername = v.user.name; string votesfor = v.votes_for; int vote; if (Int32.TryParse(votesfor, out vote)) { existing = users.FindBy(u => u.UserName == votername).FirstOrDefault(); if (existing != null) ideas.Vote(idea.Id, existing.Id, vote); else { var author = NewUser(v.user); users.Add(author); ideas.Vote(idea.Id, author.Id, vote); } } } } return Response.AsRedirect("/admin"); }; }
public IActionResult Register([FromBody] User user) { _userRepository.Add(user); return(Ok("Success")); }
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Username, model.Password, model.Email); if (createStatus == MembershipCreateStatus.Success) { var User = new User { FirstName = model.FirstName, MiddleName = model.MiddleName, LastName = model.LastName, StaffType = model.Title, LicenseNumber = model.LicenseNumber, PhoneNumber = model.PhoneNumber, Address = new Address { Street1 = model.Street1, Street2 = model.Street2, City = model.City, Region = model.Region, Country = model.Country, IsActive = true }, Username = model.Username, Password = model.Password, EmailAddress = model.Email, LastActivity = DateTime.Now, LastLogin = DateTime.Now, DateCreated = DateTime.Now, PasswordQuestion = String.Empty, PasswordAnswer = String.Empty, LastPasswordChange = DateTime.MinValue, ApplicationName = "/", IpAddress = Request.ServerVariables["REMOTE_ADDR"], IsActive = true, IsApproved = false, IsLockedOut = false, IsOnline = true, FailedPasswordAttemptCount = 0 }; _userRepository.Add(User); //FormsService.SignIn(User.Username, false); if (Request.IsAjaxRequest()) { return(Json(new { success = true })); } return(RedirectToAction("Index", "User")); } else { ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus)); } } // If we got this far, something failed, redisplay form ViewBag.PasswordLength = MembershipService.MinPasswordLength; return(View(model)); }
public void Create(Customer customer) { _userRepository.Add(customer); }
public async Task <User> Register(RegisterRequest registerRequest) { var hashedPassword = generateEncryptedPasswordFromRegisterRequest(registerRequest); if (hashedPassword == null) { return(null); } var users = await _userRepository.GetAll(); if (users.Where(p => p.UserName == registerRequest.Username || p.Email == registerRequest.Email ).Count() != 0) { return(null); } var user = new User() { Name = registerRequest.Name, UserName = registerRequest.Username, Email = registerRequest.Email, Password = hashedPassword, Balance = new UserBalance() { CoinsPool = _userRegisterInitialValues.InitialCoins, StarsPool = _userRegisterInitialValues.InitialStars }, Experience = new UserExperience() { Experience = 0 }, Statistics = new UserStatistics() { Matches = 120, MatchesWins = 40, Tournaments = 8, TournamentsWins = 2, PocketedBalls = 250 }, Friends = new UserFriends() { Friends = new List <User>(), FriendsIds = new List <string>() }, Location = new UserLocation() { Country = new Country() { Code = 55, Name = "Brazil" }, Hood = "Fazendinha", City = "Curitiba" } }; _userRepository.Add(user); await _unitOfWork.Commit(); return(user); }
public void Add(User entity) { _userService.Add(entity); }
public ActionResult Order([Bind(Include = "FirstName,LastName,Phone,Email,Street,HouseNumber,ApartmentNumber,NamePaymentType,OrderDeliveryTime,Comment")] UserDelivery userAddress) { List <PaymentType> payments = paymentTypeRepository.PaymentTypes.ToList(); ViewBag.PaymentTypes = new SelectList(payments, "Id", "NamePaymentType", payments.First(x => x.Id == int.Parse(userAddress.NamePaymentType))); if (!(Session["order"] is Order order) || order.OrderLines.Count == 0) { ModelState.AddModelError("", "Корзина заказов пуста"); return(View(userAddress)); } userAddress.OrderDeliveryTime ??= DateTime.Now.AddHours(1); if (DateTime.Now.AddMinutes(59).CompareTo(userAddress.OrderDeliveryTime) > 0) { ModelState.AddModelError("OrderDeliveryTime", "Время для доставки мин. 1 час"); return(View(userAddress)); } if (!ModelState.IsValid) { return(View(userAddress)); } //----------------------------------- Order newOrder = null; User user = userRepository.Users.FirstOrDefault(u => u.Phone == userAddress.Phone); Address address = addressRepository.Addresses.FirstOrDefault(a => a.Street == userAddress.Street && a.HouseNumber == userAddress.HouseNumber && a.ApartmentNumber == userAddress.ApartmentNumber); Address newAddress = null; if (address == null) { newAddress = new Address { Street = userAddress.Street, HouseNumber = userAddress.HouseNumber, ApartmentNumber = userAddress.ApartmentNumber }; } if (user == null) { user = new User { FirstName = userAddress.FirstName, LastName = userAddress.LastName, Phone = userAddress.Phone, Email = userAddress.Email }; if (address == null) { user.Addresses.Add(newAddress); newOrder = new Order { User = user, Address = newAddress }; } else { address.Users.Add(user); addressRepository.Update(address); newOrder = new Order { UserId = user.Id, AddressId = address.Id }; } } else { if (address == null) { user.Addresses.Add(newAddress); userRepository.Update(user); newOrder = new Order { UserId = user.Id, AddressId = newAddress.Id }; } else { bool isAddressUser = false; foreach (var item in user.Addresses) { if (item.Street == userAddress.Street && item.HouseNumber == userAddress.HouseNumber && item.ApartmentNumber == userAddress.ApartmentNumber) { isAddressUser = true; break; } } if (!isAddressUser) { userRepository.Add(user, address); } newOrder = new Order { UserId = user.Id, AddressId = address.Id }; } } newOrder.Comment = userAddress.Comment; newOrder.OrderDate = DateTime.Now; newOrder.OrderDeliveryTime = (DateTime)userAddress.OrderDeliveryTime; newOrder.PaymentTypeId = int.Parse(userAddress.NamePaymentType); orderRepository.Add(newOrder); foreach (var item in order.OrderLines) { OrderLine orderLine = new OrderLine { DishId = item.Dish.Id, Quantity = item.Quantity, OrderId = newOrder.Id }; orderLineRepository.Add(orderLine); } Session["order"] = null; order = orderRepository.Orders.First(o => o.Id == newOrder.Id); return(View("OrderAccepted", order)); }
public void Init() { var serviceLocator = new RepositoryServiceLocator(); _postRepository = serviceLocator.Locate<IPostRepository>(); _userRepository = serviceLocator.Locate<IUserRepository>(); _blogRepository = serviceLocator.Locate<IBlogRepository>(); // add the needed user _neededUser = new User { DisplayName = "Galilyou", Email = "*****@*****.**", Url = "http://galilyou.blogspot.com", SignUpDate = DateTime.Now }; _userRepository.Add(_neededUser); // add the needed blog _neededBlog = new Blog {Name = "Programming for Cowards", Author = _neededUser, CreatedDate = DateTime.Now, LastModifiedDate = DateTime.Now}; _blogRepository.Add(_neededBlog); }
private void ArrangeModelsForTest() { userRepository = new FakeUserRepository(); userProfileRepository = new FakeUserProfileRepository(); userProfile.Email = EMAIL; userProfileRepository.Add(userProfile); userProfileRepository.Save(); user = EntityHelpers.GetValidUser(); user.Username = EMAIL; user.Password = GrassrootsMembershipService.HashPassword(PASSWORD, null); user.UserProfile = userProfile; userRepository.Add(user); userRepository.Save(); }
public void Invoke(List <UserModel> userModels, int projectId, ref int usersAdded, ref int userdDuplicated, ref List <Tuple <string, string> > userAddedEmails) { var project = projectRepository.GetById(projectId).WithoutStatuses(ProjectStatus.Deleted); if (project == null) { throw new ArgumentNullException($"Cannot add user to project with id: {projectId}."); } var attribute = new EmailAddressAttribute(); foreach (var userModel in userModels) { if (!attribute.IsValid(userModel.Login)) { continue; } var newUser = repository.GetAll().FirstOrDefault(x => x.Login == userModel.Login); if (newUser == null) { var user = new User { PasswordSalt = string.Empty, ActivationToken = Guid.NewGuid().ToString().Replace("-", string.Empty), Login = userModel.Login, Password = string.Empty, FirstName = userModel.FirstName, LastName = userModel.LastName, Status = UserStatus.AccountCreated, ProjectUsers = new List <ProjectUser>(), LastPasswordChange = default(DateTime) }; userAddedEmails.Add(new Tuple <string, string>(user.Login, user.ActivationToken)); user.ProjectUsers.Add(new ProjectUser { ProjectId = project.Id }); setDefaultUserCustomDataBasedOnProject.SetDefaultUserCustomData(project, user); usersAdded++; repository.Add(user); } else { if (newUser.Status != UserStatus.Deleted) { userdDuplicated++; eventBus.Publish(new DuplicateUserImported(newUser.FirstName, newUser.LastName, newUser.Login, projectId)); continue; } newUser.PasswordSalt = string.Empty; newUser.FirstName = userModel.FirstName; newUser.LastName = userModel.LastName; newUser.Password = string.Empty; newUser.ActivationToken = Guid.NewGuid().ToString().Replace("-", string.Empty); newUser.Status = UserStatus.AccountCreated; newUser.LastPasswordChange = default(DateTime); newUser.ProjectUsers = new List <ProjectUser> { new ProjectUser { ProjectId = project.Id } }; setDefaultUserCustomDataBasedOnProject.SetDefaultUserCustomData(project, newUser); userAddedEmails.Add(new Tuple <string, string>(newUser.Login, newUser.ActivationToken)); usersAdded++; repository.Edit(newUser); } } eventBus.Publish(new UsersImported(usersAdded, userdDuplicated, userModels.Count, projectId)); }
public void AddOrUpdate(ManagerUserFilterViewModel managerUserFilterViewModel) { var ph = new Microsoft.AspNet.Identity.PasswordHasher(); try { if (managerUserFilterViewModel.userViewModel.UserID > 0) { if (!CheckDuplicateByEmailAndUser(managerUserFilterViewModel.userViewModel.Email, managerUserFilterViewModel.userViewModel.UserID)) { User user = _userRepo.GetById(managerUserFilterViewModel.userViewModel.UserID); user.UserName = managerUserFilterViewModel.userViewModel.FirstName + managerUserFilterViewModel.userViewModel.LastName; user.FirstName = managerUserFilterViewModel.userViewModel.FirstName; user.LastName = managerUserFilterViewModel.userViewModel.LastName; user.Telephone = managerUserFilterViewModel.userViewModel.Telephone; user.Address1 = managerUserFilterViewModel.userViewModel.Address1; user.Address2 = managerUserFilterViewModel.userViewModel.Address2; user.City = managerUserFilterViewModel.userViewModel.City; user.State = managerUserFilterViewModel.userViewModel.State; user.PostalCode = managerUserFilterViewModel.userViewModel.PostalCode; user.EMail = managerUserFilterViewModel.userViewModel.Email; user.UserType = managerUserFilterViewModel.userViewModel.UserType; user.dashboardUser = managerUserFilterViewModel.userViewModel.IsDashboardUser; user.Active = managerUserFilterViewModel.userViewModel.IsActive; user.ManagerUserID = managerUserFilterViewModel.userViewModel.ManagerUserId > 0 ? managerUserFilterViewModel.userViewModel.ManagerUserId : null; user.UserAccess = managerUserFilterViewModel.userViewModel.AccessLevelId; _userRepo.Update(user); _userClientRepo.DeleteByUserId(managerUserFilterViewModel.userViewModel.UserID); if (managerUserFilterViewModel.userViewModel.ClientId != null) { foreach (var itemId in managerUserFilterViewModel.userViewModel.ClientId) { UserClient uClient = new UserClient() { UserID = managerUserFilterViewModel.userViewModel.UserID, ClientID = Convert.ToInt32(itemId) }; _userClientRepo.Add(uClient); } } _userLevelsRepo.DeleteByUserId(managerUserFilterViewModel.userViewModel.UserID); if (managerUserFilterViewModel.userViewModel.RegionId != null) { foreach (var itemId in managerUserFilterViewModel.userViewModel.RegionId) { UserLevel userLevel = new UserLevel() { UserID = managerUserFilterViewModel.userViewModel.UserID, LevelID = Convert.ToInt32(itemId) }; _userLevelsRepo.Add(userLevel); } } _formUsersRepo.DeleteByUserId(managerUserFilterViewModel.userViewModel.UserID); if (managerUserFilterViewModel.userViewModel.FormId != null) { foreach (var itemId in managerUserFilterViewModel.userViewModel.FormId) { FormUser uClient = new FormUser() { UserID = managerUserFilterViewModel.userViewModel.UserID, FormID = Convert.ToInt32(itemId) }; _formUsersRepo.Add(uClient); } } managerUserFilterViewModel.IsSuccess = true; managerUserFilterViewModel.Message = "Record Updated Successfully."; } else { managerUserFilterViewModel.IsSuccess = false; managerUserFilterViewModel.Message = "Email address already exist."; } } else { if (!CheckDuplicateByEmail(managerUserFilterViewModel.userViewModel.Email)) { User user = new User() { UserName = managerUserFilterViewModel.userViewModel.FirstName + managerUserFilterViewModel.userViewModel.LastName, Password = ph.HashPassword(managerUserFilterViewModel.userViewModel.Password), FirstName = managerUserFilterViewModel.userViewModel.FirstName, LastName = managerUserFilterViewModel.userViewModel.LastName, Telephone = managerUserFilterViewModel.userViewModel.Telephone, Address1 = managerUserFilterViewModel.userViewModel.Address1, Address2 = managerUserFilterViewModel.userViewModel.Address2, City = managerUserFilterViewModel.userViewModel.City, State = managerUserFilterViewModel.userViewModel.State, PostalCode = managerUserFilterViewModel.userViewModel.PostalCode, EMail = managerUserFilterViewModel.userViewModel.Email, UserType = managerUserFilterViewModel.userViewModel.UserType, dashboardUser = managerUserFilterViewModel.userViewModel.IsDashboardUser, Active = managerUserFilterViewModel.userViewModel.IsActive, DateAdded = DateTime.Now, PasswordExpirationDate = DateTime.Now.AddDays(Convert.ToInt32(ConfigurationManager.AppSettings["ExpiryDays"])), IsPasswordHashed = false, ManagerUserID = managerUserFilterViewModel.userViewModel.ManagerUserId > 0? managerUserFilterViewModel.userViewModel.ManagerUserId:null, UserAccess = managerUserFilterViewModel.userViewModel.AccessLevelId }; _userRepo.Add(user); if (user.UserID > 0 && (managerUserFilterViewModel.userViewModel.ClientId != null)) { foreach (var itemId in managerUserFilterViewModel.userViewModel.ClientId) { UserClient dClient = new UserClient() { UserID = user.UserID, ClientID = Convert.ToInt32(itemId) }; _userClientRepo.Add(dClient); } } if (user.UserID > 0 && (managerUserFilterViewModel.userViewModel.RegionId != null)) { foreach (var itemId in managerUserFilterViewModel.userViewModel.RegionId) { UserLevel userLevel = new UserLevel() { UserID = user.UserID, LevelID = Convert.ToInt32(itemId) }; _userLevelsRepo.Add(userLevel); } } if (user.UserID > 0 && (managerUserFilterViewModel.userViewModel.FormId != null)) { foreach (var itemId in managerUserFilterViewModel.userViewModel.FormId) { FormUser formUser = new FormUser() { UserID = user.UserID, FormID = Convert.ToInt32(itemId) }; _formUsersRepo.Add(formUser); } } managerUserFilterViewModel.IsSuccess = true; managerUserFilterViewModel.Message = "Record Inserted Successfully."; } else { managerUserFilterViewModel.IsSuccess = false; managerUserFilterViewModel.Message = "Email address already exist."; } } } catch (Exception ex) { managerUserFilterViewModel.IsSuccess = false; managerUserFilterViewModel.Message = "Sorry, An error occurred!"; } }
public void Add(User entity) { _repo.Add(entity); }
public ResponseViewModel <UserRegisterResponseViewModel> CreateUser(UserRegisterRequestViewModel inputModel) { ResponseViewModel <UserRegisterResponseViewModel> response = new ResponseViewModel <UserRegisterResponseViewModel>(); List <Error> lstError = new List <Error>(); UserRegisterResponseViewModel objUserResponseViewModel = new UserRegisterResponseViewModel(); try { _loggerService.LogInformation(1, "## [UserService][CreateUser]- Start CreateUser user method."); var finduser = _userRepository.FindByEmail(inputModel.email); if (finduser == null) { byte[] passwordHash, passwordSalt; _securityHelper.CreatePasswordHash(inputModel.password, out passwordHash, out passwordSalt); Users objuser = new Users() { Address = inputModel.address, BirthDate = DateTimeOffset.Parse(inputModel.birthdate).UtcDateTime, ContactNumber = inputModel.contactnumber, Email = inputModel.email, FirstName = inputModel.firstname, LastName = inputModel.lastname, Status = inputModel.status, UserType = inputModel.usertype, PasswordHash = passwordHash, PasswordSalt = passwordSalt, CreatedBy = inputModel.createdby, UpdatedBy = inputModel.createdby, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow }; _loggerService.LogInformation(1, "## [UserService][CreateUser]- Create User Model Email : " + objuser.Email + " , FirstName : " + objuser.FirstName + " , LastName : " + objuser.LastName); var userId = _userRepository.Add(objuser); if (userId > 0) { string birthDate = Convert.ToString(inputModel.birthdate); objUserResponseViewModel = new UserRegisterResponseViewModel() { userid = userId, address = inputModel.address, birthdate = string.Format("{0:yyyy-MM-ddTHH:mm:ssZ}", birthDate), contactnumber = inputModel.contactnumber, email = inputModel.email, firstname = inputModel.firstname, lastname = inputModel.lastname, status = inputModel.status, usertype = inputModel.usertype }; _loggerService.LogInformation(1, "## [UserService][CreateUser]- User created sucessfully : " + objUserResponseViewModel.email); } else { _loggerService.LogInformation(1, "## [UserService][CreateUser]- User not created in userRepository for email id : " + inputModel.email); var errorMessage = _errorMessageService.GetErrorMessagesData("2020"); var objError = new Error { Code = "2020", Message = errorMessage }; lstError.Add(objError); } } else { _loggerService.LogInformation(1, "## [UserService]-[CreateUser]- User already exists "); var errorMessage = _errorMessageService.GetErrorMessagesData("2020"); errorMessage = errorMessage.Replace("$$InputData$$", "User"); var objError = new Error { Code = "2020", Message = errorMessage }; lstError.Add(objError); } if (lstError.Count == 0) { response.Status = true; response.Message = "User Created Sucessfully"; response.StatusCode = (int)HttpStatusCode.OK; response.Result = objUserResponseViewModel; } else { response.Status = false; response.Errors = lstError; response.StatusCode = (int)HttpStatusCode.BadRequest; } } catch (Exception ex) { if (ex.InnerException != null) { _loggerService.LogError(1, "## [UserService][CreateUser] innerexception :" + ex.InnerException.ToString()); if (ex.InnerException.Message != null) { _loggerService.LogError(1, "## [UserService][CreateUser] innerexception message :" + ex.InnerException.Message.ToString()); } } else { _loggerService.LogError(1, "## [UserService][CreateUser] exception :" + ex.Message.ToString()); } response.Status = false; response.Message = _errorMessageService.GetErrorMessagesData("501"); response.StatusCode = (int)HttpStatusCode.BadRequest; return(response); } return(response); }
public async Task AddAndSafe(User User) { _UserRepository.Add(User); await _UserRepository.Save(); }
public int Add(Database.User.User model) { return(_userRepository.Add(model)); }
public async Task <IActionResult> Create([FromBody] UserDto user) { var result = await userRepository.Find(x => x.Correo == user.Correo); if (result != null) { return(BadRequest("El correo ya existe")); } user.Password = user.NroIdentificacion.ToString(); byte[] passwordHash, passwordSalt; UtilsPassword.CreatePasswordHash(user.Password, out passwordHash, out passwordSalt); //var usuario = new User //{ // Id = Guid.NewGuid(), // NroIdentificacion = user.NroIdentificacion, // Nombres = user.Nombres, // Apellidos = user.Apellidos, // Correo = user.Correo, // Telefono = user.Telefono, // PasswordHash = passwordHash, // PasswordSalt = passwordSalt, // Activo = user.Activo, // CambioPassword = false, // FechaCreacion = DateTime.Now, // FechaModificacion = DateTime.Now //}; var usuario = mapper.Map <User>(user); usuario.Id = Guid.NewGuid(); usuario.FechaCreacion = DateTime.Now; usuario.FechaModificacion = DateTime.Now; usuario.PasswordHash = passwordHash; usuario.PasswordSalt = passwordSalt; usuario.CambioPassword = false; usuario.Rol = ValidarRol(usuario.Rol); usuario = await userRepository.Add(usuario); var objCambioPassword = await cambioPasswordRepository.Add(new CambioPassword { Id = Guid.NewGuid(), MinutosExpiracion = 120, Usuario = usuario, Activo = true, FechaCreacion = DateTime.Now, FechaModificacion = DateTime.Now }); var sender = configuration.GetSection("Settings").GetSection("EnvioCorreo").GetSection("Sender").Value; var senderPassword = configuration.GetSection("Settings").GetSection("EnvioCorreo").GetSection("Password").Value; UtilsSendEmail.SendEmailChangePassword(usuario.Correo, $"({usuario.Nombres} {usuario.Apellidos})", objCambioPassword.Id.ToString(), sender, senderPassword); return(Ok()); }
public User Add(User addUser) { _userRepo.Add(addUser); return(addUser); }
public async Task Add(User user) { await _repo.Add(user); }
public async Task <User> RegisterUser(UserDto userDto) { return(await userRepository.Add(_mapper.Map <User>(userDto))); }
public async Task <IActionResult> Post([FromBody] User user) { await _userService.Add(user); return(Ok()); }
public void addUser(string name) { _userRepository.Add(name); }
public User Add(User user) { return(_userRepository.Add(user)); }
public void AddUser(User user) { user.Password = _securityService.GenerateHashSha256(user.Password); _repository.Add(user); }
public void Add(User us) { _userRepository.Add(us); }
public User Add(User newUser) { return(_userRepo.Add(newUser)); }
public async Task <IActionResult> Login([FromBody] LoginResource loginResource) { // if (EncryptionHelper.DecryptGetValidDate(licensekey) == false) // { // return BadRequest("Trial Version is Expired"); // } var username = loginResource.Username; var password = loginResource.Password; var anyUser = await userRepository.GetAll(); var userLogin = await userRepository.GetOneByUserName(username); if (shouldLoginAD) { try { var de = new DirectoryEntry("LDAP://" + domainName, username, password); var ds = new DirectorySearcher(de); SearchResult search = ds.FindOne(); if (search != null) { if (userLogin == null) { createNewuser = true; } } else { return(Unauthorized()); } } catch { return(BadRequest("AD Login Problem")); } if (createNewuser) { // new user here userLogin = new User() { Username = username, GddbId = username, AdminStatus = anyUser.Count() <= 0 ? true : false, isActive = true }; password = ""; userRepository.Add(userLogin, password); // Copy all right to module right var rightLists = await moduleRightsRepository.GetAll(); foreach (ModuleRight list in rightLists) { var userModuleRights = new UserModuleRight { ModuleRightsId = list.Id, UserId = userLogin.Id, Read = false, Write = false }; var saveUserModule = mapper.Map <UserModuleRight>(userModuleRights); userModuleRightsRepository.Add(saveUserModule); } if (await unitOfWork.CompleteAsync() == false) { throw new Exception(message: "Save new user Failed"); } } } else { userLogin = await userRepository.Login(username, password); } if (userLogin == null) { return(Unauthorized()); } var allUserModules = await userModuleRepository.GetAll(); var userModules = allUserModules.Where(u => u.UserId == userLogin.Id).ToList(); // Add user claim var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Name, userLogin.Username)); claims.Add(new Claim("Id", userLogin.Id.ToString())); if (userLogin.AdminStatus == true) { claims.Add(new Claim(ClaimTypes.Role, "Administrator")); } foreach (UserModuleRight userModule in userModules) { var right = await moduleRightsRepository.GetOne(userModule.ModuleRightsId); var claim = right.Description.ToString(); if (userModule.Read == true) { claims.Add(new Claim(ClaimTypes.Role, $"{claim}.R")); } if (userModule.Write == true) { claims.Add(new Claim(ClaimTypes.Role, $"{claim}.W")); } } var key = new SymmetricSecurityKey(Encoding.UTF8 .GetBytes(this.config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var user = mapper.Map <ViewUserResource>(userLogin); return(Ok(new { token = tokenHandler.WriteToken(token), user })); }
public static void Add(this IUserRepository repository, string username, string password) { var user = User.CreateInternal(username, password); repository.Add(user); }