コード例 #1
0
ファイル: ApiController.cs プロジェクト: jonwchu/NuGetGallery
        public async virtual Task <ActionResult> CreatePackageVerificationKeyAsync(string id, string version)
        {
            // For backwards compatibility, we must preserve existing behavior where the client always pushes
            // symbols and the VerifyPackageKey callback returns the appropriate response. For this reason, we
            // always create a temp key scoped to the unverified package ID here and defer package and owner
            // validation until the VerifyPackageKey call.
            var credential = CredentialBuilder.CreatePackageVerificationApiKey(id);

            var user = GetCurrentUser();
            await AuthenticationService.AddCredential(user, credential);

            TelemetryService.TrackCreatePackageVerificationKeyEvent(id, version, user, User.Identity);

            return(Json(new
            {
                Key = credential.Value,
                Expires = credential.Expires.Value.ToString("O")
            }));
        }
コード例 #2
0
            public void UsesTypeCaptionToDescribeCredentialIfNoProviderNounPresent()
            {
                var user = new User {
                    EmailAddress = "*****@*****.**", Username = "******"
                };
                var cred = new CredentialBuilder().CreatePasswordCredential("bogus");

                var messageService = TestableMessageService.Create(
                    GetService <AuthenticationService>(),
                    GetConfigurationService());

                messageService.SendCredentialAddedNotice(user, cred);
                var message = messageService.MockMailSender.Sent.Last();

                Assert.Equal(user.ToMailAddress(), message.To[0]);
                Assert.Equal(TestGalleryOwner, message.From);
                Assert.Equal(string.Format(Strings.Emails_CredentialAdded_Subject, TestGalleryOwner.DisplayName, Strings.CredentialType_Password), message.Subject);
                Assert.Contains(string.Format(Strings.Emails_CredentialAdded_Body, Strings.CredentialType_Password), message.Body);
            }
コード例 #3
0
            public void UsesProviderNounToDescribeCredentialIfPresent()
            {
                var user = new User {
                    EmailAddress = "*****@*****.**", Username = "******"
                };
                var          cred = new CredentialBuilder().CreateExternalCredential("MicrosoftAccount", "abc123", "Test User");
                const string MicrosoftAccountCredentialName = "Microsoft account";

                var messageService = TestableMessageService.Create(
                    GetService <AuthenticationService>(),
                    GetConfigurationService());

                messageService.SendCredentialAddedNotice(user, cred);
                var message = messageService.MockMailSender.Sent.Last();

                Assert.Equal(user.ToMailAddress(), message.To[0]);
                Assert.Equal(TestGalleryOwner, message.From);
                Assert.Equal(string.Format(Strings.Emails_CredentialAdded_Subject, TestGalleryOwner.DisplayName, MicrosoftAccountCredentialName), message.Subject);
                Assert.Contains(string.Format(Strings.Emails_CredentialAdded_Body, MicrosoftAccountCredentialName), message.Body);
            }
コード例 #4
0
            public void ApiKeyAddedMessageIsCorrect()
            {
                var user = new User {
                    EmailAddress = "*****@*****.**", Username = "******"
                };
                var cred = new CredentialBuilder().CreateApiKey(TimeSpan.FromDays(1));

                cred.Description = "new api key";

                var messageService = TestableMessageService.Create(
                    GetService <AuthenticationService>(),
                    GetConfigurationService());

                messageService.SendCredentialAddedNotice(user, cred);
                var message = messageService.MockMailSender.Sent.Last();

                Assert.Equal(user.ToMailAddress(), message.To[0]);
                Assert.Equal(TestGalleryOwner, message.From);
                Assert.Equal(string.Format(Strings.Emails_CredentialAdded_Subject, TestGalleryOwner.DisplayName, Strings.CredentialType_ApiKey), message.Subject);
                Assert.Contains(string.Format(Strings.Emails_ApiKeyAdded_Body, cred.Description), message.Body);
            }
コード例 #5
0
            public async Task GivenFailureInAuthService_ItAddsModelError()
            {
                // Arrange
                var user = new User("foo");

                user.Credentials.Add(CredentialBuilder.CreatePbkdf2Password("old"));

                GetMock <AuthenticationService>()
                .Setup(u => u.ChangePassword(user, "old", "new", false))
                .CompletesWith(false);

                var controller = GetController <UsersController>();

                controller.SetCurrentUser(user);

                var inputModel = new AccountViewModel()
                {
                    ChangePassword = new ChangePasswordViewModel()
                    {
                        OldPassword = "******",
                        NewPassword = "******",
                    }
                };

                // Act
                var result = await controller.ChangePassword(inputModel);

                // Assert
                var outputModel = ResultAssert.IsView <AccountViewModel>(result, viewName: "Account");

                Assert.Same(inputModel, outputModel);

                var errorMessages = controller
                                    .ModelState["ChangePassword.OldPassword"]
                                    .Errors
                                    .Select(e => e.ErrorMessage)
                                    .ToArray();

                Assert.Equal(errorMessages, new[] { Strings.CurrentPasswordIncorrect });
            }
コード例 #6
0
            public void UsesTypeCaptionToDescribeCredentialIfNoProviderNounPresent()
            {
                var user = new User {
                    EmailAddress = "*****@*****.**", Username = "******"
                };
                var cred           = new CredentialBuilder().CreatePasswordCredential("bogus");
                var messageService = new TestableMessageService();

                messageService.MockAuthService
                .Setup(a => a.DescribeCredential(cred))
                .Returns(new CredentialViewModel {
                    TypeCaption = "Password"
                });

                messageService.SendCredentialAddedNotice(user, cred);
                var message = messageService.MockMailSender.Sent.Last();

                Assert.Equal(user.ToMailAddress(), message.To[0]);
                Assert.Equal(TestGalleryOwner, message.From);
                Assert.Equal("[Joe Shmoe] Password added to your account", message.Subject);
                Assert.Contains("A Password was added to your account", message.Body);
            }
コード例 #7
0
            public void UsesProviderNounToDescribeCredentialIfPresent()
            {
                var user = new User {
                    EmailAddress = "*****@*****.**", Username = "******"
                };
                var cred           = new CredentialBuilder().CreateExternalCredential("MicrosoftAccount", "abc123", "Test User");
                var messageService = new TestableMessageService();

                messageService.MockAuthService
                .Setup(a => a.DescribeCredential(cred))
                .Returns(new CredentialViewModel {
                    AuthUI = new AuthenticatorUI("sign in", "Microsoft Account", "Microsoft Account")
                });

                messageService.SendCredentialAddedNotice(user, cred);
                var message = messageService.MockMailSender.Sent.Last();

                Assert.Equal(user.ToMailAddress(), message.To[0]);
                Assert.Equal(TestGalleryOwner, message.From);
                Assert.Equal("[Joe Shmoe] Microsoft Account added to your account", message.Subject);
                Assert.Contains("A Microsoft Account was added to your account", message.Body);
            }
コード例 #8
0
            public void UsesTypeCaptionToDescribeCredentialIfNoProviderNounPresent()
            {
                var user = new User {
                    EmailAddress = "*****@*****.**", Username = "******"
                };
                var cred           = new CredentialBuilder().CreatePasswordCredential("bogus");
                var messageService = new TestableMessageService();

                messageService.MockAuthService
                .Setup(a => a.DescribeCredential(cred))
                .Returns(new CredentialViewModel()
                {
                    TypeCaption = Strings.CredentialType_Password
                });

                messageService.SendCredentialRemovedNotice(user, cred);
                var message = messageService.MockMailSender.Sent.Last();

                Assert.Equal(user.ToMailAddress(), message.To[0]);
                Assert.Equal(TestGalleryOwner, message.From);
                Assert.Equal(string.Format(Strings.Emails_CredentialRemoved_Subject, TestGalleryOwner.DisplayName, Strings.CredentialType_Password), message.Subject);
                Assert.Contains(string.Format(Strings.Emails_CredentialRemoved_Body, Strings.CredentialType_Password), message.Body);
            }
コード例 #9
0
            public void UsesProviderNounToDescribeCredentialIfPresent()
            {
                var user = new User {
                    EmailAddress = "*****@*****.**", Username = "******"
                };
                var          cred = new CredentialBuilder().CreateExternalCredential("MicrosoftAccount", "abc123", "Test User");
                const string MicrosoftAccountCredentialName = "Microsoft Account";
                var          messageService = new TestableMessageService();

                messageService.MockAuthService
                .Setup(a => a.DescribeCredential(cred))
                .Returns(new CredentialViewModel
                {
                    AuthUI = new AuthenticatorUI("sign in", "register", MicrosoftAccountCredentialName)
                });

                messageService.SendCredentialRemovedNotice(user, cred);
                var message = messageService.MockMailSender.Sent.Last();

                Assert.Equal(user.ToMailAddress(), message.To[0]);
                Assert.Equal(TestGalleryOwner, message.From);
                Assert.Equal(string.Format(Strings.Emails_CredentialRemoved_Subject, TestGalleryOwner.DisplayName, MicrosoftAccountCredentialName), message.Subject);
                Assert.Contains(string.Format(Strings.Emails_CredentialRemoved_Body, MicrosoftAccountCredentialName), message.Body);
            }
コード例 #10
0
            public void LoadsDescriptionsOfCredentialsInToViewModel()
            {
                // Arrange
                var credentialBuilder = new CredentialBuilder();
                var fakes = Get<Fakes>();
                var user = fakes.CreateUser(
                    "test",
                    credentialBuilder.CreatePasswordCredential("hunter2"),
                    TestCredentialBuilder.CreateV1ApiKey(Guid.NewGuid(), Fakes.ExpirationForApiKeyV1),
                    credentialBuilder.CreateExternalCredential("MicrosoftAccount", "blarg", "Bloog"));
                var controller = GetController<UsersController>();
                controller.SetCurrentUser(user);

                // Act
                var result = controller.Account();

                // Assert
                var model = ResultAssert.IsView<AccountViewModel>(result, viewName: "Account");
                var descs = model.Credentials.ToDictionary(c => c.Kind); // Should only be one of each kind
                Assert.Equal(3, descs.Count);
                Assert.Equal(Strings.CredentialType_Password, descs[CredentialKind.Password].TypeCaption);
                Assert.Equal(Strings.CredentialType_ApiKey, descs[CredentialKind.Token].TypeCaption);
                Assert.Equal(Strings.MicrosoftAccount_Caption, descs[CredentialKind.External].TypeCaption);
            }
コード例 #11
0
            public void LoadsDescriptionsOfCredentialsInToViewModel()
            {
                // Arrange
                var user = Fakes.CreateUser(
                    "test",
                    CredentialBuilder.CreatePbkdf2Password("hunter2"),
                    CredentialBuilder.CreateV1ApiKey(Guid.NewGuid()),
                    CredentialBuilder.CreateExternalCredential("MicrosoftAccount", "blarg", "Bloog"));
                var controller = GetController <UsersController>();

                controller.SetCurrentUser(user);

                // Act
                var result = controller.Account();

                // Assert
                var model = ResultAssert.IsView <AccountViewModel>(result, viewName: "Account");
                var descs = model.Credentials.ToDictionary(c => c.Kind); // Should only be one of each kind

                Assert.Equal(3, descs.Count);
                Assert.Equal(Strings.CredentialType_Password, descs[CredentialKind.Password].TypeCaption);
                Assert.Equal(Strings.CredentialType_ApiKey, descs[CredentialKind.Token].TypeCaption);
                Assert.Equal(Strings.MicrosoftAccount_Caption, descs[CredentialKind.External].TypeCaption);
            }
コード例 #12
0
            public async Task GivenInvalidView_ItReturnsView()
            {
                // Arrange
                var controller = GetController <UsersController>();

                controller.ModelState.AddModelError("ChangePassword.blarg", "test");
                var inputModel = new AccountViewModel();

                controller.SetCurrentUser(new User()
                {
                    Credentials = new List <Credential>()
                    {
                        CredentialBuilder.CreatePbkdf2Password("abc")
                    }
                });

                // Act
                var result = await controller.ChangePassword(inputModel);

                // Assert
                var outputModel = ResultAssert.IsView <AccountViewModel>(result, viewName: "Account");

                Assert.Same(inputModel, outputModel);
            }
        public async virtual Task <ActionResult> Register(LogOnViewModel model, string returnUrl, bool linkingAccount)
        {
            // I think it should be obvious why we don't want the current URL to be the return URL here ;)
            ViewData[Constants.ReturnUrlViewDataKey] = returnUrl;

            if (Request.IsAuthenticated)
            {
                TempData["Message"] = Strings.AlreadyLoggedIn;
                return(SafeRedirect(returnUrl));
            }

            if (linkingAccount)
            {
                ModelState.Remove("Register.Password");
            }

            if (!ModelState.IsValid)
            {
                return(LogOnView(model));
            }

            AuthenticatedUser user;

            try
            {
                if (linkingAccount)
                {
                    var result = await AuthService.ReadExternalLoginCredential(OwinContext);

                    if (result.ExternalIdentity == null)
                    {
                        return(ExternalLinkExpired());
                    }

                    user = await AuthService.Register(
                        model.Register.Username,
                        model.Register.EmailAddress,
                        result.Credential);
                }
                else
                {
                    user = await AuthService.Register(
                        model.Register.Username,
                        model.Register.EmailAddress,
                        CredentialBuilder.CreatePbkdf2Password(model.Register.Password));
                }
            }
            catch (EntityException ex)
            {
                ModelState.AddModelError("Register", ex.Message);
                return(LogOnView(model));
            }

            // Send a new account email
            if (NuGetContext.Config.Current.ConfirmEmailAddresses && !String.IsNullOrEmpty(user.User.UnconfirmedEmailAddress))
            {
                MessageService.SendNewAccountEmail(
                    new MailAddress(user.User.UnconfirmedEmailAddress, user.User.Username),
                    Url.ConfirmationUrl(
                        "Confirm",
                        "Users",
                        user.User.Username,
                        user.User.EmailConfirmationToken));
            }

            // We're logging in!
            AuthService.CreateSession(OwinContext, user.User);

            return(RedirectFromRegister(returnUrl));
        }
コード例 #14
0
            public void UsesTypeCaptionToDescribeCredentialIfNoProviderNounPresent()
            {
                var user = new User { EmailAddress = "*****@*****.**", Username = "******" };
                var cred = new CredentialBuilder().CreatePasswordCredential("bogus");
                var messageService = new TestableMessageService();
                messageService.MockAuthService
                    .Setup(a => a.DescribeCredential(cred))
                    .Returns(new CredentialViewModel {
                        TypeCaption = "Password"
                    });

                messageService.SendCredentialAddedNotice(user, cred);
                var message = messageService.MockMailSender.Sent.Last();

                Assert.Equal(user.ToMailAddress(), message.To[0]);
                Assert.Equal(TestGalleryOwner, message.From);
                Assert.Equal("[Joe Shmoe] Password added to your account", message.Subject);
                Assert.Contains("A Password was added to your account", message.Body);
            }
コード例 #15
0
            public async Task GivenNoOtherLoginCredentials_ItRedirectsBackWithAnErrorMessage()
            {
                // Arrange
                var fakes = Get<Fakes>();
                var cred = new CredentialBuilder().CreateExternalCredential("MicrosoftAccount", "blorg", "bloog");
                var user = fakes.CreateUser("test", cred);
                var controller = GetController<UsersController>();
                controller.SetCurrentUser(user);

                // Act
                var result = await controller.RemoveCredential(cred.Type);

                // Assert
                ResultAssert.IsRedirectToRoute(result, new { action = "Account" });
                Assert.Equal(Strings.CannotRemoveOnlyLoginCredential, controller.TempData["Message"]);
                Assert.Equal(1, user.Credentials.Count);
            }
コード例 #16
0
            public async Task GivenValidRequest_ItRemovesCredAndSendsNotificationToUser()
            {
                // Arrange
                var credentialBuilder = new CredentialBuilder();
                var fakes = Get<Fakes>();
                var cred = credentialBuilder.CreateExternalCredential("MicrosoftAccount", "blorg", "bloog");
                var user = fakes.CreateUser("test",
                    cred,
                    credentialBuilder.CreatePasswordCredential("password"));

                GetMock<AuthenticationService>()
                    .Setup(a => a.RemoveCredential(user, cred))
                    .Completes()
                    .Verifiable();
                GetMock<IMessageService>()
                    .Setup(m => m.SendCredentialRemovedNotice(user, cred))
                    .Verifiable();

                var controller = GetController<UsersController>();
                controller.SetCurrentUser(user);

                // Act
                var result = await controller.RemoveCredential(cred.Type);

                // Assert
                ResultAssert.IsRedirectToRoute(result, new { action = "Account" });
                GetMock<AuthenticationService>().VerifyAll();
                GetMock<IMessageService>().VerifyAll();
            }
コード例 #17
0
            public void UsesProviderNounToDescribeCredentialIfPresent()
            {
                var user = new User { EmailAddress = "*****@*****.**", Username = "******" };
                var cred = new CredentialBuilder().CreateExternalCredential("MicrosoftAccount", "abc123", "Test User");
                var messageService = new TestableMessageService();
                messageService.MockAuthService
                    .Setup(a => a.DescribeCredential(cred))
                    .Returns(new CredentialViewModel {
                        AuthUI = new AuthenticatorUI("sign in", "Microsoft Account", "Microsoft Account")
                    });

                messageService.SendCredentialAddedNotice(user, cred);
                var message = messageService.MockMailSender.Sent.Last();

                Assert.Equal(user.ToMailAddress(), message.To[0]);
                Assert.Equal(TestGalleryOwner, message.From);
                Assert.Equal("[Joe Shmoe] Microsoft Account added to your account", message.Subject);
                Assert.Contains("A Microsoft Account was added to your account", message.Body);
            }