Ejemplo n.º 1
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Attempts to sign up from the given data. </summary>
        /// <remarks>   Andre Beging, 26.04.2018. </remarks>
        /// <param name="model">    The model. </param>
        /// <returns>   True if it succeeds, false if it fails. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        public static bool TrySignUp(SignUpModel model, out User user)
        {
            user = new User();

            if (string.IsNullOrWhiteSpace(model.Password))
            {
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.PasswordConfirmation))
            {
                return(false);
            }
            if (model.Password != model.PasswordConfirmation)
            {
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.Mail))
            {
                return(false);
            }

            using (var context = ContextHelper.OpenContext())
            {
                if (context.User.Any(u => u.Mail.Trim().ToLower() == model.Mail.Trim().ToLower()))
                {
                    return(false);
                }

                // Data valid

                var salt = GenerateSalt();
                var hash = CalculatePasswordHash(salt, model.Password);

                var newUser = new User
                {
                    Mail     = model.Mail.Trim(),
                    Username = model.Name,
                    Origin   = model.Origin.Trim(),
                    Created  = DateTime.Now,
                    Modified = DateTime.Now,
                    Salt     = salt,
                    Hash     = hash,
                    Type     = UserType.User,
                    Enabled  = true
                };

                context.User.Add(newUser);
                var result = context.SaveChanges();

                // No rows affected?
                if (result == 0)
                {
                    return(false);
                }

                user = newUser;

                // All good
                return(true);
            }
        }