public IHttpActionResult RegisterUser(RegisterViewModel newUser) // You can add more parameter here ex LastName, FirstName etc
        {
//          if(!IsValidEmail(newUser.UserName)) // Requires the username to be email format.
//             return BadRequest("Username must be in a valid email format.");

            if (newUser.Role.Split(',').Contains(UserAccount.DEFAULT_ADMIN_LOGIN))
            {
                return(BadRequest("Creating an admin account is forbidden."));
            }

            var user = UserAccount.GetUserByUserName(newUser.UserName);

            if (user != null)
            {
                return(BadRequest("Account already exists"));
            }

            var userId = UserAccount.Create(newUser.UserName, newUser.Password, newUser.Role);

            if (userId != null)
            {
                // Feel free to remove the ABOVE code if not needed.

                return(Ok(new { UserId = userId, Message = "Account successfully created" }));
            }
            else
            {
                return(BadRequest("Account registration failed"));
            }
        }
        public NotificationCollection SaveWaiter(Waiter waiter)
        {
            var newPassword = string.Empty;

            if (waiter.IsTransient())
            {
                newPassword        = passwordGenerator.NewPassword();
                waiter.UserAccount = UserAccount.Create(waiter.EmailAddress, newPassword);
                waiter.UserAccount.EncrypPassword(passwordEncryptor);
            }
            else
            {
                var existingAccount = repository.FindById <Waiter>(waiter.Id);
                waiter.UserAccount = existingAccount.UserAccount;
                //Saving a waiter must not overwrite their shifts with null
                waiter.Shifts = existingAccount.Shifts;
            }

            var result = repository.Save(waiter);

            //If a new waiter was successfully saved
            if (!result.HasErrors() && newPassword.IsNotNullOrEmpty())
            {
                var msg = string.Format("You have been registered on Shifter. Your password has been set to {0}. You should change it to something you will remember after logging in.", newPassword);
                //result += EmailManager.SendEmail(waiter.EmailAddress, Config.FromEmailAddress, "Shifter registration", msg);
                MessagePublisher.PublishComsMessage(msg, "Shifter registration", waiter.EmailAddress);
            }

            return(result);
        }
        public IHttpActionResult RegisterWithRole(string username, string password, string comma_separated_roles = "")
        {
            var userRoles = UserAccount.GetUserRoles(User.Identity.Name);
            var isAdmin   = userRoles.Contains(UserAccount.DEFAULT_ADMIN_LOGIN);

            if (!isAdmin)
            {
                return(BadRequest("Access forbidden. For administrator only."));
            }

            var user = UserAccount.GetUserByUserName(username);

            if (user != null)
            {
                return(BadRequest("Account already exists"));
            }

            var userId = UserAccount.Create(username, password, comma_separated_roles);

            if (userId != null)
            {
                return(Ok(new { UserId = userId, Message = "Account successfully created" }));
            }
            else
            {
                return(BadRequest("Account registration failed"));
            }
        }
Esempio n. 4
0
            public override CREDENTIALS_BASE_TYPE ValidateCredential(CREDENTIALS_TYPE userinfo, string password)
            {
                string accid = userinfo.accountid;

                string userAccountIdInDb = "0";
                //DataManager.DataManager.Controller.Users.IsValidUser(accid, password, out userAccountIdInDb);
                DataSet dsUserDetails = OSADataProvider.Device.IsValidUser(accid, password);

                if (dsUserDetails.Tables[0].Rows.Count > 0)
                {
                    userAccountIdInDb = Convert.ToString(dsUserDetails.Tables[0].Rows[0]["USR_ACCOUNT_ID"], CultureInfo.CurrentCulture);
                }
                else
                {
                    userAccountIdInDb = string.Empty;
                }

                if (string.IsNullOrEmpty(userAccountIdInDb))
                {
                    UserAccount.Create(userAccountIdInDb);
                    CREDENTIALS_BASE_TYPE ret = new CREDENTIALS_BASE_TYPE();
                    //ret.accountid = accid;
                    ret.accountid = userAccountIdInDb;

                    return(ret);
                }
                else
                {
                    return(null);
                }
            }
Esempio n. 5
0
        public ActionResult AdminReg(RegisterViewModel newUser, string RetypePassword)
        {
            if (newUser.Password == RetypePassword)
            {
                var res = UserAccount.Create(newUser.UserName, newUser.Password, "admin");

                if (res != null)
                {
                    var newAdmin = new AdminReg();

                    newAdmin.FirstName = newUser.FirstName;
                    newAdmin.LastName  = newUser.LastName;
                    newAdmin.UserName  = newUser.UserName;
                    newAdmin.Password  = newUser.Password;


                    _db.AdminRegs.Add(newAdmin);
                    _db.SaveChanges();

                    ViewBag.message = "Registered Successfully!";
                    return(View());
                }
                ViewBag.messages = "Registration Failed";
            }


            else
            {
                ViewBag.messages = "Password not matched";
            }

            return(View());
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();

            builder.RegisterDomainEventHandler <UserAccountCreated, UserAccountCreatedHandler>();
            var container = builder.Build();

            DomainEventChannel.Dispatcher = new AutofacDomainEventDispatcher(container);

            UserAccount.Create("username", "*****@*****.**", "password");

            System.Console.ReadKey();
        }
        public NotificationCollection SaveManager(Manager manager)
        {
            var isNewManager = manager.IsTransient();
            var newPassword  = string.Empty;

            var userAccount = manager.UserAccount;

            if (isNewManager)
            {
                //Reactivate the old account
                var inactiveAccount = repository.FindBy <Manager>(w => w.UserAccount.EmailAddress == manager.UserAccount.EmailAddress).FirstOrDefault();
                if (inactiveAccount.IsNotNull())
                {
                    manager.Id = inactiveAccount.Id;
                }

                newPassword         = manager.UserAccount.Password.IsNotNullOrEmpty() ? manager.UserAccount.Password : passwordGenerator.NewPassword();
                manager.UserAccount = UserAccount.Create(manager.UserAccount.Username, newPassword, passwordEncryptor);
            }
            else
            {
                //Update info that must not be overwritten
                var existingAccount = repository.FindById <Manager>(manager.Id);
                manager.UserAccount = existingAccount.UserAccount;
            }

            manager.UserAccount.UpdatePersonalDetails(userAccount);

            var result = repository.Save(manager);

            if (!result.HasErrors())
            {
                result += new Notification("Saved successful.", NotificationSeverity.Information);

                if (isNewManager)
                {
                    var message = repository.FindBy <EmailTemplate>(e => e.TemplateName == Constants.EmailTemplates.ShifterRegistration).FirstOrDefault();

                    message.Body = message.Body.Replace(Constants.EmailTemplatePlaceHolders.Password, newPassword);
                    message.Body = message.Body.Replace(Constants.EmailTemplatePlaceHolders.Name, manager.UserAccount.FirstName);
                    message.Body = message.Body.Replace(Constants.EmailTemplatePlaceHolders.Username, manager.UserAccount.Username);

                    result += repository.Save(EmailNotification.Create(message.Subject, message.Body, SharedConfig.FromSupportEmailAddress, manager.UserAccount.EmailAddress));
                }
            }

            return(result);
        }
Esempio n. 8
0
        public void when_user_account_created_event_is_raised_and_unhandled_email_sent_is_false()
        {
            // Arrange
            UserAccount userAccount;

            // Act
            using (var dispatcher = new TestDomainEventDispatcher())
            {
                DomainEventChannel.Dispatcher = dispatcher;

                userAccount = UserAccount.Create("username", "*****@*****.**", "password");
            }

            // Assert
            Assert.False(userAccount.EmailSent);
        }
Esempio n. 9
0
 //returns nothing if account created OK
 public dynamic Save([FromBody] CreateUserParameters newUser)
 {
     // Attempt to register the user
     try
     {
         var user = UserAccount.Create(newUser.Username, newUser.Password);
         documentSession.Store(user);
         documentSession.SaveChanges();
         FormsAuthentication.SetAuthCookie(newUser.Username, false /* createPersistentCookie */);
         return(null);
     }
     catch (ConcurrencyException)
     {
         return(Request.CreateResponse(HttpStatusCode.Conflict, new { error = "User name already exists. Please enter a different user name." }));
     }
 }
 public bool Handle(RegisterUserAccountCommand message)
 {
     using (IDomainRepository domainRepository = this.GetDomainRepository())
     {
         Address address = new Address();
         address.City    = message.ContactAddressCity;
         address.Country = message.ContactAddressCountry;
         address.State   = message.ContactAddressState;
         address.Street  = message.ContactAddressStreet;
         address.Zip     = message.ContactAddressZip;
         UserAccount userAccount = UserAccount.Create(message.UserName,
                                                      message.Password, message.DisplayName, message.Email, message.ContactPhone, address);
         domainRepository.Save <UserAccount>(userAccount);
         domainRepository.Commit();
         return(true);
     }
 }
Esempio n. 11
0
        public override void Execute(ServerClient client, string[] args)
        {
            if (args.Length != 2)
            {
                SendUsage(client);
                return;
            }

            string username = args[0];
            string password = args[1];

            if (client.Account != null)
            {
                client.SendMessage("You are already authenticated.");
                return;
            }

            if (username.Length > 16 || username.Contains("%") || username.Contains("/") || username.Contains("@") || username.Contains("\\") || username.Contains(";"))
            {
                client.SendMessage("Invalid username. Usernames may not contain %, /, @, ; or \\. Usernames also have a maximum length of 16 characters.");
                return;
            }

            if (string.IsNullOrEmpty(password) || string.IsNullOrWhiteSpace(password) || password.Length < 6)
            {
                client.SendMessage("Invalid password. Passwords must contain at least 6 characters. Passwords may not be whitespace.");
                return;
            }

            if (UserAccount.Find(username) != null)
            {
                client.SendMessage("An account with that username already exists.");
                return;
            }

            UserAccount account = UserAccount.Create(username, password, false);

            if (account == null)
            {
                client.SendMessage("There was a problem creating your account. Please try again later.");
                return;
            }

            client.Account = account;
            client.SendMessage("You are now authenticated as " + account.Username + "!");
        }
        public IHttpActionResult RegisterUser(string username, string password, string role = "") // You can add more parameter here ex LastName, FirstName etc
        {
            foreach (var r in role.Split(',').Where(r => !string.IsNullOrWhiteSpace(r)))
            {
                if (r.Trim().ToLower() == UserAccount.DEFAULT_ADMIN_LOGIN.ToLower())
                {
                    return(BadRequest("Creating an admin account is forbidden."));
                }
            }

            var user = UserAccount.GetUserByUserName(username);

            if (user != null)
            {
                return(BadRequest("Account already exists"));
            }

            var userId = UserAccount.Create(username, password, role);

            if (userId != null)
            {
                // Link User Account to Entities e.g. Student, Employee, Customer
//              if(role == "doctor")
//              {
//                  var doctor = new Doctor();
//                  doctor.UserId = userId.Value;
//                  _db.Doctors.Add(doctor);
//                  _db.SaveChanges();
//              }
//              else if(role == "patient")
//              {
//                  var p = new Patient();
//                  p.UserId = userId.Value;
//                  _db.Patients.Add(p);
//                  _db.SaveChanges();
//              }
                // Feel free to remove the ABOVE code if not needed.

                return(Ok(new { UserId = userId, Message = "Account successfully created" }));
            }
            else
            {
                return(BadRequest("Account registration failed"));
            }
        }
        private Staff CreateAccount(Staff staff, UserAccount userAccount, string newPassword)
        {
            //Reactivate the old account if exists
            var inactiveAccount = repository.FindBy <Staff>(w => w.UserAccount.EmailAddress == userAccount.EmailAddress && w.IsActive == false).FirstOrDefault();

            if (inactiveAccount.IsNotNull())
            {
                staff.Id = inactiveAccount.Id;
            }

            var username = userAccount.Username.IsNullOrEmpty() ? userAccount.EmailAddress : userAccount.Username;

            //Create security account
            staff.IsActive    = true;
            staff.UserAccount = UserAccount.Create(username, newPassword, passwordEncryptor);

            return(staff);
        }
        public async Task <Unit> Handle(RegisterNewUserCommand request, CancellationToken cancellationToken)
        {
            if (!CanRegisterUser())
            {
                throw new NotImplementedException();
            }
            var password = PasswordManager.HashPassword(request.Password);

            var user = UserAccount.Create(
                request.Login,
                password,
                request.Email,
                request.FirstName,
                request.LastName);

            await _userRepository.AddAsync(user);

            return(default);
        public ActionResult Create(RegisterViewModel newUser, string RetypePassword, Vetowner vet, Product product, HttpPostedFileBase fileUpload)
        {
            if (newUser.Password == RetypePassword)
            {
                var res = UserAccount.Create(newUser.UserName, newUser.Password, "owner");

                if (res != null)
                {
                    product.Status = "Pending";
                    vet.Username   = newUser.UserName;
                    vet.Password   = newUser.Password;
                    if (ModelState.IsValid)
                    {
                        if (fileUpload != null)
                        {
                            product.PictureFilename = fileUpload.SaveAsJpegFile(product.Name);
                        }

                        TempData["ownersucces"] = "text";
                        _db.Vetowners.Add(vet);
                        _db.SaveChanges();

                        _db.Products.Add(product);
                        _db.SaveChanges();
                        ViewBag.message = "Registered Successfully!";
                        return(RedirectToAction("Login", "Account"));
                    }
                    else
                    {
                        return(View(product));
                    }
                }
                ViewBag.messages = "Registration Failed";
            }


            else
            {
                ViewBag.messages = "Password not matched";
            }

            return(View());
        }
Esempio n. 16
0
        public void when_user_account_created_event_is_raised_and_handled_email_sent_is_true()
        {
            // Arrange
            UserAccount userAccount;

            // Act
            using (var dispatcher = new TestDomainEventDispatcher())
            {
                var handler = new UserAccountCreatedHandler();
                dispatcher.Register <UserAccountCreated>(handler.When);

                DomainEventChannel.Dispatcher = dispatcher;

                userAccount = UserAccount.Create("username", "*****@*****.**", "password");
            }

            // Assert
            Assert.True(userAccount.EmailSent);
        }
Esempio n. 17
0
        public ActionResult Register(RegisterViewModel newUser, string RetypePassword)
        {
            if (Session["user"] != null)
            {
                var user  = Session["user"].ToString();
                var vetId = _db.Vetowners.Where(x => x.Username == user).FirstOrDefault();
                int Id    = vetId.Id;

                if (newUser.Password == RetypePassword)
                {
                    var Regis = UserAccount.Create(newUser.UserName, newUser.Password, "recept");
                    if (Regis != null)
                    {
                        var newRecept = new Receptionist();

                        newRecept.Fullname = newUser.Fullname;
                        newRecept.Username = newUser.UserName;
                        newRecept.Password = newUser.Password;
                        newRecept.VetId    = Id;
                        ViewBag.reg        = "text";
                        _db.Receptionists.Add(newRecept);
                        _db.SaveChanges();


                        return(View());
                    }

                    ViewBag.messages = "Registration Failed";
                }

                else
                {
                    ViewBag.message = "Password not matched";
                }
                return(View());
            }


            return(RedirectToAction("Logoff", "Account"));
        }
Esempio n. 18
0
        public ActionResult Register(RegisterViewModel newUser, string RetypePassword)
        {
            if (newUser.Password == RetypePassword)
            {
                var res = UserAccount.Create(newUser.UserName, newUser.Password, "customer");

                if (res != null)
                {
                    var newCust = new Customer();

                    newCust.Fullname = newUser.Fullname;

                    newCust.Username = newUser.UserName;
                    newCust.Address  = newUser.Addess;
                    newCust.Password = newUser.Password;
                    newCust.AddCity  = newUser.AddCity;
                    newCust.Number   = newUser.Number;

                    TempData["register"] = "register";

                    _db.Customers.Add(newCust);
                    _db.SaveChanges();



                    return(RedirectToAction("Login"));
                }
                ViewBag.message = "Account is already exist!";
            }


            else
            {
                ViewBag.notmatch = "Password not matched";
            }

            return(View());
        }
Esempio n. 19
0
        /// <summary>
        ///     Make a new end user in the database
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="email"></param>
        /// <param name="passwordQuestion"></param>
        /// <param name="passwordAnswer"></param>
        /// <param name="isApproved"></param>
        /// <param name="providerUserKey"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public override MembershipUser CreateUser(
            string username,
            string password,
            string email,
            string passwordQuestion,
            string passwordAnswer,
            bool isApproved,
            object providerUserKey,
            out MembershipCreateStatus status
            )
        {
            username = username.Trim();
            password = password.Trim();
            email = email.Trim();
            if (passwordQuestion != null)
            {
                passwordQuestion = passwordQuestion.Trim();
            }

            if (passwordAnswer != null)
            {
                passwordAnswer = passwordAnswer.Trim();
            }

            // Validate username/password
            var args = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if (RequiresUniqueEmail && GetUserNameByEmail(email) != string.Empty)
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            // Check whether user with passed username already exists
            MembershipUser mu = GetUser(username, false);

            if (mu == null)
            {
                var eu = new UserAccount
                {
                    UserName = username,
                    EMail = email,
                    Password = EncodePassword(password),
                    PasswordFormat = MembershipPasswordFormat.Hashed.ToString(),
                    PasswordSalt = string.Empty,
                    PasswordQuestion = passwordQuestion,
                    PasswordAnswer = EncodePassword(passwordAnswer),
                    FailedPasswordAttemptCount = 0,
                    IsOnLine = false,
                    IsApproved = isApproved,
                    Comment = string.Empty,
                    IsLockedOut = false,
                };
                try
                {
                    eu.Create();

                    status = eu.UserAccountID > 0 ? MembershipCreateStatus.Success : MembershipCreateStatus.UserRejected;
                }
                catch
                {
                    status = MembershipCreateStatus.UserRejected;
                }

                return GetUser(username, false);
            }
            status = MembershipCreateStatus.DuplicateUserName;

            return null;
        }