FindByUsername() публичный Метод

public FindByUsername ( string username ) : User
username string
Результат User
Пример #1
0
        public virtual async Task <ActionResult> ConfirmTransformToOrganization(string accountNameToTransform, string token)
        {
            var adminUser = GetCurrentUser();

            string errorReason;
            var    accountToTransform = UserService.FindByUsername(accountNameToTransform);

            if (accountToTransform == null)
            {
                errorReason = String.Format(CultureInfo.CurrentCulture,
                                            Strings.TransformAccount_OrganizationAccountDoesNotExist, accountNameToTransform);
                return(TransformToOrganizationFailed(errorReason));
            }

            if (!UserService.CanTransformUserToOrganization(accountToTransform, out errorReason))
            {
                return(TransformToOrganizationFailed(errorReason));
            }

            if (!await UserService.TransformUserToOrganization(accountToTransform, adminUser, token))
            {
                errorReason = Strings.TransformAccount_Failed;
                return(TransformToOrganizationFailed(errorReason));
            }

            MessageService.SendOrganizationTransformRequestAcceptedNotice(accountToTransform, adminUser);

            TelemetryService.TrackOrganizationTransformCompleted(accountToTransform);

            TempData["Message"] = String.Format(CultureInfo.CurrentCulture,
                                                Strings.TransformAccount_Success, accountNameToTransform);

            return(Redirect(Url.ManageMyOrganization(accountNameToTransform)));
        }
Пример #2
0
        public virtual ActionResult Profiles(string username)
        {
            var user = UserService.FindByUsername(username);

            if (user == null)
            {
                return(HttpNotFound());
            }

            var packages = PackageService.FindPackagesByOwner(user, includeUnlisted: false)
                           .OrderByDescending(p => p.PackageRegistration.DownloadCount)
                           .Select(p => new PackageViewModel(p)
            {
                DownloadCount = p.PackageRegistration.DownloadCount,
                Version       = null
            }).ToList();

            var model = new UserProfileModel(user)
            {
                Packages = packages,
                TotalPackageDownloadCount = packages.Sum(p => p.TotalDownloadCount),
            };

            return(View(model));
        }
Пример #3
0
        public virtual async Task <ActionResult> TransformToOrganization(TransformAccountViewModel transformViewModel)
        {
            var accountToTransform = GetCurrentUser();

            var adminUser = UserService.FindByUsername(transformViewModel.AdminUsername);

            if (adminUser == null)
            {
                ModelState.AddModelError(string.Empty, String.Format(CultureInfo.CurrentCulture,
                                                                     Strings.TransformAccount_AdminAccountDoesNotExist, transformViewModel.AdminUsername));
                return(View(transformViewModel));
            }

            if (!UserService.CanTransformUserToOrganization(accountToTransform, adminUser, out var errorReason))
            {
                ModelState.AddModelError(string.Empty, errorReason);
                return(View(transformViewModel));
            }

            await UserService.RequestTransformToOrganizationAccount(accountToTransform, adminUser);

            // sign out pending organization and prompt for admin sign in
            OwinContext.Authentication.SignOut();

            TempData[Constants.ReturnUrlMessageViewDataKey] = String.Format(CultureInfo.CurrentCulture,
                                                                            Strings.TransformAccount_SignInToConfirm, adminUser.Username, accountToTransform.Username);
            var returnUrl = Url.ConfirmTransformAccount(accountToTransform);

            return(Redirect(Url.LogOn(returnUrl)));
        }
Пример #4
0
        public virtual async Task <ActionResult> Delete(DeleteAccountAsAdminViewModel model)
        {
            var user = UserService.FindByUsername(model.AccountName);

            if (user == null || user.IsDeleted)
            {
                return(View("DeleteUserAccountStatus", new DeleteUserAccountStatus()
                {
                    AccountName = model.AccountName,
                    Description = $"Account {model.AccountName} not found.",
                    Success = false
                }));
            }
            else
            {
                var admin  = GetCurrentUser();
                var status = await _deleteAccountService.DeleteAccountAsync(
                    userToBeDeleted : user,
                    userToExecuteTheDelete : admin,
                    signature : model.Signature,
                    orphanPackagePolicy : model.ShouldUnlist?AccountDeletionOrphanPackagePolicy.UnlistOrphans : AccountDeletionOrphanPackagePolicy.KeepOrphans,
                    commitAsTransaction : true);

                return(View("DeleteUserAccountStatus", status));
            }
        }
Пример #5
0
        public virtual async Task <ActionResult> RejectTransformToOrganization(string accountNameToTransform, string token)
        {
            var adminUser = GetCurrentUser();

            string message;
            var    accountToTransform = UserService.FindByUsername(accountNameToTransform);

            if (accountToTransform == null)
            {
                message = String.Format(CultureInfo.CurrentCulture,
                                        Strings.TransformAccount_OrganizationAccountDoesNotExist, accountNameToTransform);
            }
            else
            {
                if (await UserService.RejectTransformUserToOrganizationRequest(accountToTransform, adminUser, token))
                {
                    MessageService.SendOrganizationTransformRequestRejectedNotice(accountToTransform, adminUser);

                    TelemetryService.TrackOrganizationTransformDeclined(accountToTransform);

                    message = String.Format(CultureInfo.CurrentCulture,
                                            Strings.TransformAccount_Rejected, accountNameToTransform);
                }
                else
                {
                    message = Strings.TransformAccount_FailedMissingRequestToCancel;
                }
            }

            TempData["Message"] = message;

            return(RedirectToAction(actionName: "Home", controllerName: "Pages"));
        }
Пример #6
0
        public virtual ActionResult Confirm(string username, string token)
        {
            // We don't want Login to have us as a return URL
            // By having this value present in the dictionary BUT null, we don't put "returnUrl" on the Login link at all
            ViewData[Constants.ReturnUrlViewDataKey] = null;

            if (!String.Equals(username, Identity.Name, StringComparison.OrdinalIgnoreCase))
            {
                return(View(new ConfirmationViewModel
                {
                    WrongUsername = true,
                    SuccessfulConfirmation = false,
                }));
            }

            var user = UserService.FindByUsername(username);

            if (user == null)
            {
                return(HttpNotFound());
            }

            string existingEmail = user.EmailAddress;
            var    model         = new ConfirmationViewModel
            {
                ConfirmingNewAccount   = String.IsNullOrEmpty(existingEmail),
                SuccessfulConfirmation = true,
            };

            try
            {
                if (!UserService.ConfirmEmailAddress(user, token))
                {
                    model.SuccessfulConfirmation = false;
                }
            }
            catch (EntityException)
            {
                model.SuccessfulConfirmation = false;
                model.DuplicateEmailAddress  = true;
            }

            // SuccessfulConfirmation is required so that the confirm Action isn't a way to spam people.
            // Change notice not required for new accounts.
            if (model.SuccessfulConfirmation && !model.ConfirmingNewAccount)
            {
                MessageService.SendEmailChangeNoticeToPreviousEmailAddress(user, existingEmail);

                string returnUrl = HttpContext.GetConfirmationReturnUrl();
                if (!String.IsNullOrEmpty(returnUrl))
                {
                    TempData["Message"] = "You have successfully confirmed your email address!";
                    return(new RedirectResult(RedirectHelper.SafeRedirectUrl(Url, returnUrl)));
                }
            }

            return(View(model));
        }
Пример #7
0
        public async Task DeleteOwnerFromReservedNamespaceAsync(string prefix, string username)
        {
            if (string.IsNullOrWhiteSpace(prefix))
            {
                throw new ArgumentException(Strings.ReservedNamespace_InvalidNamespace);
            }

            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentException(Strings.ReservedNamespace_InvalidUsername);
            }

            using (var strategy = new SuspendDbExecutionStrategy())
                using (var transaction = EntitiesContext.GetDatabase().BeginTransaction())
                {
                    var namespaceToModify = FindReservedNamespaceForPrefix(prefix)
                                            ?? throw new InvalidOperationException(string.Format(
                                                                                       CultureInfo.CurrentCulture, Strings.ReservedNamespace_NamespaceNotFound, prefix));

                    var userToRemove = UserService.FindByUsername(username)
                                       ?? throw new InvalidOperationException(string.Format(
                                                                                  CultureInfo.CurrentCulture, Strings.ReservedNamespace_UserNotFound, username));

                    if (!namespaceToModify.Owners.Contains(userToRemove))
                    {
                        throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.ReservedNamespace_UserNotAnOwner, username));
                    }

                    var packagesOwnedByUserMatchingPrefix = namespaceToModify
                                                            .PackageRegistrations
                                                            .Where(pr => pr
                                                                   .Owners
                                                                   .Any(pro => pro.Username == userToRemove.Username))
                                                            .ToList();

                    // Remove verified mark for package registrations if the user to be removed is the only prefix owner
                    // for the given package registration.
                    var packageRegistrationsToMarkUnverified = packagesOwnedByUserMatchingPrefix
                                                               .Where(pr => pr.Owners.Intersect(namespaceToModify.Owners).Count() == 1)
                                                               .ToList();

                    if (packageRegistrationsToMarkUnverified.Any())
                    {
                        packageRegistrationsToMarkUnverified
                        .ForEach(pr => namespaceToModify.PackageRegistrations.Remove(pr));

                        await PackageService.UpdatePackageVerifiedStatusAsync(packageRegistrationsToMarkUnverified, isVerified : false);
                    }

                    namespaceToModify.Owners.Remove(userToRemove);
                    await ReservedNamespaceRepository.CommitChangesAsync();

                    transaction.Commit();
                }
        }
Пример #8
0
        public virtual ActionResult ConfirmationRequired()
        {
            User user  = UserService.FindByUsername(User.Identity.Name);
            var  model = new ConfirmationViewModel
            {
                ConfirmingNewAccount    = !(user.Confirmed),
                UnconfirmedEmailAddress = user.UnconfirmedEmailAddress,
            };

            return(View(model));
        }
Пример #9
0
        public virtual ActionResult Delete(string accountName)
        {
            var user = UserService.FindByUsername(accountName);

            if (user == null || user.IsDeleted || (user is Organization))
            {
                return(HttpNotFound());
            }

            return(View("DeleteUserAccount", GetDeleteAccountViewModel(user)));
        }
Пример #10
0
        public virtual ActionResult Delete(string accountName)
        {
            var accountToDelete = UserService.FindByUsername(accountName) as TUser;

            if (accountToDelete == null || accountToDelete.IsDeleted)
            {
                return(HttpNotFound());
            }

            return(View(GetDeleteAccountViewName(), GetDeleteAccountViewModel(accountToDelete)));
        }
Пример #11
0
        public virtual async Task <ActionResult> TransformToOrganization(TransformAccountViewModel transformViewModel)
        {
            var accountToTransform = GetCurrentUser();

            var adminUsername = transformViewModel.AdminUsername;

            if (Regex.IsMatch(adminUsername, Constants.EmailValidationRegex, RegexOptions.None, Constants.EmailValidationRegexTimeout))
            {
                ModelState.AddModelError(string.Empty, Strings.TransformAccount_AdminNameIsEmail);
                return(View(transformViewModel));
            }

            var adminUser = UserService.FindByUsername(adminUsername);

            if (adminUser == null)
            {
                ModelState.AddModelError(string.Empty, string.Format(CultureInfo.CurrentCulture,
                                                                     Strings.TransformAccount_AdminAccountDoesNotExist, adminUsername));
                return(View(transformViewModel));
            }

            if (!UserService.CanTransformUserToOrganization(accountToTransform, adminUser, out var errorReason))
            {
                ModelState.AddModelError(string.Empty, errorReason);
                return(View(transformViewModel));
            }

            // Get the user from the previous organization migration request (if there was one) so we can notify them that their request has been cancelled.
            var existingTransformRequestUser = accountToTransform.OrganizationMigrationRequest?.AdminUser;

            await UserService.RequestTransformToOrganizationAccount(accountToTransform, adminUser);

            if (existingTransformRequestUser != null)
            {
                await MessageService.SendOrganizationTransformRequestCancelledNoticeAsync(accountToTransform, existingTransformRequestUser);
            }

            var returnUrl  = Url.ConfirmTransformAccount(accountToTransform);
            var confirmUrl = Url.ConfirmTransformAccount(accountToTransform, relativeUrl: false);
            var rejectUrl  = Url.RejectTransformAccount(accountToTransform, relativeUrl: false);
            await MessageService.SendOrganizationTransformRequestAsync(accountToTransform, adminUser, Url.User(accountToTransform, relativeUrl: false), confirmUrl, rejectUrl);

            var cancelUrl = Url.CancelTransformAccount(accountToTransform, relativeUrl: false);
            await MessageService.SendOrganizationTransformInitiatedNoticeAsync(accountToTransform, adminUser, cancelUrl);

            TelemetryService.TrackOrganizationTransformInitiated(accountToTransform);

            // sign out pending organization and prompt for admin sign in
            OwinContext.Authentication.SignOut();

            TempData[Constants.ReturnUrlMessageViewDataKey] = String.Format(CultureInfo.CurrentCulture,
                                                                            Strings.TransformAccount_SignInToConfirm, adminUser.Username, accountToTransform.Username);
            return(Redirect(Url.LogOn(returnUrl)));
        }
Пример #12
0
        public virtual ActionResult ChangeEmail()
        {
            User user  = UserService.FindByUsername(User.Identity.Name);
            var  model = new ChangeEmailRequestModel
            {
                NewEmail = String.IsNullOrEmpty(user.UnconfirmedEmailAddress) ?
                           user.EmailAddress : user.UnconfirmedEmailAddress
            };

            return(View(model));
        }
Пример #13
0
        public virtual async Task <JsonResult> GenerateApiKey(string description, string owner, string[] scopes = null, string[] subjects = null, int?expirationInDays = null)
        {
            if (string.IsNullOrWhiteSpace(description))
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(Strings.ApiKeyDescriptionRequired));
            }
            if (string.IsNullOrWhiteSpace(owner))
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(Strings.ApiKeyOwnerRequired));
            }

            // Get the owner scope
            User scopeOwner = UserService.FindByUsername(owner);

            if (scopeOwner == null)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(Strings.UserNotFound));
            }

            var resolvedScopes = BuildScopes(scopeOwner, scopes, subjects);

            if (!VerifyScopes(resolvedScopes))
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(Strings.ApiKeyScopesNotAllowed));
            }

            // Set expiration
            var expiration = TimeSpan.Zero;

            if (_config.ExpirationInDaysForApiKeyV1 > 0)
            {
                expiration = TimeSpan.FromDays(_config.ExpirationInDaysForApiKeyV1);

                if (expirationInDays.HasValue && expirationInDays.Value > 0)
                {
                    expiration = TimeSpan.FromDays(Math.Min(expirationInDays.Value, _config.ExpirationInDaysForApiKeyV1));
                }
            }

            var newCredentialViewModel = await GenerateApiKeyInternal(description, resolvedScopes, expiration);

            var emailMessage = new CredentialAddedMessage(
                _config,
                GetCurrentUser(),
                newCredentialViewModel.GetCredentialTypeInfo());
            await MessageService.SendMessageAsync(emailMessage);

            return(Json(new ApiKeyViewModel(newCredentialViewModel)));
        }
Пример #14
0
        public virtual ActionResult Edit()
        {
            var user  = UserService.FindByUsername(Identity.Name);
            var model = new EditProfileViewModel
            {
                Username               = user.Username,
                EmailAddress           = user.EmailAddress,
                EmailAllowed           = user.EmailAllowed,
                PendingNewEmailAddress = user.UnconfirmedEmailAddress
            };

            return(View(model));
        }
Пример #15
0
        public virtual ActionResult Edit(EditProfileViewModel profile)
        {
            var user = UserService.FindByUsername(Identity.Name);

            if (user == null)
            {
                return(HttpNotFound());
            }

            profile.EmailAddress           = user.EmailAddress;
            profile.Username               = user.Username;
            profile.PendingNewEmailAddress = user.UnconfirmedEmailAddress;
            UserService.UpdateProfile(user, profile.EmailAllowed);
            return(View(profile));
        }
Пример #16
0
        public virtual ActionResult GenerateApiKey()
        {
            // Get the user
            var user = UserService.FindByUsername(User.Identity.Name);

            // Generate an API Key
            var apiKey = Guid.NewGuid();

            // Set the existing API Key field
            user.ApiKey = apiKey;

            // Add/Replace the API Key credential, and save to the database
            UserService.ReplaceCredential(user, CredentialBuilder.CreateV1ApiKey(apiKey));
            return(RedirectToAction(MVC.Users.Account()));
        }
        public async Task AddOwnerToReservedNamespaceAsync(string prefix, string username)
        {
            if (string.IsNullOrWhiteSpace(prefix))
            {
                throw new ArgumentException(Strings.ReservedNamespace_InvalidNamespace);
            }

            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentException(Strings.ReservedNamespace_InvalidUsername);
            }

            using (var strategy = new SuspendDbExecutionStrategy())
                using (var transaction = EntitiesContext.GetDatabase().BeginTransaction())
                {
                    var namespaceToModify = FindReservedNamespaceForPrefix(prefix)
                                            ?? throw new InvalidOperationException(string.Format(
                                                                                       CultureInfo.CurrentCulture, Strings.ReservedNamespace_NamespaceNotFound, prefix));

                    var userToAdd = UserService.FindByUsername(username)
                                    ?? throw new InvalidOperationException(string.Format(
                                                                               CultureInfo.CurrentCulture, Strings.ReservedNamespace_UserNotFound, username));

                    if (namespaceToModify.Owners.Contains(userToAdd))
                    {
                        throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.ReservedNamespace_UserAlreadyOwner, username));
                    }

                    // Mark all packages owned by this user that start with the given namespace as verified.
                    var allPackageRegistrationsForUser        = PackageService.FindPackageRegistrationsByOwner(userToAdd);
                    var packageRegistrationsMatchingNamespace = allPackageRegistrationsForUser
                                                                .Where(pr => pr.Id.StartsWith(namespaceToModify.Value, StringComparison.OrdinalIgnoreCase))
                                                                .ToList();

                    if (packageRegistrationsMatchingNamespace.Any())
                    {
                        packageRegistrationsMatchingNamespace
                        .ForEach(pr => namespaceToModify.PackageRegistrations.Add(pr));

                        await PackageService.UpdatePackageVerifiedStatusAsync(packageRegistrationsMatchingNamespace.AsReadOnly(), isVerified : true);
                    }

                    namespaceToModify.Owners.Add(userToAdd);
                    await ReservedNamespaceRepository.CommitChangesAsync();

                    transaction.Commit();
                }
        }
Пример #18
0
        public virtual ActionResult Packages()
        {
            var user     = UserService.FindByUsername(Identity.Name);
            var packages = PackageService.FindPackagesByOwner(user, includeUnlisted: true)
                           .Select(p => new PackageViewModel(p)
            {
                DownloadCount = p.PackageRegistration.DownloadCount,
                Version       = null
            }).ToList();

            var model = new ManagePackagesViewModel
            {
                Packages = packages
            };

            return(View(model));
        }
Пример #19
0
        public virtual ActionResult ConfirmationRequiredPost()
        {
            User user            = UserService.FindByUsername(User.Identity.Name);
            var  confirmationUrl = Url.ConfirmationUrl(
                MVC.Users.Confirm(), user.Username, user.EmailConfirmationToken, protocol: Request.Url.Scheme);

            MessageService.SendNewAccountEmail(new MailAddress(user.UnconfirmedEmailAddress, user.Username), confirmationUrl);

            var model = new ConfirmationViewModel
            {
                ConfirmingNewAccount    = !(user.Confirmed),
                UnconfirmedEmailAddress = user.UnconfirmedEmailAddress,
                SentEmail = true,
            };

            return(View(model));
        }
Пример #20
0
        public virtual ActionResult Account()
        {
            var user          = UserService.FindByUsername(Identity.Name);
            var curatedFeeds  = CuratedFeedService.GetFeedsForManager(user.Key);
            var apiCredential = user
                                .Credentials
                                .FirstOrDefault(c => c.Type == CredentialTypes.ApiKeyV1);

            return(View(
                       new AccountViewModel
            {
                ApiKey = apiCredential == null ?
                         user.ApiKey.ToString() :
                         apiCredential.Value,
                IsConfirmed = user.Confirmed,
                CuratedFeeds = curatedFeeds.Select(cf => cf.Name)
            }));
        }
Пример #21
0
        private async Task <List <PackageRegistration> > DeleteOwnerFromReservedNamespaceImplAsync(string prefix, string username, ReservedNamespace namespaceToModify, bool commitChanges = true)
        {
            var userToRemove = UserService.FindByUsername(username)
                               ?? throw new InvalidOperationException(string.Format(
                                                                          CultureInfo.CurrentCulture, ServicesStrings.ReservedNamespace_UserNotFound, username));

            if (!namespaceToModify.Owners.Contains(userToRemove))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ServicesStrings.ReservedNamespace_UserNotAnOwner, username));
            }

            var packagesOwnedByUserMatchingPrefix = namespaceToModify
                                                    .PackageRegistrations
                                                    .Where(pr => pr
                                                           .Owners
                                                           .Any(pro => pro.Username == userToRemove.Username))
                                                    .ToList();

            namespaceToModify.Owners.Remove(userToRemove);

            // Remove verified mark for package registrations if the user to be removed is the only prefix owner
            // for the given package registration.
            var packageRegistrationsToMarkUnverified = packagesOwnedByUserMatchingPrefix
                                                       .Where(pr => !pr.Owners.Any(o =>
                                                                                   ActionsRequiringPermissions.AddPackageToReservedNamespace.CheckPermissionsOnBehalfOfAnyAccount(
                                                                                       o, new[] { namespaceToModify }) == PermissionsCheckResult.Allowed))
                                                       .ToList();

            if (packageRegistrationsToMarkUnverified.Any())
            {
                packageRegistrationsToMarkUnverified
                .ForEach(pr => namespaceToModify.PackageRegistrations.Remove(pr));

                await PackageService.UpdatePackageVerifiedStatusAsync(packageRegistrationsToMarkUnverified, isVerified : false, commitChanges : false);
            }

            if (commitChanges)
            {
                await ReservedNamespaceRepository.CommitChangesAsync();
            }

            return(packageRegistrationsToMarkUnverified);
        }
Пример #22
0
        public virtual ActionResult Profiles(string username, int page = 1)
        {
            var currentUser = GetCurrentUser();
            var user        = UserService.FindByUsername(username);

            if (user == null || user.IsDeleted)
            {
                return(HttpNotFound());
            }

            var packages = PackageService.FindPackagesByOwner(user, includeUnlisted: false)
                           .OrderByDescending(p => p.PackageRegistration.DownloadCount)
                           .Select(p => new ListPackageItemViewModel(p, currentUser)
            {
                DownloadCount = p.PackageRegistration.DownloadCount
            }).ToList();

            var model = new UserProfileModel(user, currentUser, packages, page - 1, Constants.DefaultPackageListPageSize, Url);

            return(View(model));
        }
Пример #23
0
        public virtual async Task <ActionResult> Delete(DeleteUserAccountViewModel model)
        {
            var user = UserService.FindByUsername(model.AccountName);

            if (user == null || user.IsDeleted)
            {
                return(View("DeleteUserAccountStatus", new DeleteUserAccountStatus()
                {
                    AccountName = model.AccountName,
                    Description = $"Account {model.AccountName} not found.",
                    Success = false
                }));
            }
            else
            {
                var admin  = GetCurrentUser();
                var status = await _deleteAccountService.DeleteGalleryUserAccountAsync(user, admin, model.Signature, model.ShouldUnlist, commitAsTransaction : true);

                return(View("DeleteUserAccountStatus", status));
            }
        }
Пример #24
0
        public virtual ActionResult Profiles(string username, int page = 1, bool showAllPackages = false)
        {
            var user = UserService.FindByUsername(username);

            if (user == null)
            {
                return(HttpNotFound());
            }

            var packages = PackageService.FindPackagesByOwner(user, includeUnlisted: false)
                           .OrderByDescending(p => p.PackageRegistration.DownloadCount)
                           .Select(p => new PackageViewModel(p)
            {
                DownloadCount = p.PackageRegistration.DownloadCount
            }).ToList();

            var model = new UserProfileModel(user, packages, page - 1, Constants.DefaultPackageListPageSize, Url);

            model.ShowAllPackages = showAllPackages;

            return(View(model));
        }
Пример #25
0
        public virtual ActionResult Delete(string accountName)
        {
            var currentUser = GetCurrentUser();
            var user        = UserService.FindByUsername(accountName);

            if (user == null || user.IsDeleted || (user is Organization))
            {
                return(HttpNotFound("User not found."));
            }

            var listPackageItems = _packageService
                                   .FindPackagesByAnyMatchingOwner(user, includeUnlisted: true)
                                   .Select(p => new ListPackageItemViewModel(p, currentUser))
                                   .ToList();
            var model = new DeleteUserAccountViewModel
            {
                Packages    = listPackageItems,
                User        = user,
                AccountName = user.Username,
            };

            return(View("DeleteUserAccount", model));
        }
        private async Task <List <PackageRegistration> > DeleteOwnerFromReservedNamespaceImplAsync(string prefix, string username, ReservedNamespace namespaceToModify)
        {
            var userToRemove = UserService.FindByUsername(username)
                               ?? throw new InvalidOperationException(string.Format(
                                                                          CultureInfo.CurrentCulture, Strings.ReservedNamespace_UserNotFound, username));

            if (!namespaceToModify.Owners.Contains(userToRemove))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.ReservedNamespace_UserNotAnOwner, username));
            }

            var packagesOwnedByUserMatchingPrefix = namespaceToModify
                                                    .PackageRegistrations
                                                    .Where(pr => pr
                                                           .Owners
                                                           .Any(pro => pro.Username == userToRemove.Username))
                                                    .ToList();

            // Remove verified mark for package registrations if the user to be removed is the only prefix owner
            // for the given package registration.
            var packageRegistrationsToMarkUnverified = packagesOwnedByUserMatchingPrefix
                                                       .Where(pr => pr.Owners.Intersect(namespaceToModify.Owners).Count() == 1)
                                                       .ToList();

            if (packageRegistrationsToMarkUnverified.Any())
            {
                packageRegistrationsToMarkUnverified
                .ForEach(pr => namespaceToModify.PackageRegistrations.Remove(pr));

                await PackageService.UpdatePackageVerifiedStatusAsync(packageRegistrationsToMarkUnverified, isVerified : false);
            }

            namespaceToModify.Owners.Remove(userToRemove);
            await ReservedNamespaceRepository.CommitChangesAsync();

            return(packageRegistrationsToMarkUnverified);
        }
Пример #27
0
        public virtual async Task <ActionResult> Delete(DeleteAccountAsAdminViewModel model)
        {
            var accountToDelete = UserService.FindByUsername(model.AccountName) as TUser;

            if (accountToDelete == null || accountToDelete.IsDeleted)
            {
                return(View("DeleteAccountStatus", new DeleteAccountStatus()
                {
                    AccountName = model.AccountName,
                    Description = $"Account {model.AccountName} not found.",
                    Success = false
                }));
            }
            else
            {
                var admin  = GetCurrentUser();
                var status = await DeleteAccountService.DeleteAccountAsync(
                    userToBeDeleted : accountToDelete,
                    userToExecuteTheDelete : admin,
                    orphanPackagePolicy : model.ShouldUnlist?AccountDeletionOrphanPackagePolicy.UnlistOrphans : AccountDeletionOrphanPackagePolicy.KeepOrphans);

                return(View("DeleteAccountStatus", status));
            }
        }
Пример #28
0
        public async Task AddOwnerToReservedNamespaceAsync(string prefix, string username)
        {
            if (string.IsNullOrWhiteSpace(prefix))
            {
                throw new ArgumentException(ServicesStrings.ReservedNamespace_InvalidNamespace);
            }

            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentException(ServicesStrings.ReservedNamespace_InvalidUsername);
            }

            using (var strategy = new SuspendDbExecutionStrategy())
                using (var transaction = EntitiesContext.GetDatabase().BeginTransaction())
                {
                    var namespaceToModify = FindReservedNamespaceForPrefix(prefix)
                                            ?? throw new InvalidOperationException(string.Format(
                                                                                       CultureInfo.CurrentCulture, ServicesStrings.ReservedNamespace_NamespaceNotFound, prefix));

                    var userToAdd = UserService.FindByUsername(username)
                                    ?? throw new InvalidOperationException(string.Format(
                                                                               CultureInfo.CurrentCulture, ServicesStrings.ReservedNamespace_UserNotFound, username));

                    if (namespaceToModify.Owners.Contains(userToAdd))
                    {
                        throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ServicesStrings.ReservedNamespace_UserAlreadyOwner, username));
                    }

                    Expression <Func <PackageRegistration, bool> > predicate;
                    if (namespaceToModify.IsPrefix)
                    {
                        predicate = registration => registration.Id.StartsWith(namespaceToModify.Value);
                    }
                    else
                    {
                        predicate = registration => registration.Id.Equals(namespaceToModify.Value);
                    }

                    // Mark all packages owned by this user that start with the given namespace as verified.
                    var allPackageRegistrationsForUser = PackageService.FindPackageRegistrationsByOwner(userToAdd);

                    // We need 'AsQueryable' here because FindPackageRegistrationsByOwner returns an IEnumerable
                    // and to evaluate the predicate server side, the casting is essential.
                    var packageRegistrationsMatchingNamespace = allPackageRegistrationsForUser
                                                                .AsQueryable()
                                                                .Where(predicate)
                                                                .ToList();

                    if (packageRegistrationsMatchingNamespace.Any())
                    {
                        packageRegistrationsMatchingNamespace
                        .ForEach(pr => namespaceToModify.PackageRegistrations.Add(pr));

                        await PackageService.UpdatePackageVerifiedStatusAsync(packageRegistrationsMatchingNamespace.AsReadOnly(), isVerified : true);
                    }

                    namespaceToModify.Owners.Add(userToAdd);
                    await ReservedNamespaceRepository.CommitChangesAsync();

                    transaction.Commit();

                    await AuditingService.SaveAuditRecordAsync(
                        new ReservedNamespaceAuditRecord(namespaceToModify, AuditedReservedNamespaceAction.AddOwner, username, packageRegistrationsMatchingNamespace));
                }
        }
Пример #29
0
 protected virtual TUser GetAccount(string accountName)
 {
     return(UserService.FindByUsername(accountName) as TUser);
 }