Ejemplo n.º 1
0
        public void ChangeEmailSubscription(User user, bool emailAllowed)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            user.EmailAllowed = emailAllowed;
            UserRepository.CommitChanges();
        }
Ejemplo n.º 2
0
        public Project CreateProject(Project project, User user, bool commitChanges = true) 
        {
            var packageRegistration = CreateOrGetProjectRegistration(user, project);
            packageRegistration.Projects.Add(project);

            if (!commitChanges) return project;

            _packageRegistrationRepository.CommitChanges();

            return project;
        }
Ejemplo n.º 3
0
        public async Task ChangeEmailAddress(User user, string newEmailAddress)
        {
            var existingUsers = FindAllByEmailAddress(newEmailAddress);
            if (existingUsers.AnySafe(u => u.Key != user.Key))
            {
                throw new EntityException(Strings.EmailAddressBeingUsed, newEmailAddress);
            }

            await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.ChangeEmail, newEmailAddress));

            user.UpdateEmailAddress(newEmailAddress, Crypto.GenerateToken);
            UserRepository.CommitChanges();
        }
Ejemplo n.º 4
0
        public AuthenticatedUser(User user, Credential cred)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (cred == null)
            {
                throw new ArgumentNullException("cred");
            }

            User = user;
            CredentialUsed = cred;
        }
Ejemplo n.º 5
0
 public IEnumerable<Project> FindProjectsByOwner(User user, bool includeUnlisted) 
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 6
0
        private ProjectRegistration CreateOrGetProjectRegistration(User currentUser, Project project)
        {
            var projectRegistration = FindProjectRegistrationById(project.Key);

            if (projectRegistration != null && !projectRegistration.Owners.Contains(currentUser))
            {
                throw new EntityException("Project ID not available", project.Key);
            }

            if (projectRegistration != null) return projectRegistration;

            projectRegistration = new ProjectRegistration
            {
                Id = project.Key
            };

            projectRegistration.Owners.Add(currentUser);

            _packageRegistrationRepository.InsertOnCommit(projectRegistration);

            return projectRegistration;
        }
Ejemplo n.º 7
0
        private ActionResult SendPasswordResetEmail(User user, bool forgotPassword)
        {
            var resetPasswordUrl = Url.ConfirmationUrl(
                "ResetPassword",
                "Users",
                user.Username,
                user.PasswordResetToken,
                new { forgot = forgotPassword });
            MessageService.SendPasswordResetInstructions(user, resetPasswordUrl, forgotPassword);

            TempData["Email"] = user.EmailAddress;
            return RedirectToAction("PasswordSent");
        }
Ejemplo n.º 8
0
        public virtual async Task<AuthenticatedUser> Register(string username, string emailAddress, Credential credential)
        {
            var existingUser = Entities.Users
                .FirstOrDefault(u => u.Username == username || u.EmailAddress == emailAddress);
            if (existingUser != null)
            {
                if (String.Equals(existingUser.Username, username, StringComparison.OrdinalIgnoreCase))
                {
                    throw new EntityException(Strings.UsernameNotAvailable, username);
                }
                else
                {
                    throw new EntityException(Strings.EmailAddressBeingUsed, emailAddress);
                }
            }

            var apiKey = Guid.NewGuid();
            var newUser = new User(username)
            {
                EmailAllowed = true,
                UnconfirmedEmailAddress = emailAddress,
                EmailConfirmationToken = CryptographyService.GenerateToken(),
                CreatedUtc = DateTime.UtcNow
            };

            // Add a credential for the password and the API Key
            newUser.Credentials.Add(CredentialBuilder.CreateV1ApiKey(apiKey));
            newUser.Credentials.Add(credential);

            if (!Config.ConfirmEmailAddresses)
            {
                newUser.ConfirmEmailAddress();
            }

            // Write an audit record
            await Auditing.SaveAuditRecord(new UserAuditRecord(newUser, UserAuditAction.Registered));

            Entities.Users.Add(newUser);
            Entities.SaveChanges();

            return new AuthenticatedUser(newUser, credential);
        }
Ejemplo n.º 9
0
        public void SendEmailChangeNoticeToPreviousEmailAddress(User user, string oldEmailAddress)
        {
            string body = @"Hi there,

The email address associated to your {0} account was recently 
changed from _{1}_ to _{2}_.

Thanks,
The {0} Team";

            body = String.Format(
                CultureInfo.CurrentCulture,
                body,
                Config.GalleryOwner.DisplayName,
                oldEmailAddress,
                user.EmailAddress);

            string subject = String.Format(CultureInfo.CurrentCulture, "[{0}] Recent changes to your account.", Config.GalleryOwner.DisplayName);
            using (
                var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                mailMessage.From = Config.GalleryOwner;

                mailMessage.To.Add(new MailAddress(oldEmailAddress, user.Username));
                SendMessage(mailMessage);
            }
        }
Ejemplo n.º 10
0
        private void SendCredentialChangeNotice(User user, Credential changed, string bodyTemplate, string subjectTemplate)
        {
            // What kind of credential is this?
            var credViewModel = AuthService.DescribeCredential(changed);
            string name = credViewModel.AuthUI == null ? credViewModel.TypeCaption : credViewModel.AuthUI.AccountNoun;

            string body = String.Format(
                CultureInfo.CurrentCulture,
                bodyTemplate,
                name);
            string subject = String.Format(
                CultureInfo.CurrentCulture,
                subjectTemplate,
                Config.GalleryOwner.DisplayName,
                name);
            SendSupportMessage(user, body, subject);
        }
Ejemplo n.º 11
0
        public virtual async Task<bool> ChangePassword(User user, string oldPassword, string newPassword)
        {
            var hasPassword = user.Credentials.Any(
                c => c.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase));
            Credential _;
            if (hasPassword && !ValidatePasswordCredential(user.Credentials, oldPassword, out _))
            {
                // Invalid old password!
                return false;
            }

            // Replace/Set password credential
            var cred = CredentialBuilder.CreatePbkdf2Password(newPassword);
            await ReplaceCredentialInternal(user, cred);
            Entities.SaveChanges();
            return true;
        }
Ejemplo n.º 12
0
        private async Task ReplaceCredentialInternal(User user, Credential credential)
        {
            // Find the credentials we're replacing, if any
            var toRemove = user.Credentials
                .Where(cred =>
                    // If we're replacing a password credential, remove ALL password credentials
                    (credential.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase) &&
                     cred.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase)) ||
                    cred.Type == credential.Type)
                .ToList();
            foreach (var cred in toRemove)
            {
                user.Credentials.Remove(cred);
                Entities.DeleteOnCommit(cred);
            }

            if (toRemove.Any())
            {
                await Auditing.SaveAuditRecord(new UserAuditRecord(
                    user, UserAuditAction.RemovedCredential, toRemove));
            }

            user.Credentials.Add(credential);

            await Auditing.SaveAuditRecord(new UserAuditRecord(
                user, UserAuditAction.AddedCredential, credential));
        }
Ejemplo n.º 13
0
        private async Task MigrateCredentials(User user, List<Credential> creds, string password)
        {
            var toRemove = creds.Where(c =>
                !String.Equals(
                    c.Type,
                    CredentialTypes.Password.Pbkdf2,
                    StringComparison.OrdinalIgnoreCase))
                .ToList();

            // Remove any non PBKDF2 credentials
            foreach (var cred in toRemove)
            {
                creds.Remove(cred);
                user.Credentials.Remove(cred);
                Entities.DeleteOnCommit(cred);
            }
            await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.RemovedCredential, toRemove));

            // Now add one if there are no credentials left
            if (creds.Count == 0)
            {
                var newCred = CredentialBuilder.CreatePbkdf2Password(password);
                await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.AddedCredential, newCred));
                user.Credentials.Add(newCred);
            }

            // Save changes, if any
            Entities.SaveChanges();
        }
Ejemplo n.º 14
0
        public static ClaimsIdentity CreateIdentity(User user, string authenticationType, params Claim[] additionalClaims)
        {
            var claims = Enumerable.Concat(new[] {
                new Claim(ClaimsIdentity.DefaultNameClaimType, user.Username),
                new Claim(ClaimTypes.AuthenticationMethod, authenticationType),

                // Needed for anti-forgery token, also good practice to have a unique identifier claim
                new Claim(ClaimTypes.NameIdentifier, user.Username)
            }, user.Roles.Select(r => new Claim(ClaimsIdentity.DefaultRoleClaimType, r.Name)));

            if (additionalClaims.Length > 0)
            {
                claims = Enumerable.Concat(claims, additionalClaims);
            }

            ClaimsIdentity identity = new ClaimsIdentity(
                claims,
                authenticationType,
                nameType: ClaimsIdentity.DefaultNameClaimType,
                roleType: ClaimsIdentity.DefaultRoleClaimType);
            return identity;
        }
Ejemplo n.º 15
0
 public virtual async Task RemoveCredential(User user, Credential cred)
 {
     await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.RemovedCredential, cred));
     user.Credentials.Remove(cred);
     Entities.Credentials.Remove(cred);
     Entities.SaveChanges();
 }
Ejemplo n.º 16
0
 public virtual async Task AddCredential(User user, Credential credential)
 {
     await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.AddedCredential, credential));
     user.Credentials.Add(credential);
     Entities.SaveChanges();
 }
Ejemplo n.º 17
0
 public virtual async Task ReplaceCredential(User user, Credential credential)
 {
     await ReplaceCredentialInternal(user, credential);
     Entities.SaveChanges();
 }
Ejemplo n.º 18
0
        public void SendPasswordResetInstructions(User user, string resetPasswordUrl, bool forgotPassword)
        {
            string body = String.Format(
                CultureInfo.CurrentCulture,
                forgotPassword ? Strings.Emails_ForgotPassword_Body : Strings.Emails_SetPassword_Body,
                Constants.DefaultPasswordResetTokenExpirationHours,
                resetPasswordUrl,
                Config.GalleryOwner.DisplayName);

            string subject = String.Format(CultureInfo.CurrentCulture, forgotPassword ? Strings.Emails_ForgotPassword_Subject : Strings.Emails_SetPassword_Subject, Config.GalleryOwner.DisplayName);
            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                mailMessage.From = Config.GalleryOwner;

                mailMessage.To.Add(user.ToMailAddress());
                SendMessage(mailMessage);
            }
        }
Ejemplo n.º 19
0
 public void AddProjectOwner(ProjectRegistration package, User user) {
     throw new NotImplementedException();
 }
Ejemplo n.º 20
0
        public virtual async Task GeneratePasswordResetToken(User user, int expirationInMinutes)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (expirationInMinutes < 1)
            {
                throw new ArgumentException(
                    "Token expiration should give the user at least a minute to change their password", "expirationInMinutes");
            }

            if (!user.Confirmed)
            {
                throw new InvalidOperationException(Strings.UserIsNotYetConfirmed);
            }

            if (!String.IsNullOrEmpty(user.PasswordResetToken) && !user.PasswordResetTokenExpirationDate.IsInThePast())
            {
                return;
            }

            user.PasswordResetToken = CryptographyService.GenerateToken();
            user.PasswordResetTokenExpirationDate = DateTime.UtcNow.AddMinutes(expirationInMinutes);

            await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.RequestedPasswordReset));

            Entities.SaveChanges();
            return;
        }
Ejemplo n.º 21
0
 public UserProfileModel(User user)
 {
     Username = user.Username;
     EmailAddress = user.EmailAddress;
     UnconfirmedEmailAddress = user.UnconfirmedEmailAddress;
 }
Ejemplo n.º 22
0
        public async Task<bool> ConfirmEmailAddress(User user, string token)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (String.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException("token");
            }

            if (user.EmailConfirmationToken != token)
            {
                return false;
            }

            var conflictingUsers = FindAllByEmailAddress(user.UnconfirmedEmailAddress);
            if (conflictingUsers.AnySafe(u => u.Key != user.Key))
            {
                throw new EntityException(Strings.EmailAddressBeingUsed, user.UnconfirmedEmailAddress);
            }

            await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.ConfirmEmail, user.UnconfirmedEmailAddress));

            user.ConfirmEmailAddress();

            UserRepository.CommitChanges();
            return true;
        }
Ejemplo n.º 23
0
 public void SendCredentialAddedNotice(User user, Credential added)
 {
     SendCredentialChangeNotice(
         user,
         added,
         Strings.Emails_CredentialAdded_Body,
         Strings.Emails_CredentialAdded_Subject);
 }
Ejemplo n.º 24
0
        private async Task<ActionResult> RemoveCredential(User user, Credential cred, string message)
        {
            // Count login credentials
            if (CountLoginCredentials(user) <= 1)
            {
                TempData["Message"] = Strings.CannotRemoveOnlyLoginCredential;
            }
            else if (cred != null)
            {
                await AuthService.RemoveCredential(user, cred);

                // Notify the user of the change
                MessageService.SendCredentialRemovedNotice(user, cred);

                TempData["Message"] = message;
            }
            return RedirectToAction("Account");
        }
Ejemplo n.º 25
0
        private void SendSupportMessage(User user, string body, string subject)
        {
            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                mailMessage.From = Config.GalleryOwner;

                mailMessage.To.Add(user.ToMailAddress());
                SendMessage(mailMessage);
            }
        }
Ejemplo n.º 26
0
 private static int CountLoginCredentials(User user)
 {
     return user.Credentials.Count(c =>
         c.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase) ||
         c.Type.StartsWith(CredentialTypes.ExternalPrefix, StringComparison.OrdinalIgnoreCase));
 }
Ejemplo n.º 27
0
 public static string User(this UrlHelper url, User user, string scheme = null)
 {
     string result = url.Action(MVC.Users.Profiles(user.Username), protocol: scheme);
     return EnsureTrailingSlash(result);
 }
Ejemplo n.º 28
0
        public virtual void CreateSession(IOwinContext owinContext, User user)
        {
            // Create a claims identity for the session
            ClaimsIdentity identity = CreateIdentity(user, AuthenticationTypes.LocalUser);

            // Issue the session token and clean up the external token if present
            owinContext.Authentication.SignIn(identity);
            owinContext.Authentication.SignOut(AuthenticationTypes.External);
        }