//private string GetUserToken(string email)
        //{
        //    return Membership.Provider.GetUser(email, false).ProviderUserKey.ToString();
        //}

        //private MembershipCreateStatus CreateUser(string userName, string password, string email)
        //{
        //    MembershipCreateStatus status;
        //    Membership.Provider.CreateUser(userName, password, email, null, null, false, null, out status);
        //    return status;
        //}

        //private string ConvertToString(object[] array)
        //{
        //    string s = string.Empty;

        //    foreach (object o in array)
        //    {
        //        s += o.ToString() + ",";
        //    }

        //    return s;
        //}

        protected override void AfterCreateBeforeCommit(CreateEventArgs e)
        {
            //System.Diagnostics.EventLog.WriteEntry("Gear", e.Values.Values.ToArray().ToString());
            //System.Threading.Thread.Sleep(5000);
            //System.Diagnostics.EventLog.WriteEntry("Gear", ConvertToString(e.Values.Values.ToArray()));
            string username  = e.Values["Email"].ToString();
            string email     = e.Values["Email"].ToString();
            string password  = e.Values["Password"].ToString();
            string firstName = e.Values["FirstName"].ToString();
            string lastName  = e.Values["LastName"].ToString();

            System.Web.Security.MembershipCreateStatus status = MembershipService.CreateUser(username, password, email, false);

            if (status == System.Web.Security.MembershipCreateStatus.Success)
            {
                System.Web.Security.Roles.AddUserToRole(username, "User");
            }
            else
            {
                e.Cancel = true;
            }
            base.AfterCreateBeforeCommit(e);

            if (e.Cancel)
            {
                throw new Exception(status.ToString());
            }
            else
            {
                SendAuthenticationEmail(email, firstName, lastName);
            }
        }
Exemple #2
0
        protected override void AfterCreateBeforeCommit(CreateEventArgs e)
        {
            string username  = e.Values["Email"].ToString();
            string email     = e.Values["Email"].ToString();
            string password  = e.Values["Password"].ToString();
            string firstName = e.Values["FirstName"].ToString();
            string lastName  = e.Values["LastName"].ToString();

            System.Web.Security.MembershipCreateStatus status = MembershipService.CreateUser(username, password, email, false);

            if (status == System.Web.Security.MembershipCreateStatus.Success)
            {
                System.Web.Security.Roles.AddUserToRole(username, "User");
            }
            else
            {
                e.Cancel = true;
            }
            base.AfterCreateBeforeCommit(e);

            if (e.Cancel)
            {
                throw new Exception(status.ToString());
            }
            else
            {
                SendAuthenticationEmail(email, firstName, lastName);
            }
        }
Exemple #3
0
        MembershipCreateStatus IMembershipManager.CreateUser(string application, string userName, string password,
                                                             string email, string passwordQuestion,
                                                             string passwordAnswer, bool isApproved)
        {
            System.Web.Security.MembershipCreateStatus status = System.Web.Security.MembershipCreateStatus.UserRejected;

            Membership.ApplicationName = application;
            Membership.CreateUser(userName, password, email, passwordQuestion, passwordAnswer, isApproved, out status);

            return((MembershipCreateStatus)status);
        }
Exemple #4
0
        protected override void AfterCreateBeforeCommit(CreateEventArgs e)
        {
            string username = e.Values["Username"].ToString();
            string email    = e.Values["Email"].ToString();

            //string tempPassword = e.Values["Password"].ToString();
            string tempPassword;

            if (e.Values.ContainsKey("Password"))
            {
                tempPassword = e.Values["Password"].ToString();
            }
            else
            {
                tempPassword = GetRandomPassword((View)e.View);
                //e.Values.Add("Password", tempPassword);
            }
            System.Web.Security.MembershipCreateStatus status = CreateUser(username, tempPassword, email);

            if (status == MembershipCreateStatus.Success)
            {
                string role = GetRole(e.Values);
                if (String.IsNullOrEmpty(role))
                {
                    System.Web.Security.Membership.Provider.DeleteUser(username, true);
                    throw new DuradosException(Map.Database.Localizer.Translate("Failed to create user, Role is missing"));
                }
                System.Web.Security.Roles.AddUserToRole(username, role);

                if (e.Values.ContainsKey("IsApproved"))
                {
                    bool isApproved = Convert.ToBoolean(e.Values["IsApproved"].ToString());

                    if (!isApproved)
                    {
                        System.Web.Security.MembershipUser user = System.Web.Security.Membership.Provider.GetUser(username, true);
                        user.IsApproved = false;
                        System.Web.Security.Membership.UpdateUser(user);
                    }
                }

                base.AfterCreateBeforeCommit(e);
            }
            else
            {
                e.Cancel = true;
            }

            if (e.Cancel)
            {
                throw new DuradosException(ErrorCodeToString(status));
            }
        }
Exemple #5
0
 /// <summary>
 /// Adds a new membership user to the data source.
 /// </summary>
 /// <param name="username">The user name for the new user.</param>
 /// <param name="password">The password for the new user.</param>
 /// <param name="email">The e-mail address for the new user.</param>
 /// <param name="passwordQuestion">The password question for the new user.</param>
 /// <param name="passwordAnswer">The password answer for the new user</param>
 /// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
 /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
 /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus" /> enumeration value indicating whether the user was created successfully.</param>
 /// <returns>
 /// A <see cref="T:System.Web.Security.MembershipUser" /> object populated with the information for the newly created user.
 /// </returns>
 /// <exception cref="System.NotImplementedException"></exception>
 public override System.Web.Security.MembershipUser CreateUser(
     string username,
     string password,
     string email,
     string passwordQuestion,
     string passwordAnswer,
     bool isApproved,
     object providerUserKey,
     out System.Web.Security.MembershipCreateStatus status)
 {
     throw new System.NotImplementedException();
 }
Exemple #6
0
        public void Register_Should_Fail_If_Provider_Create_Fails(System.Web.Security.MembershipCreateStatus createStatus, string error)
        {
            var mockProvider = new Mock<MembershipProvider>();
             MembershipUser mockUser = null; //new Mock<MembershipUser>();
            //CreateUser on error return null
            mockProvider.Setup(m => m.CreateUser(username, password, email, securityQuestion, securityAnswer, true, null, out createStatus))
                .Returns(()=> mockUser);
            var mockFormsAuthentication = new Mock<IFormsAuthentication>();
            mockFormsAuthentication.Setup(m => m.SetAuthCookie(username, false));

            var ac = new AccountController(mockProvider.Object, mockFormsAuthentication.Object);
            var result = ac.Register(username, email, password, securityQuestion, securityAnswer);

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(ActionResult));
            ac.ViewData.ModelState.AssertErrorMessage("provider", error);
            mockProvider.VerifyAll();
        }
Exemple #7
0
        protected override void AfterCreateBeforeCommit(CreateEventArgs e)
        {
            string username     = e.Values["Username"].ToString();
            string email        = e.Values["Email"].ToString();
            string tempPassword = "******";

            System.Web.Security.MembershipCreateStatus status = CreateUser(username, tempPassword, email);
            System.Web.Security.Roles.AddUserToRole(username, "User");

            if (status != System.Web.Security.MembershipCreateStatus.Success)
            {
                e.Cancel = true;
            }
            base.AfterCreateBeforeCommit(e);

            if (e.Cancel)
            {
                throw new Exception(status.ToString());
            }
        }
Exemple #8
0
        protected void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            this.Membership = System.Web.Security.Membership.Provider;
            int totalUsers = -1;

            if (Membership != null)
            {
                var user = Membership.GetAllUsers(0, 1, out totalUsers);

                if (user == null)
                {
                    var membershipStatus = new System.Web.Security.MembershipCreateStatus();
                    this.Membership.CreateUser("Kingsley", "@gmail.com", "@gmail.com", "What is my first name", "KIngsley",
                                               true, null, out membershipStatus);
                }
            }
        }
        private static string ErrorCodeToString(System.Web.Security.MembershipCreateStatus createStatus)
        {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes.
            switch (createStatus)
            {
            case MembershipCreateStatus.DuplicateUserName:
                return("Username already exists. Please enter a different user name.");

            case MembershipCreateStatus.DuplicateEmail:
                return("A username for that e-mail address already exists. Please enter a different e-mail address.");

            case MembershipCreateStatus.InvalidPassword:
                return("The password provided is invalid. Please enter a valid password value.");

            case MembershipCreateStatus.InvalidEmail:
                return("The e-mail address provided is invalid. Please check the value and try again.");

            case MembershipCreateStatus.InvalidAnswer:
                return("The password retrieval answer provided is invalid. Please check the value and try again.");

            case MembershipCreateStatus.InvalidQuestion:
                return("The password retrieval question provided is invalid. Please check the value and try again.");

            case MembershipCreateStatus.InvalidUserName:
                return("The user name provided is invalid. Please check the value and try again.");

            case MembershipCreateStatus.ProviderError:
                return
                    ("The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.");

            case MembershipCreateStatus.UserRejected:
                return
                    ("The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.");

            default:
                return
                    ("An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.");
            }
        }
Exemple #10
0
        /// <summary>
        /// Crea un usuario
        /// </summary>
        /// <param name="userName">Nombre de usuario, nombre de logging</param>
        /// <param name="password">Clave</param>
        /// <param name="email">Correo electronico</param>
        /// <param name="passwordQuestion">Pregunta secreta</param>
        /// <param name="passwordAnswer">Respuesta secreta</param>
        /// <param name="isApproved">True si esta aprovado </param>
        /// <param name="pStatus"><see cref="MembershipCreateStatus"/></param>
        /// <param name="providerName">Nombre del proveedor de membership</param>
        /// <returns><see cref="User"/></returns>
        public static User CreateUser(string userName,
                                      string password,
                                      string email,
                                      string passwordQuestion,
                                      string passwordAnswer,
                                      Boolean isApproved,
                                      out System.Web.Security.MembershipCreateStatus pStatus,
                                      string providerName)
        {
            SqlMembershipProvider wProvider = GetSqlMembershipProvider(providerName);

            User wUsuario = null;

            System.Web.Security.MembershipUser newUser = wProvider.CreateUser(userName, password, email, passwordQuestion, passwordAnswer, isApproved, Guid.NewGuid(), out pStatus);


            if (newUser != null)
            {
                wUsuario = new User(newUser);
            }


            return(wUsuario);
        }
Exemple #11
0
 public System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
 {
     return(membershipProvider.CreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status));
 }
Exemple #12
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            MembershipUser            result = null;
            ValidatePasswordEventArgs args   = new ValidatePasswordEventArgs(username, password, true);

            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
            }
            else if (GetUserNameByEmail(email) != string.Empty)
            {
                status = MembershipCreateStatus.DuplicateEmail;
            }
            else
            {
                MembershipUser user = GetUser(username, false);
                if (user == null)
                {
                    string passwordSalt   = PasswordHelper.CreatePasswordSalt(PasswordHelper.DEFAULT_SALT_SIZE);
                    string hashedPassword = PasswordHelper.CreatePasswordHash(password, passwordSalt);

                    User userData = new User();
                    //userData.FirstName = passwordQuestion;
                    //userData.LastName = passwordAnswer;
                    userData.Username     = username;
                    userData.EmailAddress = email;
                    userData.Password     = hashedPassword;
                    userData.PasswordSalt = passwordSalt;
                    userData.IsApproved   = isApproved;
                    userData.IsLockedOut  = false;
                    userData.IsOnline     = false;
                    userData.CreateDate   = DateTime.Now;

                    User userReturn;
                    using (_unitOfWork)
                    {
                        userReturn = _userRepository.Insert(userData);
                    }

                    if (userReturn != null)
                    {
                        status = MembershipCreateStatus.Success;
                    }
                    else
                    {
                        status = MembershipCreateStatus.UserRejected;
                    }

                    result = GetUser(username, false);
                }
                else
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                }
            }

            return(result);
        }
Exemple #13
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            bool createInactive = true;

            using (var db = new ClimbingContext())
            {
                if (db.UserProfiles.Count(u => u.Name.Equals(username, StringComparison.OrdinalIgnoreCase)) > 0)
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                    return(null);
                }
                if (String.IsNullOrEmpty(password))
                {
                    password = Membership.GeneratePassword(minRequiredPasswordLength + 10, minRequiredNonAlphanumericCharacters + 1);
                }
                else
                {
                    ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);
                    OnValidatingPassword(args);
                    if (args.Cancel)
                    {
                        status = MembershipCreateStatus.InvalidPassword;
                        return(null);
                    }
                }
                if (String.IsNullOrEmpty(email))
                {
                    status = MembershipCreateStatus.InvalidEmail;
                    return(null);
                }
                if (requiresUniqueEmail && db.UserProfiles.Count(u => u.Email.Equals(email, StringComparison.OrdinalIgnoreCase)) > 0)
                {
                    status = MembershipCreateStatus.DuplicateEmail;
                    return(null);
                }
                try
                {
                    string token = null;
                    if (createInactive)
                    {
                        do
                        {
                            token = GenerateToken();
                        }while (db.UserProfiles.Count(p => p.Token.Equals(token, StringComparison.InvariantCultureIgnoreCase)) > 0);
                    }
                    var upm = db.UserProfiles.Create();
                    upm.Name = username;
                    upm.SetPassword(password);
                    upm.Email    = email;
                    upm.Inactive = createInactive;
                    upm.Token    = token;
                    upm.PasswordTokenExpirationTime = null;
                    db.UserProfiles.Add(upm);
                    db.SaveChanges();
                    status = MembershipCreateStatus.Success;
                    return(GetUser(username, false));
                }
                catch
                {
                    status = MembershipCreateStatus.ProviderError;
                    return(null);
                }
            }
        }
Exemple #14
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            if (!ValidateParameter(ref password, true, true, false, 128))
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }

            var salt = GenerateSalt();
            var pass = EncodePassword(password, (int)passwordFormat, salt);

            if (pass.Length > 128)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }

            string encodedPasswordAnswer;

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

            if (!string.IsNullOrEmpty(passwordAnswer))
            {
                if (passwordAnswer.Length > 128)
                {
                    status = MembershipCreateStatus.InvalidAnswer;
                    return(null);
                }
                encodedPasswordAnswer = EncodePassword(passwordAnswer.ToLower(CultureInfo.InvariantCulture), (int)passwordFormat, salt);
            }
            else
            {
                encodedPasswordAnswer = passwordAnswer;
            }

            if (!ValidateParameter(ref encodedPasswordAnswer, RequiresQuestionAndAnswer, true, false, 128))
            {
                status = MembershipCreateStatus.InvalidAnswer;
                return(null);
            }

            if (!ValidateParameter(ref username, true, true, true, 256))
            {
                status = MembershipCreateStatus.InvalidUserName;
                return(null);
            }

            if (!ValidateParameter(ref email,
                                   RequiresUniqueEmail,
                                   RequiresUniqueEmail,
                                   false,
                                   256))
            {
                status = MembershipCreateStatus.InvalidEmail;
                return(null);
            }

            if (!ValidateParameter(ref passwordQuestion, RequiresQuestionAndAnswer, true, false, 256))
            {
                status = MembershipCreateStatus.InvalidQuestion;
                return(null);
            }

            if (providerUserKey != null)
            {
                //if (!(providerUserKey is Guid)) {
                //    status = MembershipCreateStatus.InvalidProviderUserKey;
                //    return null;
                //}
                status = MembershipCreateStatus.InvalidProviderUserKey;
                return(null);
            }

            if (password.Length < MinRequiredPasswordLength)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }

            int count = 0;

            for (int i = 0; i < password.Length; i++)
            {
                if (!char.IsLetterOrDigit(password, i))
                {
                    count++;
                }
            }

            if (count < MinRequiredNonAlphanumericCharacters)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }

            if (PasswordStrengthRegularExpression.Length > 0)
            {
                if (!Regex.IsMatch(password, PasswordStrengthRegularExpression))
                {
                    status = MembershipCreateStatus.InvalidPassword;
                    return(null);
                }
            }


            ValidatePasswordEventArgs e = new ValidatePasswordEventArgs(username, password, true);

            OnValidatingPassword(e);

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

            using (var db = new NotificatorEntities())
            {
                if (RequiresUniqueEmail)
                {
                    if (db.Users.Where(u => u.Email == email && u.Application.Id == applicationId).Any())
                    {
                        status = MembershipCreateStatus.DuplicateEmail;
                        return(null);
                    }
                }

                if (db.Users.Where(u => u.Username == username && u.Application.Id == applicationId).Any())
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                    return(null);
                }

                var utc  = DateTime.UtcNow;
                var user = new User()
                {
                    Comment  = "",
                    CreateOn = utc,
                    Email    = email,
                    FailedPasswordAnswerAttemptCount       = 0,
                    FailedPasswordAnswerAttemptWindowStart = utc,
                    FailedPasswordAttemptCount             = 0,
                    FailedPasswordAttemptWindowStart       = utc,
                    IsAnonymous             = false,
                    IsApproved              = isApproved,
                    LastActivityDate        = utc,
                    LastLockoutDate         = utc,
                    LastLoginDate           = utc,
                    LastPasswordChangedDate = utc,
                    Password         = pass,
                    PasswordAnswer   = encodedPasswordAnswer,
                    PasswordFormat   = (int)PasswordFormat,
                    PasswordQuestion = passwordQuestion,
                    PasswordSalt     = salt,
                    TimeZone         = 0,
                    Username         = username,
                    Application      = db.GetApplication(applicationId)
                };

                db.Users.AddObject(user);
                try
                {
                    db.SaveChanges();
                }
                catch
                {
                    status = MembershipCreateStatus.UserRejected;
                    return(null);
                }

                status = MembershipCreateStatus.Success;
                return(UserMapper.Map(this.Name, user));
            }
        }
        /// <summary>
        /// Need to override because the underlying class doesn't allow us to specify an id for member, always generates one which doesn't work for our unit tests.
        /// </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 System.Web.Security.MembershipCreateStatus status)
        {
            if (username == null)
            {
                throw new ArgumentNullException("username");
            }
            try
            {
                if (!this.VerifyUserIsValid(providerUserKey, username, password, email, passwordQuestion, passwordAnswer, out status))
                {
                    return(null);
                }
                var dateTime = this.UseUniversalTime ? DateTime.UtcNow : DateTime.Now;
                var salt     = string.Empty;
                var str      = this.EncodePassword(password, ref salt);
                var user     = new XmlUser()
                {
                    //NOTE: this is the fix, have lodged a bug here: http://tinyproviders.codeplex.com/workitem/3
                    UserKey = providerUserKey == null?Guid.NewGuid() : (Guid)providerUserKey,

                                  UserName               = username,
                                  PasswordSalt           = salt,
                                  Password               = str,
                                  Email                  = email,
                                  PasswordQuestion       = passwordQuestion,
                                  PasswordAnswer         = passwordAnswer,
                                  IsApproved             = isApproved,
                                  CreationDate           = dateTime,
                                  LastActivityDate       = dateTime,
                                  LastPasswordChangeDate = dateTime
                };
                lock (SyncRoot)
                {
                    this.Store.Users.Add(user);
                    this.Store.Save();
                }
                return(this.CreateMembershipFromInternalUser(user));
            }
            catch
            {
                throw;
            }
        }
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);

            OnValidatingPassword(args);
            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }
            if (RequiresUniqueEmail && !string.IsNullOrEmpty(GetUserNameByEmail(email)))
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return(null);
            }
            MembershipUser user = GetUser(username, true);

            if (user == null)
            {
                CommandServiceClient commandService = new CommandServiceClient();
                commandService.RegisterUserAccount(username, password, username, email, "", new AddressDataObject {
                    City = "", Country = "", State = "", Street = "", Zip = ""
                });
                commandService.Close();
                //Thread.Sleep(6000); // Wait for the synchronization service to sync the event message to query database.
                status = MembershipCreateStatus.Success;
                return(GetUser(username, true));
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return(null);
            }
        }
Exemple #17
0
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            status = MembershipCreateStatus.Success;
            var user = this.CreateUser(username, password);

            return(new MembershipUser("CustomMembershipProvider", user.Email, null, null, null, null,
                                      false, false, DateTime.Now, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue));
        }
Exemple #18
0
 public static System.Web.Security.MembershipUser CreateUser(this System.Web.Security.MembershipProvider pProvider, String pUserName, String pPassword, String pPostalAddress, String pEmail, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
 {
     try
     {
         User lUser = new User()
         {
             Address = pPostalAddress, Name = pUserName, LoginCredential = new LoginCredential()
             {
                 UserName = pUserName, Password = pPassword
             }, Email = pEmail
         };
         MembershipProvider.CreateUser(lUser);
         status = MembershipCreateStatus.Success;
     }
     catch (Exception)
     {
         status = MembershipCreateStatus.ProviderError;
     }
     return(new MembershipUser("VideoStoreMembershipProvider", pUserName, null, pEmail, null, null, true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.MinValue));
 }
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            if (String.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Value cannot be null or empty.", "userName");
            }
            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Value cannot be null or empty.", "password");
            }
            if (String.IsNullOrEmpty(email))
            {
                throw new ArgumentException("Value cannot be null or empty.", "email");
            }

            int count;

            FindUsersByName(username, 0, 1, out count);
            if (count == 0)
            {
                FindUsersByEmail(email, 0, 1, out count);
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return(null);
            }

            if (count == 0)
            {
                var     application = Subscription.GetApplicationInformation();
                Contact contact     = providerUserKey as Contact;
                if (contact == null)
                {
                    status = MembershipCreateStatus.UserRejected;
                    return(null);
                }

                User user = new User
                {
                    email            = email,
                    userName         = username,
                    createDate       = DateTime.Now,
                    isAnonymous      = false,
                    isConfirmed      = false,
                    isLockedOut      = false,
                    lastActivityDate = DateTime.Now,
                    passwordFormat   = ((int)PasswordFormat) + 1,
                    passwordSalt     = Guid.NewGuid().ToString(),
                    password         = password.GetMD5HashCode(),
                    passwordQuestion = passwordQuestion,
                    passwordAnswer   = passwordAnswer,
                    enabled          = true
                };

                Repository.Add(user);
                status = System.Web.Security.MembershipCreateStatus.Success;
                return(new System.Web.Security.MembershipUser(this.Name, username, contact, email, passwordQuestion, user.comment, user.isConfirmed, user.isLockedOut, user.createDate, user.lastLoginDate, user.lastActivityDate, user.lastPasswordChangedDate, user.lastLockoutDate));
            }
            else
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return(null);
            }
        }
        private void btnLuu_Click(object sender, EventArgs e)
        {
            UserName = this.txtUsername.Text;
            if (UserName == string.Empty || FormStatus == FormUpdate.Insert)//Thêm mới người dùng
            {
                System.Web.Security.MembershipCreateStatus mcs = new System.Web.Security.MembershipCreateStatus();
                try
                {
                    if (txtUsername.Text == string.Empty)
                    {
                        MessageBox.Show("Tên đăng nhập không được để trống");
                        txtUsername.Focus();
                        return;
                    }
                    if (txtPassWord.Text == string.Empty)
                    {
                        MessageBox.Show("Mật khẩu không được để trống");
                        txtPassWord.Focus();
                        return;
                    }
                    if (txtThuDienTu.Text == string.Empty)
                    {
                        MessageBox.Show("Địa chỉ hòm thư không được để trống");
                        txtThuDienTu.Focus();
                        return;
                    }
                    System.Web.Security.Membership.CreateUser(txtUsername.Text, txtPassWord.Text, txtThuDienTu.Text, "Who are you?", "It's me", true, out mcs);
                    System.Web.Security.MembershipUser u = System.Web.Security.Membership.GetUser(txtUsername.Text);

                    u.IsApproved = true;
                    System.Web.Security.Membership.UpdateUser(u);
                }
                catch
                {
                    if (mcs == System.Web.Security.MembershipCreateStatus.DuplicateUserName)
                    {
                        MessageBox.Show("Tên đăng nhập đã tồn tại!");
                    }
                    if (mcs == System.Web.Security.MembershipCreateStatus.InvalidPassword)
                    {
                        MessageBox.Show("Mật khẩu phải từ 7 kí tự và chứa kí tự đặc biệt!");
                    }
                }
            }
            else//Sửa thông tin người dùng
            {
                System.Web.Security.MembershipUser         u   = System.Web.Security.Membership.GetUser(txtUsername.Text);
                System.Web.Security.MembershipCreateStatus mcs = new System.Web.Security.MembershipCreateStatus();
                //oldPass = u.GetPassword();
                //u.ChangePassword(oldPass, txtMatKhau.Text);

                if (txtPassWord.Text != string.Empty && txtRePass.Text != string.Empty && txtRePass.Visible == true)
                {
                    //string password = u.ResetPassword()
                    //u.ChangePassword(txtPassWord.Text, txtRePass.Text);
                    System.Web.Security.Membership.DeleteUser(u.UserName);
                    MessageBox.Show("Đồi mật khẩu thành công!");
                }
                else
                {
                    MessageBox.Show("Cần nhập mật khẩu cũ và mật khẩu mới");
                    txtPassWord.Focus();
                    return;
                }
                System.Web.Security.Membership.CreateUser(txtUsername.Text, txtRePass.Text, txtThuDienTu.Text, "Who are you?", "It's me", true, out mcs);
                System.Web.Security.MembershipUser new_user = System.Web.Security.Membership.GetUser(txtUsername.Text);
                new_user.Email      = txtThuDienTu.Text;
                new_user.IsApproved = true;
                System.Web.Security.Membership.UpdateUser(new_user);
            }
            FormStatus = FormUpdate.View;
            SetStatus(FormStatus);
            BindData();
        }
Exemple #21
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            DataAccess.Identity identity = null;

            var connect = new Connect();

            using (var db = new DataAccess.CSSDataContext())
            {
                if (DataAccess.Login.FindLoginByUsernameOrCallsign(db, username) != null)
                {
                    status = System.Web.Security.MembershipCreateStatus.DuplicateUserName;
                    return(null);
                }

                if (DataAccess.Alias.ListAliases(db, username).Count > 0)
                {
                    status = System.Web.Security.MembershipCreateStatus.UserRejected;
                    return(null);
                }

                if (Settings.Default.UseIPConverge == true)
                {
                    if (connect.CheckEmail(email) == false)
                    {
                        status = MembershipCreateStatus.DuplicateEmail;
                        return(null);
                    }

                    if (connect.CheckUsername(username) == false)
                    {
                        status = MembershipCreateStatus.DuplicateUserName;
                        return(null);
                    }
                }

                status = DataAccess.Identity.TryCreateIdentity(db, username, password, email, out identity);

                if (status == MembershipCreateStatus.Success)
                {
                    if (Settings.Default.UseIPConverge == true)
                    {
                        string ipAddress = "127.0.0.1";
                        if (HttpContext.Current != null)
                        {
                            ipAddress = HttpContext.Current.Request.UserHostAddress;
                        }

                        // TODO: If IP Converge is to be used ever, then working around IPC's MD5 password hashs will need to be done.
                        //if (connect.AddMember(email, username, passwordHash, ipAddress) == false)
                        //{
                        //    status = MembershipCreateStatus.ProviderError;
                        //    return null;
                        //}
                    }
                }

                db.SubmitChanges();

                if (identity != null)
                {
                    DataAccess.Login createdLogin = DataAccess.Login.FindLoginByUsernameOrCallsign(db, username);

                    if (createdLogin != null)
                    {
                        status = System.Web.Security.MembershipCreateStatus.Success;
                        var memebershipUser = MembershipUserUtility.CreateMembershipUserFromLogin(createdLogin);

                        if (memebershipUser != null)
                        {
                            SendWelcomeEmail(memebershipUser);
                        }

                        return(memebershipUser);
                    }
                }
            }

            status = System.Web.Security.MembershipCreateStatus.ProviderError;
            return(null);
        }
Exemple #22
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            BuildingEntities db;
            User             user;
            int count;

            System.Web.Security.MembershipUser result = null;
            status = System.Web.Security.MembershipCreateStatus.Success;

            using (db = new BuildingEntities())
            {
                count = db.Users.Where(val => val.Login.ToLower() == username.ToLower() && !val.Deleted).Count();

                if (count > 0)
                {
                    status = System.Web.Security.MembershipCreateStatus.DuplicateUserName;
                }
                else
                {
                    user            = new User();
                    user.Login      = username;
                    user.Password   = password.ToSha1Base64String();
                    user.Name       = string.Empty;
                    user.Surname    = string.Empty;
                    user.Patronymic = string.Empty;
                    db.Users.AddObject(user);
                    db.SaveChanges();
                    result = ConvertUser(user);
                }
            }
            return(result);
        }
        public bool SaveUserFile(Model.Boloes.Bolao bolao, Model.Campeonatos.Campeonato campeonato, Framework.Security.Model.UserData user)
        {
            if (bolao == null)
            {
                throw new ArgumentException("bolao");
            }

            if (campeonato == null)
            {
                throw new ArgumentException("campeonato");
            }

            if (user == null)
            {
                throw new ArgumentException("user");
            }

            #region Buscando os jogos cadastrados do bolão
            //Loading jogos stored
            Business.Campeonatos.Support.Campeonato businessCampeonato =
                new Business.Campeonatos.Support.Campeonato(_currentLogin, campeonato);

            IList <Framework.DataServices.Model.EntityBaseData> listJogos =
                businessCampeonato.LoadJogos(0, null, null, DateTime.MinValue, DateTime.MinValue, null);


            if (listJogos.Count != 64)
            {
                throw new Exception("Não existem a quantidade determinada de jogos cadastradas no banco");
            }
            #endregion

            #region Buscando os dados do arquivo Excel
            //Loading jogos from Excel file
            List <Model.Boloes.JogoUsuario> jogosUsuario = new List <BolaoNet.Model.Boloes.JogoUsuario>();
            jogosUsuario = _daoTemplate.LoadJogosUsuario(_dao.CreateConnection(_file));

            if (jogosUsuario.Count != 64)
            {
                throw new Exception("Não existem a quantidade de apostas cadastradas no excel.");
            }



            List <Model.Boloes.JogoUsuario> result = new List <BolaoNet.Model.Boloes.JogoUsuario>();


            //Setting apostas dos usuários into jogos
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[0], jogosUsuario[0]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[1], jogosUsuario[1]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[2], jogosUsuario[7]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[3], jogosUsuario[6]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[4], jogosUsuario[12]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[5], jogosUsuario[13]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[6], jogosUsuario[19]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[7], jogosUsuario[18]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[8], jogosUsuario[24]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[9], jogosUsuario[25]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[10], jogosUsuario[30]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[11], jogosUsuario[31]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[12], jogosUsuario[36]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[13], jogosUsuario[37]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[14], jogosUsuario[42]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[15], jogosUsuario[43]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[16], jogosUsuario[2]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[17], jogosUsuario[9]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[18], jogosUsuario[8]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[19], jogosUsuario[3]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[20], jogosUsuario[20]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[21], jogosUsuario[14]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[22], jogosUsuario[15]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[23], jogosUsuario[26]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[24], jogosUsuario[21]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[25], jogosUsuario[27]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[26], jogosUsuario[32]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[27], jogosUsuario[33]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[28], jogosUsuario[38]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[29], jogosUsuario[39]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[30], jogosUsuario[44]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[31], jogosUsuario[45]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[32], jogosUsuario[4]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[33], jogosUsuario[5]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[34], jogosUsuario[10]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[35], jogosUsuario[11]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[36], jogosUsuario[16]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[37], jogosUsuario[17]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[38], jogosUsuario[22]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[39], jogosUsuario[23]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[40], jogosUsuario[34]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[41], jogosUsuario[35]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[42], jogosUsuario[28]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[43], jogosUsuario[29]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[44], jogosUsuario[40]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[45], jogosUsuario[41]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[46], jogosUsuario[46]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[47], jogosUsuario[47]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[48], jogosUsuario[48]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[49], jogosUsuario[49]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[50], jogosUsuario[51]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[51], jogosUsuario[50]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[52], jogosUsuario[52]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[53], jogosUsuario[53]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[54], jogosUsuario[54]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[55], jogosUsuario[55]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[56], jogosUsuario[57]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[57], jogosUsuario[56]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[58], jogosUsuario[58]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[59], jogosUsuario[59]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[60], jogosUsuario[60]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[61], jogosUsuario[61]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[62], jogosUsuario[62]));
            result.Add(SetValue((Model.Campeonatos.Jogo)listJogos[63], jogosUsuario[63]));
            #endregion

            #region Criando o usuário
            Framework.Security.Business.UserDataService userBusiness = new Framework.Security.Business.UserDataService(_currentLogin, user);
            System.Web.Security.MembershipCreateStatus  status       = userBusiness.CreateUser();

            switch (status)
            {
            case MembershipCreateStatus.DuplicateEmail:
                throw new Exception("O email especificado já existe cadastrado para um usuário, por favor, entre com outro email.");

            case MembershipCreateStatus.DuplicateProviderUserKey:
                throw new Exception("O usuário já existe no banco de dados, por favor, entre com outro.");

            case MembershipCreateStatus.DuplicateUserName:
                throw new Exception("O login do usuário já existe no banco de dados, por favor, entre com outro login.");

            case MembershipCreateStatus.InvalidAnswer:
                throw new Exception("Resposta inválida, por favor entre com uma resposta que atenda aos requisitos de segurança.");

            case MembershipCreateStatus.InvalidEmail:
                throw new Exception("Formato de email incorreto.");

            case MembershipCreateStatus.InvalidPassword:
                throw new Exception("Senha inválida, por favor entre com uma senha que atenda aos requisitos de segurança.");

            case MembershipCreateStatus.InvalidProviderUserKey:
                throw new Exception("Chave do usuário inválida.");

            case MembershipCreateStatus.InvalidQuestion:
                throw new Exception("Pergunta inválida, por favor entre com uma pergunta que atenda aos requisitos de segurança.");

            case MembershipCreateStatus.InvalidUserName:
                throw new Exception("Usuário inválido.");

            case MembershipCreateStatus.ProviderError:
                throw new Exception("Erro de provider.");

            case MembershipCreateStatus.UserRejected:
                throw new Exception("Usuário rejeitado.");

            case MembershipCreateStatus.Success:
                break;
            }

            if (!userBusiness.UpdateUser())
            {
                throw new Exception("Erro ao atualizar o usuário.");
            }


            #endregion

            Business.Boloes.Support.Bolao bolaoBusiness = new BolaoNet.Business.Boloes.Support.Bolao(_currentLogin, bolao.Nome);


            #region Adicionando as Roles para o usuário
            string rolesToAdd = ConfigurationManager.AppSettings["RolesToAddAtConfirmation"];

            if (rolesToAdd != null)
            {
                string[] roles = rolesToAdd.Split(new char[] { '|' });

                System.Web.Security.Roles.AddUserToRoles(user.UserName, roles);
            }
            #endregion


            #region Adicionando o usuário no bolão determinado

            bool insertedMember = bolaoBusiness.InsertMembro(user);

            if (!insertedMember)
            {
                throw new Exception("Não foi possível inserir o usuário no bolão " + bolao.Nome);
            }

            #endregion


            #region Inserindo jogos do usuário

            foreach (Model.Boloes.JogoUsuario jogoUsuario in result)
            {
                Business.Boloes.Support.JogoUsuario apostaUsuario = new BolaoNet.Business.Boloes.Support.JogoUsuario(_currentLogin, jogoUsuario);
                apostaUsuario.UserName = user.UserName;
                apostaUsuario.Bolao    = bolao;
                apostaUsuario.Time1    = jogoUsuario.Time1;
                apostaUsuario.Time2    = jogoUsuario.Time2;
                apostaUsuario.Insert();
            }


            #endregion


            #region Inserindo apostas extras

            string[] extras = new string[4];

            //Primeiro Lugar
            if (result[63].ApostaTime1 > result[63].ApostaTime2)
            {
                extras[0] = result[63].Time1.Nome;
                extras[1] = result[63].Time2.Nome;
            }
            else
            {
                extras[0] = result[63].Time2.Nome;
                extras[1] = result[63].Time1.Nome;
            }

            //Terceiro Lugar
            if (result[62].ApostaTime1 > result[62].ApostaTime2)
            {
                extras[2] = result[62].Time1.Nome;
                extras[3] = result[62].Time2.Nome;
            }
            else
            {
                extras[2] = result[62].Time2.Nome;
                extras[3] = result[62].Time1.Nome;
            }

            for (int c = 0; c < 4; c++)
            {
                if (string.Compare(extras[c], "Suiça") == 0)
                {
                    extras[c] = "Suíça";
                }
            }


            //Primeiro lugar
            Business.Boloes.Support.ApostaExtraUsuario businessExtra =
                new BolaoNet.Business.Boloes.Support.ApostaExtraUsuario(_currentLogin, 1, bolao.Nome, user.UserName);
            businessExtra.NomeTime = extras[0];
            businessExtra.Insert();

            //Segundo Lugar
            businessExtra          = new BolaoNet.Business.Boloes.Support.ApostaExtraUsuario(_currentLogin, 2, bolao.Nome, user.UserName);
            businessExtra.NomeTime = extras[1];
            businessExtra.Insert();

            //Terceiro Lugar
            businessExtra          = new BolaoNet.Business.Boloes.Support.ApostaExtraUsuario(_currentLogin, 3, bolao.Nome, user.UserName);
            businessExtra.NomeTime = extras[2];
            businessExtra.Insert();

            //Quarto Lugar
            businessExtra          = new BolaoNet.Business.Boloes.Support.ApostaExtraUsuario(_currentLogin, 4, bolao.Nome, user.UserName);
            businessExtra.NomeTime = extras[3];
            businessExtra.Insert();

            #endregion



            return(true);
        }
Exemple #24
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            if (_repository.Users.FindBy(u => u.UserName == username).FirstOrDefault() == null)
            {
                status = MembershipCreateStatus.InvalidUserName;
                return(null);
            }
            var user = new User
            {
                UserName = username,
            };

            user.SetPassword(password);
            _repository.Users.Add(user);
            status = MembershipCreateStatus.Success;
            return(GetUser(username, true));
        }
Exemple #25
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            string passwordHash = Allegiance.CommunitySecuritySystem.Common.Utility.Encryption.SHA256Hash(password);

            DataAccess.Identity identity = null;

            using (var db = new DataAccess.CSSDataContext())
            {
                if (DataAccess.Login.FindLoginByUsername(db, username) != null)
                {
                    status = System.Web.Security.MembershipCreateStatus.DuplicateUserName;
                    return(null);
                }

                if (DataAccess.Alias.ListAliases(db, username).Count > 0)
                {
                    status = System.Web.Security.MembershipCreateStatus.UserRejected;
                    return(null);
                }

                if (DataAccess.Identity.TryCreateIdentity(db, username, passwordHash, email, out identity) == true)
                {
                    db.SubmitChanges();
                }

                if (identity != null)
                {
                    DataAccess.Login createdLogin = DataAccess.Login.FindLoginByUsername(db, username);

                    if (createdLogin != null)
                    {
                        status = System.Web.Security.MembershipCreateStatus.Success;
                        return(MembershipUserUtility.CreateMembershipUserFromLogin(createdLogin));
                    }
                }
            }

            status = System.Web.Security.MembershipCreateStatus.ProviderError;
            return(null);
        }
        public MembershipUser CreateContact(string firstname, string lastname, string middlename, string email, string username, string password, string passwordQuestion, string passwordAnswer, bool isApproved, out System.Web.Security.MembershipCreateStatus status)
        {
            if (String.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Value cannot be null or empty.", "firstname");
            }
            if (String.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Value cannot be null or empty.", "lastname");
            }
            if (String.IsNullOrEmpty(email))
            {
                throw new ArgumentException("Value cannot be null or empty.", "email");
            }
            if (String.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Value cannot be null or empty.", "userName");
            }
            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Value cannot be null or empty.", "password");
            }

            int count;

            FindUsersByEmail(email, 0, 1, out count);
            if (count == 0)
            {
                FindUsersByName(username, 0, 1, out count);
            }
            else
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return(null);
            }

            if (count == 0)
            {
                System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(email);
                Contact contact = null;
                using (var Entities = Repository)
                {
                    var contacts = Entities.ContactEmails_v1_0.Where(e => e.Email_v1_0.formattedEmailAddress == email);
                    if (contacts.Count() == 1)
                    {
                        status = MembershipCreateStatus.DuplicateEmail;
                        return(null);
                    }
                    else
                    {
                        contact = new Contacts_v1_0
                        {
                            firstName           = firstname,
                            lastName            = lastname,
                            middleName          = middlename,
                            givenName           = firstname,
                            firstPartOfLastName = lastname.GetCharLeftPart(),
                            createDate          = DateTime.Now
                        };
                        Email_v1_0 mail = new Email_v1_0
                        {
                            formattedEmailAddress = address.Address,
                            domainName            = address.Host.Split('.')[0],
                            extension             = address.Host.Split('.')[1],
                            localpart             = address.User,
                            emailTypeId           = 2 //TODO:Detect
                        };
                        ContactEmails_v1_0 contactMail = new ContactEmails_v1_0
                        {
                            Contacts_v1_0 = contact,
                            Email_v1_0    = mail
                        };

                        return(CreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, contact, out status));
                    }
                }
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return(null);
            }
        }
Exemple #27
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            var roles     = database.Get();
            var emptyRole = roles.Single(r => r.Name == "-");

            emptyRole.Users.Add(new EKUser {
                UserName = username, Password = password
            });
            database.Save(emptyRole);
            status = MembershipCreateStatus.Success;
            return(GetUser(username, false));
        }