/// <summary>
 ///     Create the message that are sent from the server to the client with the salts that should be used during the
 ///     authentication.
 /// </summary>
 /// <param name="user">User that want to be authenticated</param>
 /// <returns>
 ///     <see cref="AuthenticationHandshakeReply" />
 /// </returns>
 public IAuthenticationHandshakeReply CreateServerPreAuthentication(IUserAccount user)
 {
     return new AuthenticationHandshakeReply()
     {
         AccountSalt = user.PasswordSalt,
         SessionSalt = Hasher.CreateSalt()
     };
 }
Ejemplo n.º 2
0
        ///// <summary>
        ///// Send a plain text email with the specified properties. The email will appear to come from the name and email specified in the
        ///// EmailFromName and EmailFromAddress configuration settings. The email
        ///// is sent to the address configured in the emailToAddress setting in the configuration file. If
        ///// <paramref name="sendOnBackgroundThread"/> is true, the e-mail is sent on a background thread and the function
        ///// returns immediately. An exception is thrown if an error occurs while sending the e-mail, unless <paramref name="sendOnBackgroundThread"/>
        ///// is true, in which case the error is logged but the exception does not propagate back to the UI thread.
        ///// </summary>
        ///// <param name="subject">The text to appear in the subject of the email.</param>
        ///// <param name="body">The body of the email. If the body is HTML, specify true for the isBodyHtml parameter.</param>
        ///// <param name="galleryId">The gallery ID.</param>
        ///// <param name="sendOnBackgroundThread">If set to <c>true</c> send e-mail on a background thread. This causes any errors
        ///// to be silently handled by the error logging system, so if it is important for any errors to propogate to the UI,
        ///// such as when testing the e-mail function in the Site Administration area, set to <c>false</c>.</param>
        ///// <overloads>
        ///// Send an e-mail message.
        ///// </overloads>
        ///// <exception cref="WebException">Thrown when a SMTP Server is not specified. (Not thrown when
        ///// <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        ///// <exception cref="SmtpException">Thrown when the connection to the SMTP server failed, authentication failed,
        ///// or the operation timed out. (Not thrown when <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        ///// <exception cref="SmtpFailedRecipientsException">The message could not be delivered to one or more
        ///// recipients. (Not thrown when <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        //public static void SendEmail(string subject, string body, int galleryId, bool sendOnBackgroundThread)
        //{
        //  MailAddress recipient = new MailAddress(Config.GetCore().EmailToAddress, Config.GetCore().EmailToName);
        //  SendEmail(recipient, subject, body, galleryId, sendOnBackgroundThread);
        //}
        /// <overloads>
        /// Send an e-mail.
        /// </overloads>
        /// <summary>
        /// Send a plain text e-mail to the <paramref name="user" />. The email will appear to come from the name and email specified in the
        /// <see cref="IAppSetting.EmailFromName" /> and <see cref="IAppSetting.EmailFromAddress" /> configuration settings.
        /// The e-mail is sent on a background thread, so if an error occurs on that thread no exception bubbles to the caller (the error, however, is
        /// recorded in the error log). If it is important to know if the e-mail was successfully sent, use the overload of this
        /// method that specifies a sendOnBackgroundThread parameter.
        /// </summary>
        /// <param name="user">The user to receive the email. If the user does not have a valid e-mail, no action is taken.</param>
        /// <param name="subject">The text to appear in the subject of the email.</param>
        /// <param name="body">The body of the email. Must be plain text.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="user" /> is null.</exception>
        public static void SendEmail(IUserAccount user, string subject, string body)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            if (HelperFunctions.IsValidEmail(user.Email))
            {
                SendEmail(new MailAddress(user.Email, user.UserName), subject, body, false);
            }
        }
Ejemplo n.º 3
0
 public RegistrationModel(IUserAccount entity)
 {
     NickName = entity.NickName;
     Email = entity.Email;
     Description = entity.Description;
     Avatar = entity.Avatar;
     RegistrationDate = entity.RegistrationDate;
     if(string.IsNullOrEmpty(entity.PasswordHash))
     {
         IsTempUser = true;
     }
 }
Ejemplo n.º 4
0
        ///// <summary>
        ///// Send a plain text email with the specified properties. The email will appear to come from the name and email specified in the
        ///// EmailFromName and EmailFromAddress configuration settings. The email
        ///// is sent to the address configured in the emailToAddress setting in the configuration file. If
        ///// <paramref name="sendOnBackgroundThread"/> is true, the e-mail is sent on a background thread and the function
        ///// returns immediately. An exception is thrown if an error occurs while sending the e-mail, unless <paramref name="sendOnBackgroundThread"/>
        ///// is true, in which case the error is logged but the exception does not propagate back to the UI thread.
        ///// </summary>
        ///// <param name="subject">The text to appear in the subject of the email.</param>
        ///// <param name="body">The body of the email. If the body is HTML, specify true for the isBodyHtml parameter.</param>
        ///// <param name="galleryId">The gallery ID.</param>
        ///// <param name="sendOnBackgroundThread">If set to <c>true</c> send e-mail on a background thread. This causes any errors
        ///// to be silently handled by the error logging system, so if it is important for any errors to propogate to the UI,
        ///// such as when testing the e-mail function in the Site Administration area, set to <c>false</c>.</param>
        ///// <overloads>
        ///// Send an e-mail message.
        ///// </overloads>
        ///// <exception cref="WebException">Thrown when a SMTP Server is not specified. (Not thrown when
        ///// <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        ///// <exception cref="SmtpException">Thrown when the connection to the SMTP server failed, authentication failed,
        ///// or the operation timed out. (Not thrown when <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        ///// <exception cref="SmtpFailedRecipientsException">The message could not be delivered to one or more
        ///// recipients. (Not thrown when <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        //public static void SendEmail(string subject, string body, int galleryId, bool sendOnBackgroundThread)
        //{
        //  MailAddress recipient = new MailAddress(Config.GetCore().EmailToAddress, Config.GetCore().EmailToName);

        //  SendEmail(recipient, subject, body, galleryId, sendOnBackgroundThread);
        //}

        /// <overloads>
        /// Send an e-mail.
        /// </overloads>
        /// <summary>
        /// Send a plain text e-mail to the <paramref name="user" />. The email will appear to come from the name and email specified in the
        /// <see cref="IAppSetting.EmailFromName" /> and <see cref="IAppSetting.EmailFromAddress" /> configuration settings.
        /// The e-mail is sent on a background thread, so if an error occurs on that thread no exception bubbles to the caller (the error, however, is
        /// recorded in the error log). If it is important to know if the e-mail was successfully sent, use the overload of this
        /// method that specifies a sendOnBackgroundThread parameter.
        /// </summary>
        /// <param name="user">The user to receive the email. If the user does not have a valid e-mail, no action is taken.</param>
        /// <param name="subject">The text to appear in the subject of the email.</param>
        /// <param name="body">The body of the email. Must be plain text.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="user" /> is null.</exception>
        public static void SendEmail(IUserAccount user, string subject, string body)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (HelperFunctions.IsValidEmail(user.Email))
            {
                SendEmail(new MailAddress(user.Email, user.UserName), subject, body, false);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Gets the email template. Replacement parameters in the template are replaced with their appropriate values. The data
        /// in the template can be used to construct an e-mail.
        /// </summary>
        /// <param name="template">The template to retrieve.</param>
        /// <param name="user">The user associated with the template.</param>
        /// <returns>Returns an e-mail template.</returns>
        public static EmailTemplate GetEmailTemplate(EmailTemplateForm template, IUserAccount user)
        {
            EmailTemplate emailTemplate = new EmailTemplate();

            emailTemplate.EmailTemplateId = template;

            string filePath = Utils.GetPath(String.Format(CultureInfo.InvariantCulture, "/templates/{0}.txt", template));

            // Step 1: Get subject and body from text file and assign to fields.
            using (StreamReader sr = File.OpenText(filePath))
            {
                while (sr.Peek() >= 0)
                {
                    string lineText = sr.ReadLine().Trim();

                    if (lineText == "[Subject]")
                    {
                        emailTemplate.Subject = sr.ReadLine();
                    }

                    if (lineText == "[Body]")
                    {
                        emailTemplate.Body = sr.ReadToEnd();
                    }
                }
            }

            // Step 2: Update replacement parameters with real values.
            emailTemplate.Body = emailTemplate.Body.Replace("{CurrentPageUrlFull}", Utils.GetCurrentPageUrlFull());

            string userName = (user != null ? user.UserName : String.Empty);
            string email    = (user != null ? user.Email : String.Empty);

            emailTemplate.Body = emailTemplate.Body.Replace("{UserName}", userName);
            emailTemplate.Body = emailTemplate.Body.Replace("{Email}", String.IsNullOrEmpty(email) ? Resources.GalleryServerPro.Email_Template_No_Email_For_User_Replacement_Text : email);

            if (emailTemplate.Body.Contains("{VerificationUrl}"))
            {
                emailTemplate.Body = emailTemplate.Body.Replace("{VerificationUrl}", GenerateVerificationLink(userName));
            }

            if (emailTemplate.Body.Contains("{Password}"))
            {
                emailTemplate.Body = emailTemplate.Body.Replace("{Password}", UserController.GetPassword(userName));
            }

            if (emailTemplate.Body.Contains("{ManageUserUrl}"))
            {
                emailTemplate.Body = emailTemplate.Body.Replace("{ManageUserUrl}", GenerateManageUserLink(userName));
            }

            return(emailTemplate);
        }
Ejemplo n.º 6
0
 public AdminController(IUser iuser, ISetting isetting, ILog ilog, IPrice iprice, INotice inotice, IRequestMoney irequestmoney, IMoney imoney, IHelp ihelp, IUserAccount iuseraccount)
 {
     this.iuser         = iuser;
     this.isetting      = isetting;
     this.ilog          = ilog;
     this.iprice        = iprice;
     this.inotice       = inotice;
     this.irequestmoney = irequestmoney;
     this.imoney        = imoney;
     this.ihelp         = ihelp;
     this.iuseraccount  = iuseraccount;
 }
Ejemplo n.º 7
0
        private void AssertVisibility(IUserAccount custodian)
        {
            Assert.IsTrue(_fullNameTextBox.IsVisible);

            Assert.IsTrue(_loginIdTextBox.IsVisible);
            Assert.IsTrue(_isEnabledTextBox.IsVisible);

            Assert.AreEqual(_enableButton.IsVisible, !custodian.IsEnabled);
            Assert.AreEqual(_disableButton.IsVisible, custodian.IsEnabled);

            Assert.IsTrue(_passwordTextBox.IsVisible);
            Assert.IsTrue(_changeButton.IsVisible);
        }
Ejemplo n.º 8
0
        void IUserAccountsCommand.ActivateUserAccount(IUserAccount user, Guid activatedById)
        {
            _repository.ActivateUserAccount(user.Id, activatedById, DateTime.Now);

            // Fire events.

            var handlers = UserActivated;

            if (handlers != null)
            {
                handlers(this, new UserAccountEventArgs(user.Id, user.UserType, activatedById));
            }
        }
Ejemplo n.º 9
0
        public void MatchPassword_CorrectPassword_ResultTrue()
        {
            // prepare
            string       PlainPassword    = "******";
            IUserAccount shopOwnerAccount = _kernel.Get <IUserAccount>();

            shopOwnerAccount.Password = "******";
            // act
            bool isCorrect = shopOwnerAccount.MatchPassword(PlainPassword);

            // assert
            Assert.Equals(true, isCorrect);
        }
Ejemplo n.º 10
0
        public async Task <string> GeneratePinCode(IUserAccount user, string cellular, string email)
        {
            IAccessToken accessToken = await GenerateToken(user);

            PasswordBuilder  pb  = new PasswordBuilder();
            PinCodeGenerator gen = new PinCodeGenerator();

            string pinCode = gen.GenerateNextPinCode();

            await m_session_repository.ResetPinCode(accessToken.Guid, pb.MakeGuid(cellular, email, pinCode), pb.MakePasswordHash(cellular, email, pinCode));

            return(pinCode);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Sends an e-mail based on the <paramref name="templateForm"/> to the specified <paramref name="user"/>.
        /// No action is taken if the user's e-mail is null or empty. The e-mail is sent on a
        /// background thread, so if an error occurs on that thread no exception bubbles to the caller (the error, however, is
        /// recorded in the error log). If <paramref name="sendOnBackgroundThread"/> is true, the e-mail is sent on a background
        /// thread and the function returns immediately. An exception is thrown if an error occurs while sending the e-mail,
        /// unless <paramref name="sendOnBackgroundThread"/> is true, in which case the error is logged but the exception does
        /// not propagate back to the UI thread.
        /// </summary>
        /// <param name="user">The user to receive the e-mail.</param>
        /// <param name="templateForm">The template form specifying the type of e-mail to send.</param>
        /// <param name="galleryId">The gallery ID containing the e-mail configuration settings to use.</param>
        /// <param name="sendOnBackgroundThread">If set to <c>true</c> send e-mail on a background thread. This causes any errors
        /// to be silently handled by the error logging system, so if it is important for any errors to propogate to the UI,
        /// such as when testing the e-mail function in the Site Administration area, set to <c>false</c>.</param>
        public static void SendNotificationEmail(IUserAccount user, EmailTemplateForm templateForm, int galleryId, bool sendOnBackgroundThread)
        {
            if (String.IsNullOrEmpty(user.Email))
            {
                return;
            }

            EmailTemplate emailTemplate = GetEmailTemplate(templateForm, user);

            MailAddress emailRecipient = new MailAddress(user.Email, user.UserName);

            SendEmail(emailRecipient, emailTemplate.Subject, emailTemplate.Body, galleryId, sendOnBackgroundThread);
        }
 private void SaveUserAccount(IUserAccount userAccount, string path)
 {
     try
     {
         string serialized = JsonConvert.SerializeObject(userAccount);
         File.WriteAllText(path, serialized);
     }
     catch (IOException ex)
     {
         Debug.WriteLine($"Failed to save user account to {path}: {ex.Message}");
         throw new CredentialsStoreException(ex.Message, ex);
     }
 }
Ejemplo n.º 13
0
        private void AssertVisibility(IUserAccount administrator)
        {
            Assert.IsTrue(_fullNameTextBox.IsVisible);

            Assert.IsTrue(_loginIdTextBox.IsVisible);
            Assert.IsTrue(_isEnabledTextBox.IsVisible);

            Assert.AreEqual(!administrator.IsEnabled, _enableButton.IsVisible);
            Assert.AreEqual(administrator.IsEnabled, _disableButton.IsVisible);

            Assert.IsTrue(_passwordTextBox.IsVisible);
            Assert.IsTrue(_changeButton.IsVisible);
        }
Ejemplo n.º 14
0
        void IUserAccountsCommand.DeactivateUserAccount(IUserAccount user, Guid deactivatedById)
        {
            _repository.DeactivateUserAccount(user.Id, deactivatedById, DateTime.Now);

            // Fire events.

            var handlers = UserDeactivated;

            if (handlers != null)
            {
                handlers(this, new UserDeactivatedEventArgs(user.Id, user.UserType, deactivatedById, DeactivationReason.Other, null));
            }
        }
Ejemplo n.º 15
0
        public static UserAccountJson CreateInstance(IUserAccount ua)
        {
            UserAccountJson user = new UserAccountJson();

            user.UserId      = ua.UserId;
            user.Name        = ua.Name;
            user.Description = ua.Description;
            user.IsBlocked   = ua.IsBlocked;
            user.Password    = ua.Password;
            user.Scope       = ua.Scope;
            user.Username    = ua.Username;
            return(user);
        }
Ejemplo n.º 16
0
        public UserAccount(IUserAccount user) : base(user)
        {
            CreatedDateTime = user.CreatedDateTime;
            IsAdmin         = user.IsAdmin;
            IsStaff         = user.IsStaff;
            IsCustomer      = user.IsCustomer;

            LoginName = user.LoginName;

            if (user.Address != null)
            {
                Address = new Address(user.Address);
            }
        }
        /// <summary>
        /// Updates the current account for the extension.
        /// This method will also invalidate the project.
        /// It is up to the caller to select an appropriate one.
        /// </summary>
        public void UpdateCurrentAccount(IUserAccount account)
        {
            if (CurrentAccount?.AccountName != account?.AccountName)
            {
                CurrentAccount          = account;
                CurrentProjectId        = null;
                CurrentProjectNumericId = null;

                InvalidateProjectList();

                UpdateDefaultCredentials();
                CurrentAccountChanged?.Invoke(this, EventArgs.Empty);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Handles the LoggedIn event of the Login control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Login1_LoggedIn(object sender, EventArgs e)
        {
            // Get the user. This will ensure we get the username with the correct case, regardless of how the user logged on (Admin vs. admin, etc).
            IUserAccount user = UserController.GetUser(Login1.UserName, false);

            UserController.UserLoggedOn(user.UserName, this.GalleryPage.GalleryId);

            if (this.GalleryPage.GallerySettings.EnableUserAlbum && this.GalleryPage.GallerySettings.RedirectToUserAlbumAfterLogin)
            {
                Utils.Redirect(Utils.GetUrl(PageId.album, "aid={0}", UserController.GetUserAlbumId(user.UserName, this.GalleryPage.GalleryId)));
            }

            ReloadPage();
        }
        public void DeleteUser(string userId)
        {
            if (String.IsNullOrWhiteSpace(userId))
            {
                throw new Exception("user ID is not set");
            }
            IUserAccount ua = GetUserById(userId);

            if (ua != null)
            {
                _userAccounts.Remove(ua);
                RemoveFromDisk(userId);
            }
        }
Ejemplo n.º 20
0
        public void GetUserProfile()
        {
            User user;

            using (SMPSEntities123 objectContext = new SMPSEntities123())
            {
                IQueryable <User> users = objectContext.Users;
                user = users.FirstOrDefault();
            }

            IUserAccount obj         = this.container.Resolve <IUserAccount>();
            UserProfile  profileuser = obj.GetUserProfile(user.UserLoginId);

            Assert.AreEqual(true, profileuser != null);
        }
Ejemplo n.º 21
0
        public void CheckValidUser()
        {
            User user;

            using (SMPSEntities123 objectContext = new SMPSEntities123())
            {
                IQueryable <User> users = objectContext.Users;
                user = users.FirstOrDefault();
            }

            IUserAccount obj         = this.container.Resolve <IUserAccount>();
            UserProfile  userProfile = obj.ValidateUser(user.UserLoginId, user.UserLoginPassword);

            Assert.AreEqual(true, userProfile != null);
        }
Ejemplo n.º 22
0
        void IUserAccountsCommand.DeactivateUserAccount(IUserAccount user, DeactivationReason reason, string comments)
        {
            // Deactivated themselves.

            _repository.DeactivateUserAccount(user.Id, user.Id, DateTime.Now, reason, comments);

            // Fire events.

            var handlers = UserDeactivated;

            if (handlers != null)
            {
                handlers(this, new UserDeactivatedEventArgs(user.Id, user.UserType, user.Id, reason, comments));
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Copies the current account information to the specified <paramref name="userAccount" />. The <paramref name="userAccount" />
        /// must be able to be cast to an instance of <see cref="UserAccount" />. If not, an <see cref="ArgumentNullException" />
        /// is thrown.
        /// </summary>
        /// <param name="userAccount">The user account to populate with information from the current instance.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="userAccount" /> is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="userAccount" /> cannot be cast to an instance of
        /// <see cref="UserAccount" />.</exception>
        public void CopyTo(IUserAccount userAccount)
        {
            if (userAccount == null)
            {
                throw new ArgumentNullException("userAccount");
            }

            try
            {
                CopyToInstance(userAccount as UserAccount);
            }
            catch (ArgumentNullException)
            {
                throw new ArgumentOutOfRangeException("userAccount", "The parameter 'userAccount' cannot be cast to an instance of UserAccount.");
            }
        }
Ejemplo n.º 24
0
        public void BeforeEach()
        {
            _defaultProject = new Project {
                ProjectId = DefaultProjectId
            };
            _defaultUserAccount = Mock.Of <IUserAccount>(ua => ua.AccountName == DefaultAccountName);

            _fileSystemMock = new Mock <IFileSystem> {
                DefaultValueProvider = DefaultValueProvider.Mock
            };

            _objectUnderTest = new CredentialsStore(_fileSystemMock.ToLazy());

            _projectIdChangedHandlerMock = new Mock <Action <object, EventArgs> >();
            _accountChangedHandlerMock   = new Mock <Action <object, EventArgs> >();
        }
        private static string GetFileName(IUserAccount userAccount)
        {
            string serialized = JsonConvert.SerializeObject(userAccount);
            SHA1   sha1       = SHA1.Create();

            byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(serialized));

            var sb = new StringBuilder();

            foreach (byte b in hash)
            {
                sb.AppendFormat("{0:x2}", b);
            }
            sb.Append(".json");
            return(sb.ToString());
        }
Ejemplo n.º 26
0
        protected void cbValidateNewUserName_Callback(object sender, ComponentArt.Web.UI.CallBackEventArgs e)
        {
            // The user just typed in a user name in the Add New User wizard. Let's check to see if it already
            // exists and let the user know the result.
            string requestedUsername = e.Parameter;

            if (String.IsNullOrEmpty(requestedUsername))
            {
                lblUserNameValidationResult.Text = String.Empty;
            }
            else
            {
                if (UseEmailForAccountName && (!HelperFunctions.IsValidEmail(requestedUsername)))
                {
                    // App is configured to use an e-mail address as the account name, but the name is not a valid
                    // e-mail.
                    lblUserNameValidationResult.Text     = Resources.GalleryServerPro.CreateAccount_Verification_Username_Not_Valid_Email_Text;
                    lblUserNameValidationResult.CssClass = "gsp_msgwarning";
                }
                else if (Util.RemoveHtmlTags(requestedUsername).Length != requestedUsername.Length)
                {
                    // The user name has HTML tags, which are not allowed.
                    lblUserNameValidationResult.Text     = Resources.GalleryServerPro.Site_Invalid_Text;
                    lblUserNameValidationResult.CssClass = "gsp_msgwarning";
                }
                else
                {
                    // We passed the first test above. Now verify that the requested user name is not already taken.
                    IUserAccount user = UserController.GetUser(requestedUsername, false);

                    bool userNameIsInUse = (user != null);

                    if (userNameIsInUse)
                    {
                        lblUserNameValidationResult.Text     = Resources.GalleryServerPro.Admin_Manage_Users_Username_Already_In_Use_Msg;
                        lblUserNameValidationResult.CssClass = "gsp_msgwarning";
                    }
                    else
                    {
                        lblUserNameValidationResult.Text     = Resources.GalleryServerPro.Admin_Manage_Users_Username_Already_Is_Valid_Msg;
                        lblUserNameValidationResult.CssClass = "gsp_msgfriendly";
                    }
                }
            }

            lblUserNameValidationResult.RenderControl(e.Output);
        }
Ejemplo n.º 27
0
            public void WhenUpdateUserAccountWithPartialAddress_ThenUpdatesAccount()
            {
                var account = new UserAccount
                {
                    Id           = "foo",
                    Username     = "******",
                    PasswordHash = "apasswordhash",
                    Forenames    = "aforename",
                    Surname      = "asurname",
                    Email        = "anemail",
                    MobilePhone  = "amobilephone",
                    Address      = new Address
                    {
                        Street1 = "astreet1",
                        Street2 = "",
                        Town    = "atown",
                    },
                    Roles = "roles"
                };
                var newAccount = new UserAccount();

                storageProvider.Setup(sp => sp.Get(It.IsAny <string>()))
                .Returns(account);
                storageProvider.Setup(sp => sp.Update(It.IsAny <string>(), It.IsAny <IUserAccount>()))
                .Returns(newAccount);

                IUserAccount result = manager.UpdateUserAccount("auserid", "bar1", "apasswordhash", "newpasswordhash",
                                                                "newforename",
                                                                "newsurname", "newemail", "newmobilephone",
                                                                new Address {
                    Street2 = "newstreet2",
                });

                storageProvider.Verify(sp => sp.Update("bar1", It.Is <IUserAccount>(
                                                           ua => ua.Username == "ausername" &&
                                                           ua.PasswordHash == "newpasswordhash" &&
                                                           ua.Forenames == "newforename" &&
                                                           ua.Surname == "newsurname" &&
                                                           ua.Email == "newemail" &&
                                                           ua.MobilePhone == "newmobilephone" &&
                                                           ua.Address.Street1 == "astreet1" &&
                                                           ua.Address.Street2 == "newstreet2" &&
                                                           ua.Address.Town == "atown"
                                                           )), Times.Once());

                Assert.Equal(newAccount, result);
            }
Ejemplo n.º 28
0
        private void AssertVisibility(IUserAccount employer)
        {
            Assert.IsTrue(_firstNameTextBox.IsVisible);
            Assert.IsTrue(_lastNameTextBox.IsVisible);
            Assert.IsTrue(_emailAddressTextBox.IsVisible);
            Assert.IsTrue(_phoneNumberTextBox.IsVisible);

            Assert.IsTrue(_loginIdTextBox.IsVisible);
            Assert.IsTrue(_isEnabledTextBox.IsVisible);

            Assert.AreEqual(_enableButton.IsVisible, !employer.IsEnabled);
            Assert.AreEqual(_disableButton.IsVisible, employer.IsEnabled);

            Assert.IsTrue(_changePasswordTextBox.IsVisible);
            Assert.IsTrue(_changeButton.IsVisible);
            Assert.IsTrue(_sendPasswordEmailCheckBox.IsVisible);
        }
Ejemplo n.º 29
0
        public virtual void Edit(IUserAccount user)
        {
            DbCommand command = _dbCommandFactory.CreateCommand("AdminAccount_Edit",
                                                                _dbCommandFactory.CreateParameter("ID", user.ID),
                                                                _dbCommandFactory.CreateParameter("AccountCreationDateTime", user.AccountCreationDateTime),
                                                                _dbCommandFactory.CreateParameter("AccountStatus", user.AccountStatus),
                                                                _dbCommandFactory.CreateParameter("EmailAddress", user.EmailAddress),
                                                                _dbCommandFactory.CreateParameter("FirstName", user.FirstName),
                                                                _dbCommandFactory.CreateParameter("LastName", user.LastName),
                                                                _dbCommandFactory.CreateParameter("LastWrongPasswordAttemptDateTime", user.LastWrongPasswordAttemptDateTime),
                                                                _dbCommandFactory.CreateParameter("MobileNumber", user.MobileNumber),
                                                                _dbCommandFactory.CreateParameter("Password", user.EncryptedPassword),
                                                                _dbCommandFactory.CreateParameter("WrongPasswordAttempt", user.WrongPasswordAttempt)
                                                                );

            _dbCommandExecutionService.ExecuteCommand(command);
        }
Ejemplo n.º 30
0
        private void SendTestEmail()
        {
            string       subject   = Resources.GalleryServer.Admin_Gallery_Settings_Test_Email_Subject;
            string       body      = Resources.GalleryServer.Admin_Gallery_Settings_Test_Email_Body;
            string       msgResult = String.Empty;
            bool         emailSent = false;
            MessageStyle msgStyle;
            IUserAccount user = UserController.GetUser();

            if (HelperFunctions.IsValidEmail(user.Email))
            {
                try
                {
                    EmailController.SendEmail(user, subject, body);
                    emailSent = true;
                }
                catch (Exception ex)
                {
                    string errorMsg = EventController.GetExceptionDetails(ex);

                    msgResult = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServer.Admin_Gallery_Settings_Test_Email_Failure_Text, errorMsg);
                }
            }
            else
            {
                msgResult = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServer.Admin_Gallery_Settings_Test_Email_Invalid_Text, user.UserName);
            }

            if (emailSent)
            {
                msgStyle  = MessageStyle.Success;
                msgResult = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServer.Admin_Gallery_Settings_Test_Email_Success_Text, user.UserName, user.Email);
            }
            else
            {
                msgStyle = MessageStyle.Error;
            }

            ClientMessage = new ClientMessageOptions
            {
                Title   = "Send Test E-mail",
                Message = msgResult,
                Style   = msgStyle
            };
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Gets an entity from the <see cref="IUserAccount" />.
        /// </summary>
        public static UserAccountEntity FromDto(IUserAccount dto)
        {
            Guard.NotNull(() => dto, dto);

            return(new UserAccountEntity
            {
                Id = EntityHelper.SerializeForStorage(dto.Id),
                Forenames = EntityHelper.SerializeForStorage(dto.Forenames),
                Surname = EntityHelper.SerializeForStorage(dto.Surname),
                Email = EntityHelper.SerializeForStorage(dto.Email),
                Username = EntityHelper.SerializeForStorage(dto.Username),
                PasswordHash = EntityHelper.SerializeForStorage(dto.PasswordHash),
                Roles = EntityHelper.SerializeForStorage(dto.Roles),
                MobilePhone = EntityHelper.SerializeForStorage(dto.MobilePhone),
                Address = EntityHelper.SerializeForStorage(dto.Address),
                IsRegistered = EntityHelper.SerializeForStorage(dto.IsRegistered),
            });
        }
        /// <summary>
        /// Deletes the <paramref name="account"/> from the store. The account must exist in the store
        /// or it will throw.
        /// </summary>
        /// <param name="account">The account to delete.</param>
        /// <returns>True if the current account was deleted, false otherwise.</returns>
        public void DeleteAccount(IUserAccount account)
        {
            string accountFilePath = GetUserAccountPath(account.AccountName);

            if (accountFilePath == null)
            {
                throw new InvalidOperationException($"Unknown account name: {account.AccountName}");
            }

            File.Delete(accountFilePath);
            bool isCurrentAccount = account.AccountName == CurrentAccount?.AccountName;

            _cachedCredentials = LoadAccounts();
            if (isCurrentAccount)
            {
                ResetCredentials(null, null);
            }
        }
Ejemplo n.º 33
0
        public static void Initialization(IUserAccount user, CancellationTokenSource cToken,
                                          IUserInteractor GUI)
        {
            if (!isInitialized)
            {
                userAccount = user;

                token = cToken;

                mainWindowGUI = GUI;

                lock (myLock)
                {
                    instance = new Server();
                }
                isInitialized = true;
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Gets the email template. Replacement parameters in the template are replaced with their appropriate values. The data
        /// in the template can be used to construct an e-mail.
        /// </summary>
        /// <param name="template">The template to retrieve.</param>
        /// <param name="user">The user associated with the template.</param>
        /// <returns>Returns an e-mail template.</returns>
        public static EmailTemplate GetEmailTemplate(EmailTemplateForm template, IUserAccount user)
        {
            EmailTemplate emailTemplate = new EmailTemplate();
            emailTemplate.EmailTemplateId = template;

            string filePath = Utils.GetPath(String.Format(CultureInfo.InvariantCulture, "/templates/{0}.txt", template));

            // Step 1: Get subject and body from text file and assign to fields.
            using (StreamReader sr = File.OpenText(filePath))
            {
                while (sr.Peek() >= 0)
                {
                    string lineText = sr.ReadLine().Trim();

                    if (lineText == "[Subject]")
                        emailTemplate.Subject = sr.ReadLine();

                    if (lineText == "[Body]")
                        emailTemplate.Body = sr.ReadToEnd();
                }
            }

            // Step 2: Update replacement parameters with real values.
            emailTemplate.Body = emailTemplate.Body.Replace("{CurrentPageUrlFull}", Utils.GetCurrentPageUrlFull());

            string userName = (user != null ? user.UserName : String.Empty);
            string email = (user != null ? user.Email : String.Empty);

            emailTemplate.Body = emailTemplate.Body.Replace("{UserName}", userName);
            emailTemplate.Body = emailTemplate.Body.Replace("{Email}", String.IsNullOrEmpty(email) ? Resources.GalleryServerPro.Email_Template_No_Email_For_User_Replacement_Text : email);

            if (emailTemplate.Body.Contains("{VerificationUrl}"))
                emailTemplate.Body = emailTemplate.Body.Replace("{VerificationUrl}", GenerateVerificationLink(userName));

            if (emailTemplate.Body.Contains("{Password}"))
                emailTemplate.Body = emailTemplate.Body.Replace("{Password}", UserController.GetPassword(userName));

            if (emailTemplate.Body.Contains("{ManageUserUrl}"))
                emailTemplate.Body = emailTemplate.Body.Replace("{ManageUserUrl}", GenerateManageUserLink(userName));

            return emailTemplate;
        }
Ejemplo n.º 35
0
 private void SetAuditProperties(AbstractPreDatabaseOperationEvent @event,  IEntityPersister persister, 
     object[] state, IUserAccount auditUser, DateTime auditDate)
 {
     foreach (var propertyPair in _auditProperties) {
     if (propertyPair.Key.Contains(ModelConstants.UPDATEDBY)) {
        propertyPair.Value.SetValue(@event.Entity, auditUser, null);
        Set(persister, state, propertyPair.Key, auditUser);
     }
     if (propertyPair.Key.Contains(ModelConstants.UPDATEDON)) {
        propertyPair.Value.SetValue(@event.Entity, auditDate, null);
        Set(persister, state, propertyPair.Key, auditDate);
     }
     if (propertyPair.Key.Contains(ModelConstants.CREATEDBY)) {
        var currentValue = (IUserAccount)propertyPair.Value.GetValue(@event.Entity, null);
        if(currentValue == null) {
           propertyPair.Value.SetValue(@event.Entity, auditUser, null);
           Set(persister, state, propertyPair.Key, auditUser);
        }
        else {
           propertyPair.Value.SetValue(@event.Entity, currentValue, null);
           Set(persister, state, propertyPair.Key, currentValue);
        }
     }
     if (propertyPair.Key.Contains(ModelConstants.CREATEDON)) {
        var currentValue = (DateTime?)propertyPair.Value.GetValue(@event.Entity, null);
        if(currentValue == null ||
           !((DateTime)currentValue).IsBetween(DateTime.Parse("1/1/1900"), DateTime.Parse("1/1/3000"))) {
           propertyPair.Value.SetValue(@event.Entity, auditDate, null);
           Set(persister, state, propertyPair.Key, auditDate);
        }
        else {
           propertyPair.Value.SetValue(@event.Entity, currentValue, null);
           Set(persister, state, propertyPair.Key, currentValue);
        }
     }
      }
 }
Ejemplo n.º 36
0
 /// <summary>
 /// Updates information about a user in the data source.
 /// </summary>
 /// <param name="user">A <see cref="IUserAccount"/> object that represents the user to update and the updated information for the user.</param>
 private static void UpdateUser(IUserAccount user)
 {
     if (UserHasBeenModified(user))
     {
         MembershipGsp.UpdateUser(ToMembershipUser(user));
     }
 }
Ejemplo n.º 37
0
        private static MembershipUser ToMembershipUser(IUserAccount u)
        {
            if (String.IsNullOrEmpty(u.UserName))
            {
                throw new ArgumentException("IUserAccount.UserName cannot be empty.");
            }

            MembershipUser user = MembershipGsp.GetUser(u.UserName, false);

            user.Comment = u.Comment;
            user.Email = u.Email;
            user.IsApproved = u.IsApproved;

            return user;
        }
Ejemplo n.º 38
0
 /// <summary>
 /// Sends an e-mail based on the <paramref name="templateForm"/> to the specified <paramref name="user"/>.
 /// No action is taken if the user's e-mail is null or empty. The e-mail is sent on a
 /// background thread, so if an error occurs on that thread no exception bubbles to the caller (the error, however, is
 /// recorded in the error log).
 /// </summary>
 /// <param name="user">The user to receive the e-mail.</param>
 /// <param name="templateForm">The template form specifying the type of e-mail to send.</param>
 public static void SendNotificationEmail(IUserAccount user, EmailTemplateForm templateForm)
 {
     SendNotificationEmail(user.UserName, user.Email, templateForm, true);
 }
Ejemplo n.º 39
0
        /// <summary>
        /// Persist the <paramref name="user"/> to the data store, including associating the specified roles with the user. The user is
        /// automatically removed from any other roles they may be a member of. Prior to saving, validation is performed and a 
        /// <see cref="GallerySecurityException"/> is thrown if a business rule would be violated.
        /// </summary>
        /// <param name="user">The user to save.</param>
        /// <param name="roles">The roles to associate with the user.</param>
        /// <exception cref="GallerySecurityException">Thrown when the user cannot be saved because doing so would violate a business rule.</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="user" /> is null.</exception>
        /// <exception cref="InvalidUserException">Thrown when the e-mail address is not valid.</exception>
        public static void SaveUser(IUserAccount user, string[] roles)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            if (roles == null)
                throw new ArgumentNullException("roles");

            ValidateSaveUser(user, roles);

            UserController.UpdateUser(user);

            var rolesForUser = RoleController.GetRolesForUser(user.UserName);
            var rolesToAdd = roles.Where(r => !rolesForUser.Contains(r)).ToArray();
            var rolesToRemove = rolesForUser.Where(r => !roles.Contains(r)).ToArray();

            RoleController.AddUserToRoles(user.UserName, rolesToAdd);
            RoleController.RemoveUserFromRoles(user.UserName, rolesToRemove);

            var addingOrDeletingRoles = ((rolesToAdd.Length > 0) || (rolesToRemove.Length > 0));

            if (addingOrDeletingRoles)
            {
                HelperFunctions.RemoveCache(CacheItem.GalleryServerRoles);
            }
        }
Ejemplo n.º 40
0
 public IEmployee Logon(int password)
 {
     var employee = Facade.Logon(password);
     _userAccount = employee.UserAccount;
     return employee;
 }
 private async Task<object> AuthenticateUser(IClientContext context, IUserAccount user, string sessionSalt,
     IAuthenticate authenticateRequest)
 {
     object response;
     if (user.IsLocked)
         response = _authenticationMessageFactory.CreateAuthenticationResult(AuthenticateReplyState.Locked, null);
     else
     {
         var serverHash = _passwordHasher.HashPassword(user.HashedPassword, sessionSalt);
         if (_passwordHasher.Compare(serverHash, authenticateRequest.AuthenticationToken))
         {
             context.ChannelData["Principal"] = await PrincipalFactory.CreatePrincipalAsync(user);
             var proof = _passwordHasher.HashPassword(user.HashedPassword, authenticateRequest.ClientSalt);
             response = _authenticationMessageFactory.CreateAuthenticationResult(AuthenticateReplyState.Success,
                 proof);
         }
         else
             response =
                 _authenticationMessageFactory.CreateAuthenticationResult(AuthenticateReplyState.IncorrectLogin,
                     null);
     }
     return response;
 }
Ejemplo n.º 42
0
        /// <summary>
        /// Sends an e-mail based on the <paramref name="templateForm"/> to the specified <paramref name="user"/>.
        /// No action is taken if the user's e-mail is null or empty. The e-mail is sent on a
        /// background thread, so if an error occurs on that thread no exception bubbles to the caller (the error, however, is
        /// recorded in the error log). If <paramref name="sendOnBackgroundThread"/> is true, the e-mail is sent on a background
        /// thread and the function returns immediately. An exception is thrown if an error occurs while sending the e-mail,
        /// unless <paramref name="sendOnBackgroundThread"/> is true, in which case the error is logged but the exception does
        /// not propagate back to the UI thread.
        /// </summary>
        /// <param name="user">The user to receive the e-mail.</param>
        /// <param name="templateForm">The template form specifying the type of e-mail to send.</param>
        /// <param name="galleryId">The gallery ID containing the e-mail configuration settings to use.</param>
        /// <param name="sendOnBackgroundThread">If set to <c>true</c> send e-mail on a background thread. This causes any errors
        /// to be silently handled by the error logging system, so if it is important for any errors to propogate to the UI,
        /// such as when testing the e-mail function in the Site Administration area, set to <c>false</c>.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="user" /> is null.</exception>
        public static void SendNotificationEmail(IUserAccount user, EmailTemplateForm templateForm, int galleryId, bool sendOnBackgroundThread)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            if (String.IsNullOrEmpty(user.Email))
                return;

            EmailTemplate emailTemplate = GetEmailTemplate(templateForm, user);

            MailAddress emailRecipient = new MailAddress(user.Email, user.UserName);

            SendEmail(emailRecipient, emailTemplate.Subject, emailTemplate.Body, galleryId, sendOnBackgroundThread);
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Sends an e-mail containing details about the <paramref name="appError" /> to the specified <paramref name="user" />. Returns
        /// <c>true</c> if the e-mail is successfully sent.
        /// </summary>
        /// <param name="appError">The application error to be sent to users.</param>
        /// <param name="user">The user to send the e-mail to.</param>
        /// <param name="gallerySettings">The gallery settings containing the e-mail configuration data.</param>
        /// <param name="emailSender">The account that that will appear in the "From" portion of the e-mail.</param>
        /// <returns>Returns <c>true</c> if the e-mail is successfully sent; otherwise <c>false</c>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="appError" />, <paramref name="user" />, 
        /// <paramref name="gallerySettings" />, or <paramref name="emailSender" /> is null.</exception>
        private static bool SendMail(IAppError appError, IUserAccount user, IGallerySettings gallerySettings, MailAddress emailSender)
        {
            #region Validation

            if (appError == null)
                throw new ArgumentNullException("appError");

            if (user == null)
                throw new ArgumentNullException("user");

            if (gallerySettings == null)
                throw new ArgumentNullException("gallerySettings");

            if (emailSender == null)
                throw new ArgumentNullException("emailSender");

            #endregion

            bool emailWasSent = false;

            if (!IsValidEmail(user.Email))
            {
                return false;
            }

            MailAddress emailRecipient = new MailAddress(user.Email, user.UserName);
            try
            {
                using (MailMessage mail = new MailMessage(emailSender, emailRecipient))
                {
                    if (String.IsNullOrEmpty(appError.ExceptionType))
                        mail.Subject = Resources.Email_Subject_When_No_Ex_Type_Present;
                    else
                        mail.Subject = String.Concat(Resources.Email_Subject_Prefix_When_Ex_Type_Present, " ", appError.ExceptionType);

                    mail.Body = appError.ToHtmlPage();
                    mail.IsBodyHtml = true;

                    using (SmtpClient smtpClient = new SmtpClient())
                    {
                        smtpClient.EnableSsl = gallerySettings.SendEmailUsingSsl;

                        // Specify SMTP server if it is specified. The server might have been assigned via web.config,
                        // so only update this if we have a config setting.
                        if (!String.IsNullOrEmpty(gallerySettings.SmtpServer))
                        {
                            smtpClient.Host = gallerySettings.SmtpServer;
                        }

                        // Specify port number if it is specified and it's not the default value of 25. The port
                        // might have been assigned via web.config, so only update this if we have a config setting.
                        int smtpServerPort;
                        if (!Int32.TryParse(gallerySettings.SmtpServerPort, out smtpServerPort))
                            smtpServerPort = int.MinValue;

                        if ((smtpServerPort > 0) && (smtpServerPort != 25))
                        {
                            smtpClient.Port = smtpServerPort;
                        }

                        smtpClient.Send(mail);
                    }

                    emailWasSent = true;
                }
            }
            catch (Exception ex2)
            {
                string errorMsg = String.Concat(ex2.GetType(), ": ", ex2.Message);

                if (ex2.InnerException != null)
                    errorMsg += String.Concat(" ", ex2.InnerException.GetType(), ": ", ex2.InnerException.Message);

                appError.ExceptionData.Add(new KeyValuePair<string, string>(Resources.Cannot_Send_Email_Lbl, errorMsg));
            }

            return emailWasSent;
        }
Ejemplo n.º 44
0
 /// <summary>
 ///     Get all roles that the specified user is a member of
 /// </summary>
 /// <param name="account">Account previously fetched using <see cref="IUserFetcher.FindUserAsync" />.</param>
 /// <returns>An array of roles (or an empty array if roles are not used)</returns>
 /// <exception cref="ArgumentException">user is not found</exception>
 /// <exception cref="ArgumentNullException">User was not supplied</exception>
 public Task<string[]> GetRolesAsync(IUserAccount account)
 {
     return Task.FromResult(new string[0]);
 }
Ejemplo n.º 45
0
 /// <summary>
 /// Sends an e-mail based on the <paramref name="templateForm"/> to the specified <paramref name="user"/>.
 /// No action is taken if the user's e-mail is null or empty. The e-mail is sent on a
 /// background thread, so if an error occurs on that thread no exception bubbles to the caller (the error, however, is
 /// recorded in the error log).
 /// </summary>
 /// <param name="user">The user to receive the e-mail.</param>
 /// <param name="templateForm">The template form specifying the type of e-mail to send.</param>
 /// <param name="galleryId">The gallery ID.</param>
 public static void SendNotificationEmail(IUserAccount user, EmailTemplateForm templateForm, int galleryId)
 {
     SendNotificationEmail(user, templateForm, galleryId, true);
 }
Ejemplo n.º 46
0
 /// <overloads>
 /// Persist the user to the data store.
 /// </overloads>
 /// <summary>
 /// Persist the <paramref name="userToSave" /> to the data store.
 /// </summary>
 /// <param name="userToSave">The user to save.</param>
 public static void SaveUser(IUserAccount userToSave)
 {
     UserController.UpdateUser(userToSave);
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Persist the <paramref name="userToSave"/> to the data store, including adding or removing the specified roles.
        /// Prior to saving, validation is performed and a <see cref="GallerySecurityException"/> is thrown if a business rule
        /// would be violated.
        /// </summary>
        /// <param name="userToSave">The user to save.</param>
        /// <param name="rolesToAdd">The roles to associate with the user. The roles should not already be associated with the
        /// user, although no harm is done if they do.</param>
        /// <param name="rolesToRemove">The roles to remove from the user.</param>
        /// <param name="galleryId">The ID of the current gallery.</param>
        /// <exception cref="GallerySecurityException">Thrown when the user cannot be saved because doing so would violate a business rule.</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="userToSave" /> is null.</exception>
        public static void SaveUser(IUserAccount userToSave, string[] rolesToAdd, string[] rolesToRemove, int galleryId)
        {
            if (userToSave == null)
                throw new ArgumentNullException("userToSave");

            ValidateSaveUser(userToSave, rolesToAdd, rolesToRemove, galleryId);

            UserController.UpdateUser(userToSave);
            RoleController.AddUserToRoles(userToSave.UserName, rolesToAdd);
            RoleController.RemoveUserFromRoles(userToSave.UserName, rolesToRemove);

            bool addingOrDeletingRoles = ((rolesToAdd != null) && (rolesToAdd.Length > 0) || (rolesToRemove != null) && (rolesToRemove.Length > 0));

            if (addingOrDeletingRoles)
            {
                HelperFunctions.RemoveCache(CacheItem.GalleryServerRoles);
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Validates the logged on user has permission to save the specified <paramref name="userToSave"/> and add/remove the user 
        /// to/from the specified <paramref name="rolesToAdd"/> and <paramref name="rolesToRemove" />. Throw a 
        /// <see cref="GallerySecurityException"/> if user is not authorized.
        /// This method assumes the logged on user is a site administrator or gallery administrator but does not verify it.
        /// </summary>
        /// <param name="userToSave">The user to save. The only property that must be specified is <see cref="IUserAccount.UserName" />.</param>
        /// <param name="rolesToAdd">The roles to be associated with the user. The roles should not already be assigned to the
        /// user, although no harm is done if they are.</param>
        /// <param name="rolesToRemove">The roles to remove from user.</param>
        /// <exception cref="GallerySecurityException">Thrown when the user cannot be saved because doing so would violate a business rule.</exception>
        public static void ValidateLoggedOnUserHasPermissionToSaveUser(IUserAccount userToSave, string[] rolesToAdd, string[] rolesToRemove)
        {
            #region Parameter validation

            if (rolesToAdd == null)
                rolesToAdd = new string[] { };

            if (rolesToRemove == null)
                rolesToRemove = new string[] { };

            #endregion

            // Enforces the following rules:
            // 1. A user with site administration permission has no restrictions. Subsequent rules do not apply.
            // 2. Gallery admin is not allowed to add admin site permission to any user or update any user that has site admin permission.
            // 3. Gallery admin cannot add or remove a user to/from a role associated with other galleries, UNLESS he is also a gallery admin
            //    to those galleries.
            // 4. NOT ENFORCED: If user to be updated is a member of roles that apply to other galleries, Gallery admin must be a gallery admin
            //    in every one of those galleries. Not enforced because this is considered acceptable behavior.

            if (Utils.IsCurrentUserSiteAdministrator())
                return;

            VerifyGalleryAdminIsNotUpdatingUserWithAdminSitePermission(userToSave, rolesToAdd);

            VerifyGalleryAdminCanAddOrRemoveRolesForUser(rolesToAdd, rolesToRemove);

            #region RULE 4 (Not enforced)
            // RULE 4: Gallery admin can update user only when he is a gallery admin in every gallery the user to be updated is a member of.

            //// Step 1: Get a list of galleries the user to be updated is associated with.
            //IGalleryCollection userGalleries = new GalleryCollection();
            //foreach (IGalleryServerRole role in RoleController.GetGalleryServerRolesForUser(userToSave.UserName))
            //{
            //  foreach (IGallery gallery in role.Galleries)
            //  {
            //    if (!userGalleries.Contains(gallery))
            //    {
            //      userGalleries.Add(gallery);
            //    }
            //  }
            //}

            //// Step 2: Validate that the current user is a gallery admin for every gallery the user to be updated is a member of.
            //foreach (IGallery userGallery in userGalleries)
            //{
            //  if (!adminGalleries.Contains(userGallery))
            //  {
            //    throw new GallerySecurityException("You are attempting to save changes to a user that affects multiple galleries, including at least one gallery you do not have permission to administer. To edit this user, you must be a gallery administrator in every gallery this user is a member of.");
            //  }
            //}
            #endregion
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Send an e-mail to the user associated with the new account. This will be a verification e-mail if e-mail verification
        /// is enabled; otherwise it is a welcome message. The calling method should ensure that the <paramref name="user"/>
        /// has a valid e-mail configured before invoking this function.
        /// </summary>
        /// <param name="user">An instance of <see cref="IUserAccount"/> that represents the newly created account.</param>
        /// <param name="galleryId">The gallery ID. This specifies which gallery to use to look up configuration settings.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="user" /> is null.</exception>
        private static void NotifyUserOfNewlyCreatedAccount(IUserAccount user, int galleryId)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            IGallerySettings gallerySetting = Factory.LoadGallerySetting(galleryId);

            bool enableEmailVerification = gallerySetting.RequireEmailValidationForSelfRegisteredUser;
            bool requireAdminApproval = gallerySetting.RequireApprovalForSelfRegisteredUser;

            if (enableEmailVerification)
            {
                EmailController.SendNotificationEmail(user, EmailTemplateForm.UserNotificationAccountCreatedNeedsVerification, galleryId);
            }
            else if (requireAdminApproval)
            {
                EmailController.SendNotificationEmail(user, EmailTemplateForm.UserNotificationAccountCreatedNeedsApproval, galleryId);
            }
            else
            {
                EmailController.SendNotificationEmail(user, EmailTemplateForm.UserNotificationAccountCreated, galleryId);
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Populates the properties of <paramref name="userToLoad" /> with information about the user. Requires that the
        /// <see cref="IUserAccount.UserName" /> property of the <paramref name="userToLoad" /> parameter be assigned a value.
        /// If no user with the specified username exists, no action is taken.
        /// </summary>
        /// <param name="userToLoad">The user account whose properties should be populated.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="userToLoad" /> is null.</exception>
        public static void LoadUser(IUserAccount userToLoad)
        {
            if (userToLoad == null)
                throw new ArgumentNullException("userToLoad");

            if (String.IsNullOrEmpty(userToLoad.UserName))
            {
                throw new ArgumentException("The UserName property of the userToLoad parameter must have a valid value. Instead, it was null or empty.");
            }

            IUserAccount user = GetUser(userToLoad.UserName, false);

            if (user != null)
            {
                user.CopyTo(userToLoad);
            }
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Send an e-mail to the users that are subscribed to new account notifications. These are specified in the
        /// <see cref="IGallerySettings.UsersToNotifyWhenAccountIsCreated" /> configuration setting. If 
        /// <see cref="IGallerySettings.RequireEmailValidationForSelfRegisteredUser" /> is enabled, do not send an e-mail at this time. 
        /// Instead, it is sent when the user clicks the confirmation link in the e-mail.
        /// </summary>
        /// <param name="user">An instance of <see cref="IUserAccount"/> that represents the newly created account.</param>
        /// <param name="isSelfRegistration">Indicates when the user is creating his or her own account. Set to false when an
        /// administrator creates an account.</param>
        /// <param name="isEmailVerified">If set to <c>true</c> the e-mail has been verified to be a valid, active e-mail address.</param>
        /// <param name="galleryId">The gallery ID storing the e-mail configuration information and the list of users to notify.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="user" /> is null.</exception>
        private static void NotifyAdminsOfNewlyCreatedAccount(IUserAccount user, bool isSelfRegistration, bool isEmailVerified, int galleryId)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            IGallerySettings gallerySettings = Factory.LoadGallerySetting(galleryId);

            if (isSelfRegistration && !isEmailVerified && gallerySettings.RequireEmailValidationForSelfRegisteredUser)
            {
                return;
            }

            EmailTemplate emailTemplate;
            if (isSelfRegistration && gallerySettings.RequireApprovalForSelfRegisteredUser)
            {
                emailTemplate = EmailController.GetEmailTemplate(EmailTemplateForm.AdminNotificationAccountCreatedRequiresApproval, user);
            }
            else
            {
                emailTemplate = EmailController.GetEmailTemplate(EmailTemplateForm.AdminNotificationAccountCreated, user);
            }

            foreach (IUserAccount userToNotify in gallerySettings.UsersToNotifyWhenAccountIsCreated)
            {
                if (!String.IsNullOrEmpty(userToNotify.Email))
                {
                    MailAddress admin = new MailAddress(userToNotify.Email, userToNotify.UserName);
                    try
                    {
                        EmailController.SendEmail(admin, emailTemplate.Subject, emailTemplate.Body, galleryId);
                    }
                    catch (WebException ex)
                    {
                        AppErrorController.LogError(ex);
                    }
                    catch (SmtpException ex)
                    {
                        AppErrorController.LogError(ex);
                    }
                }
            }
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Verifies that the specified <paramref name="userToSave" /> is not a site administrator or is being added to a site administrator
        /// role. Calling methods should invoke this function ONLY when the current user is a gallery administrator.
        /// </summary>
        /// <param name="userToSave">The user to save. The only property that must be specified is <see cref="IUserAccount.UserName" />.</param>
        /// <param name="rolesToAdd">The roles to be associated with the user. Must not be null. The roles should not already be assigned to the
        /// user, although no harm is done if they are.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="userToSave" /> or <paramref name="rolesToAdd" /> is null.</exception>
        private static void VerifyGalleryAdminIsNotUpdatingUserWithAdminSitePermission(IUserAccount userToSave, IEnumerable<string> rolesToAdd)
        {
            if (userToSave == null)
                throw new ArgumentNullException("userToSave");

            if (rolesToAdd == null)
                throw new ArgumentNullException("rolesToAdd");

            IGalleryServerRoleCollection rolesAssignedOrBeingAssignedToUser = RoleController.GetGalleryServerRolesForUser(userToSave.UserName).Copy();

            foreach (string roleToAdd in rolesToAdd)
            {
                if (rolesAssignedOrBeingAssignedToUser.GetRole(roleToAdd) == null)
                {
                    IGalleryServerRole role = Factory.LoadGalleryServerRole(roleToAdd);

                    if (role != null)
                    {
                        rolesAssignedOrBeingAssignedToUser.Add(role);
                    }
                }
            }

            foreach (IGalleryServerRole role in rolesAssignedOrBeingAssignedToUser)
            {
                if (role.AllowAdministerSite)
                {
                    throw new GallerySecurityException("You must be a site administrator to add a user to a role with Administer site permission or update an existing user who has Administer site permission. Sadly, you are just a gallery administrator.");
                }
            }
        }
Ejemplo n.º 53
0
        private void ReportSuccess(IUserAccount user)
        {
            string title = Resources.GalleryServerPro.CreateAccount_Success_Header_Text;

            string detailPendingNotification = String.Concat("<p>", Resources.GalleryServerPro.CreateAccount_Success_Detail1_Text, "</p>");
            detailPendingNotification += String.Concat(@"<p>", String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.CreateAccount_Success_Pending_Notification_Detail2_Text, user.Email), "</p>");
            detailPendingNotification += String.Concat(@"<p>", Resources.GalleryServerPro.CreateAccount_Success_Pending_Notification_Detail3_Text, "</p>");

            string detailPendingApproval = String.Concat("<p>", Resources.GalleryServerPro.CreateAccount_Success_Detail1_Text, "</p>");
            detailPendingApproval += String.Concat(@"<p>", String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.CreateAccount_Success_Pending_Approval_Detail2_Text), "</p>");
            detailPendingApproval += String.Concat(@"<p>", Resources.GalleryServerPro.CreateAccount_Success_Pending_Approval_Detail3_Text, "</p>");

            string detailActivated = String.Format(CultureInfo.InvariantCulture, @"<p>{0}</p><p><a href=""{1}"">{2}</a></p>",
                                                                                         Resources.GalleryServerPro.CreateAccount_Success_Detail1_Text,
                                                                                         Utils.GetCurrentPageUrl(),
                                                                                         Resources.GalleryServerPro.CreateAccount_Gallery_Link_Text);

            if (EnableEmailVerification)
            {
                DisplaySuccessMessage(title, detailPendingNotification);
            }
            else if (RequireAdminApproval)
            {
                DisplaySuccessMessage(title, detailPendingApproval);
            }
            else
            {
                UserController.LogOnUser(user.UserName, GalleryId);

                if (EnableUserAlbum && (UserController.GetUserAlbumId(user.UserName, GalleryId) > int.MinValue))
                {
                    detailActivated += String.Format(CultureInfo.InvariantCulture, @"<p><a href=""{0}"">{1}</a></p>",
                                                                                                                                                     Utils.GetUrl(PageId.album, "aid={0}", UserController.GetUserAlbumId(user.UserName, GalleryId)),
                                                                                                                                                     Resources.GalleryServerPro.CreateAccount_User_Album_Link_Text);
                }

                DisplaySuccessMessage(title, detailActivated);
            }

            pnlCreateUser.Visible = false;
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Validates the user can save his own account. Throws a <see cref="GallerySecurityException" /> when the action is not allowed.
        /// </summary>
        /// <param name="userToSave">The user to save.</param>
        /// <param name="rolesToRemoveFromUser">The roles to remove from user.</param>
        /// <exception cref="GallerySecurityException">Thrown when the user cannot be saved because doing so would violate a business rule.</exception>
        private static void ValidateUserCanSaveOwnAccount(IUserAccount userToSave, string[] rolesToRemoveFromUser)
        {
            // This function should be called only when the logged on person is updating their own account. They are not allowed to
            // revoke approval and they must remain in at least one role that has Administer Site or Administer Gallery permission.
            if (!userToSave.IsApproved)
            {
                throw new GallerySecurityException(Resources.GalleryServerPro.Admin_Manage_Users_Cannot_Revoke_Approval_Msg);
            }

            bool rolesAreBeingRemovedFromAccount = ((rolesToRemoveFromUser != null) && (rolesToRemoveFromUser.Length > 0));

            if (rolesAreBeingRemovedFromAccount)
            {
                bool hasAdminPermission = false;
                foreach (IGalleryServerRole galleryRole in RoleController.GetGalleryServerRolesForUser(userToSave.UserName))
                {
                    if (Array.IndexOf<string>(rolesToRemoveFromUser, galleryRole.RoleName) < 0)
                    {
                        // This is a role the user is in that is NOT being removed.
                        if (galleryRole.AllowAdministerSite || galleryRole.AllowAdministerGallery)
                        {
                            hasAdminPermission = true;
                            break;
                        }
                    }
                }

                if (!hasAdminPermission)
                {
                    throw new GallerySecurityException(Resources.GalleryServerPro.Admin_Manage_Users_Cannot_Save_User_Msg);
                }
            }
        }
 /// <summary>
 ///     Create a principal
 /// </summary>
 /// <param name="account">Account which have been authenticated</param>
 /// <returns>Principal</returns>
 /// <exception cref="InvalidOperationException">Failed to create principal using the specified account</exception>
 /// <exception cref="ArgumentNullException">account</exception>
 public async Task<IPrincipal> CreatePrincipalAsync(IUserAccount account)
 {
     if (account == null) throw new ArgumentNullException("account");
     var roles = await _fetcher.GetRolesAsync(account);
     return new GenericPrincipal(new GenericIdentity(account.UserName, "ThreeWay"), roles);
 }
Ejemplo n.º 56
0
        /// <summary>
        /// Make sure the loggod-on person has authority to save the user info and that h/she isn't doing anything stupid,
        /// like removing admin permission from his or her own account. Throws a <see cref="GallerySecurityException"/> when
        /// the action is not allowed.
        /// </summary>
        /// <param name="userToSave">The user to save.</param>
        /// <param name="rolesToAdd">The roles to associate with the user. The roles should not already be associated with the
        /// user, although no harm is done if they do.</param>
        /// <param name="rolesToRemoveFromUser">The roles to remove from user.</param>
        /// <param name="galleryId">The gallery ID.</param>
        /// <exception cref="GallerySecurityException">Thrown when the user cannot be saved because doing so would violate a business rule.</exception>
        private static void ValidateSaveUser(IUserAccount userToSave, string[] rolesToAdd, string[] rolesToRemoveFromUser, int galleryId)
        {
            if (!Utils.IsCurrentUserSiteAdministrator() && !Utils.IsCurrentUserGalleryAdministrator(galleryId))
            {
                throw new GallerySecurityException("You must be a gallery or site administrator to save changes to this user.");
            }

            if (userToSave.UserName.Equals(Utils.UserName, StringComparison.OrdinalIgnoreCase))
            {
                ValidateUserCanSaveOwnAccount(userToSave, rolesToRemoveFromUser);
            }

            ValidateLoggedOnUserHasPermissionToSaveUser(userToSave, rolesToAdd, rolesToRemoveFromUser);
        }
Ejemplo n.º 57
0
 /// <overloads>
 /// Gets the email template.
 /// </overloads>
 /// <summary>
 /// Gets the email template. Replacement parameters in the template are replaced with their appropriate values. The data
 /// in the template can be used to construct an e-mail.
 /// </summary>
 /// <param name="template">The template to retrieve.</param>
 /// <param name="user">The user associated with the template.</param>
 /// <returns>Returns an e-mail template.</returns>
 public static EmailTemplate GetEmailTemplate(EmailTemplateForm template, IUserAccount user)
 {
     return GetEmailTemplate(template, user.UserName, user.Email);
 }
Ejemplo n.º 58
0
        /// <summary>
        /// Gets a value indicating whether the <paramref name="userToSave" /> is different than the one stored in the 
        /// membership provider.
        /// </summary>
        /// <param name="userToSave">The user to persist to the membership provider.</param>
        /// <returns>A bool indicating whether the <paramref name="userToSave" /> is different than the one stored in the 
        /// membership provider.</returns>
        private static bool UserHasBeenModified(IUserAccount userToSave)
        {
            MembershipUser user = MembershipGsp.GetUser(userToSave.UserName, false);

            if (user == null)
                return true;

            bool commentEqual = ((String.IsNullOrEmpty(userToSave.Comment) && String.IsNullOrEmpty(user.Comment)) || userToSave.Comment == user.Comment);
            bool emailEqual = ((String.IsNullOrEmpty(userToSave.Email) && String.IsNullOrEmpty(user.Email)) || userToSave.Email == user.Email);
            bool isApprovedEqual = (userToSave.IsApproved == user.IsApproved);

            return (!(commentEqual && emailEqual && isApprovedEqual));
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Tries to log in an account.
        /// </summary>
        /// <param name="socket">The socket used to communicate with the client.</param>
        /// <param name="name">The name of the account.</param>
        /// <param name="password">The account password.</param>
        /// <param name="userAccount">When this method returns <see cref="AccountLoginResult.Successful"/>,
        /// contains the <see cref="IUserAccount"/> that was logged in to. Otherwise, this value will be null.</param>
        /// <returns>If <see cref="AccountLoginResult.Successful"/>, the login was successful. Otherwise, contains
        /// the reason why the login failed.</returns>
        public AccountLoginResult Login(IIPSocket socket, string name, string password, out IUserAccount userAccount)
        {
            // Try to load the account data
            var accountTable = DbController.GetQuery<SelectAccountQuery>().TryExecute(name);
            if (accountTable == null)
            {
                userAccount = null;
                return AccountLoginResult.InvalidName;
            }

            // Check the password
            var encodedPass = EncodePassword(password);
            if (!StringComparer.OrdinalIgnoreCase.Equals(encodedPass, accountTable.Password))
            {
                userAccount = null;
                return AccountLoginResult.InvalidPassword;
            }

            // Check if the account is already logged in to
            if (accountTable.CurrentIp.HasValue)
            {
                if (ServerSettings.Default.AccountDropExistingConnectionWhenInUse)
                {
                    // Kick existing user so the new connection can enter the account
                    UserAccount existingAccount;
                    lock (_accountsSync)
                    {
                        if (!_accounts.TryGetValue(name, out existingAccount))
                            existingAccount = null;
                    }

                    if (existingAccount != null)
                        existingAccount.Dispose();
                }
                else
                {
                    // Let the existing user stay connected and reject the new connection to the account
                    userAccount = null;
                    return AccountLoginResult.AccountInUse;
                }
            }

            // Try to mark the account as in use
            if (!DbController.GetQuery<TrySetAccountIPIfNullQuery>().Execute(accountTable.ID, socket.IP))
            {
                userAccount = null;
                return AccountLoginResult.AccountInUse;
            }

            // Try to add the new account to the collection
            lock (_accountsSync)
            {
                // If for some reason an account instance already exists, close it
                UserAccount existingAccount;
                if (_accounts.TryGetValue(name, out existingAccount))
                {
                    const string errmsg = "UserAccount for `{0}` already existing in _accounts collection somehow.";
                    if (log.IsErrorEnabled)
                        log.ErrorFormat(errmsg, name);
                    Debug.Fail(string.Format(errmsg, name));

                    userAccount = null;
                    return AccountLoginResult.AccountInUse;
                }

                // Create the account instance
                userAccount = new UserAccount(accountTable, socket, this);

                // Add
                _accounts.Add(name, (UserAccount)userAccount);
            }

            // Load the characters in this account
            userAccount.LoadCharacterIDs();

            // Record the login IP
            DbController.GetQuery<InsertAccountIPQuery>().Execute(userAccount.ID, socket.IP);

            return AccountLoginResult.Successful;
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Copies the current account information to the specified <paramref name="userAccount" />. The <paramref name="userAccount" />
        /// must be able to be cast to an instance of <see cref="UserAccount" />. If not, an <see cref="ArgumentNullException" />
        /// is thrown.
        /// </summary>
        /// <param name="userAccount">The user account to populate with information from the current instance.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="userAccount" /> is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="userAccount" /> cannot be cast to an instance of 
        /// <see cref="UserAccount" />.</exception>
        public void CopyTo(IUserAccount userAccount)
        {
            if (userAccount == null)
                throw new ArgumentNullException("userAccount");

            try
            {
                CopyToInstance(userAccount as UserAccount);
            }
            catch (ArgumentNullException)
            {
                throw new ArgumentOutOfRangeException("userAccount", "The parameter 'userAccount' cannot be cast to an instance of UserAccount.");
            }
        }