Esempio n. 1
0
        public AuthenticationControllerTests()
        {
            //setup test database
            settings = new AccountDatabaseSettings()
            {
                AccountsCollectionName       = "accountsCollection",
                AuthenticationCollectionName = "authenticationsCollection",
                ConnectionString             = "ChangeToMongoDBConnectionString",
                DatabaseName = "TestAccountDatabase"
            };
            JwtTokenConfig jwtTokenConfig = new JwtTokenConfig()
            {
                Secret   = "SecretTestingKeyNotForProductionPurposes",
                Issuer   = "AccountService",
                Audience = "",
                AccessTokenExpiration  = 30,
                RefreshTokenExpiration = 30
            };

            AuthenticationManager manager = new AuthenticationManager(settings, jwtTokenConfig);

            controller = new AuthenticationController(manager);

            //mock http requests
            idString = "e70f904b69e7372796e4f799";
            var claim       = new Claim("accountID", idString);
            var httpContext = new Mock <HttpContext>();

            httpContext.Setup(m => m.User.IsInRole("admin")).Returns(true);
            httpContext.Setup(m => m.User.FindFirst(ClaimTypes.NameIdentifier)).Returns(claim);

            var controllerContext = new ControllerContext(new ActionContext(httpContext.Object, new RouteData(), new ControllerActionDescriptor()));

            controller.ControllerContext = controllerContext;
        }
Esempio n. 2
0
        public void Setup()
        {
            _store = Substitute.For <IStore>();

            _userManager                = new UserManager <IdentityUser, string>(_store);
            _passwordHasher             = Substitute.For <IPasswordHasher>();
            _userManager.PasswordHasher = _passwordHasher;
            _authenticationManager      = Substitute.For <IAuthenticationManager>();

            // Create the unit under test.
            uut = new AuthenticationController(_userManager, _authenticationManager);

            // Create and set the controller context.
            var controllerContext = new ControllerContext();

            uut.ControllerContext = controllerContext;

            // Setup data.
            userName = "******";
            password = "******";
            hash     = "hash";

            var iUser = new IdentityUser()
            {
                UserName = userName
            };

            _store.FindByNameAsync(Arg.Is(userName)).Returns(iUser);
            _store.FindByIdAsync(Arg.Is(userName)).Returns(iUser);
            _store.GetLockoutEnabledAsync(Arg.Any <IdentityUser>()).Returns(Task.FromResult(false));
            _store.GetPasswordHashAsync(Arg.Is(iUser)).Returns(Task.FromResult(hash));
            _store.GetTwoFactorEnabledAsync(Arg.Any <IdentityUser>()).Returns(Task.FromResult(false));
        }
        public async Task QuandOnSeConnecte()
        {
            if (_login == _validLogin)
            {
                _user = new User()
                {
                    Login    = _login,
                    Password = _validPassword,
                    NbTentativesConnexions = _nbTentativesConnexions
                };
            }
            _credentialRepository = AuthenticationUtility.BuildCredentialsRepository(_user);
            var controller =
                new AuthenticationController(
                    new AuthenticationUseCase(
                        AuthenticationUtility.BuildTokenRepository(new DateTime(2049, 05, 17)),
                        _credentialRepository));

            var authenticationDto = new AuthenticationDto()
            {
                Login    = this._login,
                Password = this._password
            };

            this._actual = await controller.ConnectAsync(authenticationDto);
        }
        public void LogOn_TokenNotValid_Test()
        {
            string token = "mytoken";

            IRegisteredUserRepository eventDefinitionService = new StubIRegisteredUserRepository()
            {
                GetString = (facebookId) =>
                {
                    Assert.Fail();
                    return(null);
                }
            };
            IFacebookService facebookService = new StubIFacebookService()
            {
                GetUserInformationString = (facebookToken) =>
                {
                    return(null);
                }
            };
            var target = new AuthenticationController(eventDefinitionService, facebookService);

            MyEvents.Api.Authentication.AuthenticationResponse response = target.LogOn(token);

            Assert.IsNull(response);
        }
        protected void buttonResendCode_Click(object sender, EventArgs e)
        {
            string code = AuthenticationController.GetInstance().GenerateCodeAndSend(Session["Email"].ToString());

            Session.Remove("CodeGenerated");
            Session["CodeGenerated"] = code;
        }
Esempio n. 6
0
        public void OnDidLogin(JToken e)
        {
            using (Log.CriticalOperation($"{nameof(OnDidLogin)} Method={DidLoginNotificationType.MethodName}", Serilog.Events.LogEventLevel.Debug)) {
                try {
                    if (e == null)
                    {
                        Log.IsNull(nameof(OnDidLogin));
                    }
                    else
                    {
                        var componentModel = _serviceProvider.GetService(typeof(SComponentModel)) as IComponentModel;
                        Assumes.Present(componentModel);

                        var authenticationController = new AuthenticationController(
                            _settingsServiceFactory.GetOrCreate(nameof(OnDidLogin)),
                            componentModel.GetService <ISessionService>(),
                            _eventAggregator,
                            componentModel.GetService <ICredentialsService>(),
                            componentModel.GetService <IWebviewUserSettingsService>()
                            );

                        authenticationController.CompleteSignin(e["data"]);
                    }
                }
                catch (Exception ex) {
                    Log.Error(ex, "Problem with AutoSignIn");
                }
            }
        }
Esempio n. 7
0
        protected override bool IsAuthorized(HttpActionContext httpContext)
        {
            if (!TryGetAuthorization(httpContext.Request.Headers, out string accessToken))
            {
                return(false);
            }

            var userInformationDictionary = AuthenticationController.GetUserInfoDictionary(accessToken);

            if (!userInformationDictionary.ContainsKey("roles"))
            {
                throw new UnauthorizedAccessException("User has no roles assigned.");
            }

            var userInformation = ESECSecurity.GetUserInformation(userInformationDictionary);

            // Some API endpoints need this user information, so it is inserted into
            // the request here before they process it
            httpContext.Request.Headers.Clear();

            httpContext.Request.Headers.Add("Role", userInformation.Role);
            httpContext.Request.Headers.Add("Name", userInformation.Name);
            httpContext.Request.Headers.Add("Email", userInformation.Email);

            return(ValidateRole(userInformation.Role));
        }
        public void LoginPostTest()
        {
            AuthenticationController controller = new AuthenticationController();
            RedirectToRouteResult    result     = controller.Login(DataProvider.NegativeLoginData[0]) as RedirectToRouteResult;

            Assert.AreEqual("Index", result.RouteValues["action"]);
        }
        public void AuthenticateTokenContainsNameClaims()
        {
            var mockRepository = new MockRepository(MockBehavior.Strict);

            var user = new User(Guid.NewGuid());

            user.Create("user", "password");

            var userService = mockRepository.Create <IUserService>();

            userService.Setup(x => x.Authenticate(It.IsAny <string>(), It.IsAny <string>())).Returns(ServiceResult <User> .Ok(user));
            var jwtConfig = mockRepository.Create <IJwtTokenConfigurationProvider>();

            jwtConfig.SetupGet(x => x.Issuer).Returns("TestIssuer");
            jwtConfig.SetupGet(x => x.Audience).Returns("TestAudience");
            var signingKey = new SymmetricSecurityKey(new HMACSHA256().Key);

            jwtConfig.SetupGet(x => x.Key).Returns(signingKey);

            var controller = new AuthenticationController(userService.Object, jwtConfig.Object);

            var request = new AuthenticationRequest()
            {
                UserName = "******", Password = "******"
            };
            var response = controller.Authenticate(request);

            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.ReadJwtToken(response.Value.Token);

            token.Claims.Should().Contain(x => (x.Type == "nameid") && (x.Value == user.Id.ToString()))
            .And.Contain(x => (x.Type == "unique_name") && (x.Value == user.UserName));

            mockRepository.Verify();
        }
Esempio n. 10
0
        /// <summary>
        /// UserCreateCompleted runs when a new user has been Created
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	07/12/2007	created
        /// </history>
        protected void UserCreateCompleted(object sender, UserUserControlBase.UserCreatedEventArgs e)
        {
            var strMessage = "";

            try
            {
                if (e.CreateStatus == UserCreateStatus.Success)
                {
                    //Assocate alternate Login with User and proceed with Login
                    AuthenticationController.AddUserAuthentication(e.NewUser.UserID, AuthenticationType, UserToken);

                    strMessage = CompleteUserCreation(e.CreateStatus, e.NewUser, e.Notify, true);
                    if ((string.IsNullOrEmpty(strMessage)))
                    {
                        //First update the profile (if any properties have been passed)
                        UpdateProfile(e.NewUser, true);

                        ValidateUser(e.NewUser, true);
                    }
                }
                else
                {
                    AddLocalizedModuleMessage(UserController.GetUserCreateStatus(e.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true);
                }
            }
            catch (Exception exc)             //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Esempio n. 11
0
 /// <summary>
 /// cmdAssociate_Click runs when the associate button is clicked
 /// </summary>
 /// <remarks>
 /// </remarks>
 protected void cmdAssociate_Click(object sender, EventArgs e)
 {
     if ((UseCaptcha && ctlCaptcha.IsValid) || (!UseCaptcha))
     {
         UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
         UserInfo        objUser     = UserController.ValidateUser(PortalId,
                                                                   txtUsername.Text,
                                                                   txtPassword.Text,
                                                                   "DNN",
                                                                   "",
                                                                   PortalSettings.PortalName,
                                                                   AuthenticationLoginBase.GetIPAddress(),
                                                                   ref loginStatus);
         if (loginStatus == UserLoginStatus.LOGIN_SUCCESS)
         {
             //Assocate alternate Login with User and proceed with Login
             AuthenticationController.AddUserAuthentication(objUser.UserID, AuthenticationType, UserToken);
             if (objUser != null)
             {
                 UpdateProfile(objUser, true);
             }
             ValidateUser(objUser, true);
         }
         else
         {
             AddModuleMessage("AssociationFailed", ModuleMessage.ModuleMessageType.RedError, true);
         }
     }
 }
        public void SignUpGetTest()
        {
            AuthenticationController controller = new AuthenticationController();
            ViewResult result = controller.SignUp() as ViewResult;

            Assert.IsNotNull(result);
        }
Esempio n. 13
0
        public async void Me_Returns200OKForValidToken()
        {
            var testUser = new User()
            {
                Id       = 1,
                Email    = "*****@*****.**",
                UserName = "******"
            };
            var testController        = new AuthenticationController(CreateMockUserService(testUser, null).Object);
            var mockControllerContext = new ControllerContext()
            {
                HttpContext = _mockHttpContext
            };

            _mockHttpContext.Request.Headers["Authorization"] = $"bearer {DUMMY_TOKEN}";
            testController.ControllerContext = mockControllerContext;

            var result = await testController.Me();

            Assert.IsType <OkObjectResult>(result);

            var expected = ((result as OkObjectResult).Value as UserDto);

            Assert.Equal(expected.Id, testUser.Id);
            Assert.Equal(expected.Email, testUser.Email);
        }
        public void LogoffTest_View()
        {
            #region Setup Test Data

            var controller = new AuthenticationController();

            Mock <IFormsAuthentication> formsAuthenticationMock = new Mock <IFormsAuthentication>();
            controller.FormsAuth = formsAuthenticationMock.Object;
            formsAuthenticationMock.Setup(p => p.SignOut());

            #endregion


            #region Execute Test

            var result = controller.Logoff();

            #endregion


            #region Evaluate Results

            RedirectToRouteResult redirectResult = (RedirectToRouteResult)result;
            Assert.AreEqual("Login", redirectResult.RouteValues["action"],
                            "Logoff should redirect to Login");

            #endregion
        }
Esempio n. 15
0
        public async Task AuthenticateOk()
        {
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddJsonFile("appSettings.json");

            IConfiguration configuration = configurationBuilder.Build();

            var repository     = new MeetingRepository(configuration);
            var weatherService = new WeatherService();

            IOptions <PaginationOptions> options = Options.Create(new PaginationOptions());

            var meetingController = new MeetingController(
                new MeetingService(repository, weatherService, options));

            var user = new UserLoginDto
            {
                Username = "******",
                Password = "******"
            };
            var userRepo    = new UserRepository(configuration);
            var userService = new UserService(userRepo, options);

            var authController = new AuthenticationController(configuration, userService);

            var token = await authController.Authenticate(user);

            Assert.AreEqual(token.GetType(), typeof(OkObjectResult));

            await Task.CompletedTask;
        }
Esempio n. 16
0
        public async Task AdminLogin_Should_Return_AuthenticationToken_When_Credentials_Are_Valid()
        {
            var userServiceMock = new Mock <IPearUpAuthenticationService>();
            var adminLoginDTO   = new AdminCredentialsDTO
            {
                EmailId  = "*****@*****.**",
                Password = "******"
            };

            userServiceMock.Setup(us => us.AuthenticateAdmin(adminLoginDTO.EmailId, adminLoginDTO.Password)).ReturnsAsync(Result.Ok(admin));
            var tokenProviderMock = new Mock <ITokenProvider>();

            var authTokenMock = new Mock <IAuthToken>();

            authTokenMock.Setup(a => a.Value).Returns(VALID_AUTH_TOKEN);
            tokenProviderMock.Setup(tp => tp.CreateToken(It.IsAny <TokenInfo>(), It.IsAny <bool>())).Returns(Result.Ok(authTokenMock.Object));
            var controller = new AuthenticationController(userServiceMock.Object, tokenProviderMock.Object);

            var actualResult = await controller.AdminLogin(adminLoginDTO);

            Assert.IsAssignableFrom <OkObjectResult>(actualResult);
            var contentResult = actualResult as OkObjectResult;

            Assert.AreEqual(200, contentResult.StatusCode.Value);
            var actualValue = contentResult.Value as Result <AdminAuthDto>;

            Assert.IsTrue(actualValue.IsSuccessed);
        }
Esempio n. 17
0
        public async Task Login_Should_Return_AuthenticationToken_When_Credentials_Are_Valid()
        {
            var userServiceMock   = new Mock <IPearUpAuthenticationService>();
            var tokenProviderMock = new Mock <ITokenProvider>();
            var userLoginDTO      = new UserCredentialsDTO
            {
                PhoneNumber = "9999999999",
                Password    = "******"
            };

            var user = await Builders.UserBuilder.Builder().BuildAsync();

            var authTokenMock = new Mock <IAuthToken>();

            authTokenMock.Setup(a => a.Value).Returns(VALID_AUTH_TOKEN);

            userServiceMock.Setup(us => us.Authenticate(userLoginDTO.PhoneNumber, userLoginDTO.Password)).ReturnsAsync(Result.Ok(user));
            tokenProviderMock.Setup(tp => tp.CreateToken(It.IsAny <TokenInfo>(), It.IsAny <bool>())).Returns(Result.Ok(authTokenMock.Object));
            var controller = new AuthenticationController(userServiceMock.Object, tokenProviderMock.Object);

            var actualResult = await controller.Login(userLoginDTO);

            Assert.IsAssignableFrom <OkObjectResult>(actualResult);
            var contentResult = actualResult as OkObjectResult;

            Assert.AreEqual(200, contentResult.StatusCode.Value);
            Assert.IsAssignableFrom <LoginResponseDTO>(contentResult.Value);
            var actualValue = contentResult.Value as LoginResponseDTO;

            Assert.AreEqual(VALID_AUTH_TOKEN, actualValue.Token);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            bool secondStep = Session["CodeValidation"] != null && (bool)Session["CodeValidation"];

            if (Session["UserObj"] != null)
            {
                if (!IsPostBack)
                {
                    User   user = (User)Session["UserObj"];
                    string code = AuthenticationController.GetInstance().GenerateCodeAndSend(user.Email);
                    secondStep = true;
                    Session["CodeGenerated"]  = code;
                    Session["CodeValidation"] = true;
                    Session["Email"]          = user.Email;
                }
            }

            if (secondStep)
            {
                RequestEmail.Visible = false;
                CheckCode.Visible    = true;
            }
            else
            {
                RequestEmail.Visible = true;
                CheckCode.Visible    = false;
            }
        }
        public void LogOn_Logged_Test()
        {
            string token = "mytoken";

            IRegisteredUserRepository eventDefinitionService = new StubIRegisteredUserRepository()
            {
                AddRegisteredUser = (user) =>
                {
                    Assert.AreEqual(user.FacebookId, "facebookId");
                    return(10);
                }
            };
            IFacebookService facebookService = new StubIFacebookService()
            {
                GetUserInformationString = (facebookToken) =>
                {
                    return(new Model.RegisteredUser()
                    {
                        FacebookId = "facebookId"
                    });
                }
            };
            var target = new AuthenticationController(eventDefinitionService, facebookService);

            MyEvents.Api.Authentication.AuthenticationResponse response = target.LogOn(token);

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Token);
        }
        protected void OnUpdateClick(object sender, EventArgs e)
        {
            foreach (var settingControl in _settingControls)
            {
                settingControl.UpdateSettings();
            }

            //Validate Enabled
            var enabled     = false;
            var authSystems = AuthenticationController.GetEnabledAuthenticationServices();

            foreach (var authSystem in authSystems)
            {
                var authLoginControl = (AuthenticationLoginBase)LoadControl("~/" + authSystem.LoginControlSrc);

                //Check if AuthSystem is Enabled
                if (authLoginControl.Enabled)
                {
                    enabled = true;
                    break;
                }
            }
            if (!enabled)
            {
                //Display warning
                UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NoProvidersEnabled", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning);
            }
        }
Esempio n. 21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String username = Request.Form["username"];
            String password = Request.Form["password"];

            AuthenticationController authController = new AuthenticationController();
            User user = authController.actionCheckLoginData(username, password);

            if (user == null || (user.user_type != 1 && user.user_type != 2))
            {
                Response.Cookies.Add(new HttpCookie("flash_message", "Invilid Login.")
                {
                    Path = "/"
                });
                Response.Cookies.Add(new HttpCookie("flash_css", "alert alert-error")
                {
                    Path = "/"
                });
                Response.Redirect("~/m/Login.aspx");
                return;
            }

            Session["user"] = null;
            Session["user"] = user;

            redirectByUserType(user.user_type);
        }
        public async Task RegisterUser_ReturnsJsonMessege_WhenUserAlreadyExists()
        {
            // Arrange
            string userEmail = "*****@*****.**";
            User   user      = new User
            {
                Name     = "TestName",
                Surname  = "TestSurname",
                Email    = userEmail,
                Password = "******"
            };
            User newUser = new User
            {
                Name     = "AnotherName",
                Surname  = "AnotherSurname",
                Email    = userEmail,
                Password = "******"
            };
            var controller = new AuthenticationController();
            // Act
            var result = controller.Register(newUser);

            // Assert
            Assert.Same(result, JsonConvert.SerializeObject("A user with this Email already exists!"));
        }
Esempio n. 23
0
        private static Hashtable GetModuleSettings(PortalSettings portalSettings, ModuleInfo moduleInfo, int uniqueId)
        {
            var usePopup =
                portalSettings.EnablePopUps &&
                portalSettings.LoginTabId == Null.NullInteger &&
                !AuthenticationController.HasSocialAuthenticationEnabled();

            var navigationKey =
                moduleInfo != null &&
                moduleInfo.DesktopModule != null
                    ? GetHistoryNavigationKey(moduleInfo.DesktopModule.FriendlyName)
                    : null;

            var moduleRoot =
                moduleInfo != null &&
                moduleInfo.DesktopModule != null
                    ? moduleInfo.DesktopModule.FolderName
                    : null;

            var moduleTitle = moduleInfo != null
                ? moduleInfo.ModuleTitle
                : null;

            var moduleId = moduleInfo != null ? moduleInfo.ModuleID : Null.NullInteger;

            var moduleSettings = moduleInfo != null ? moduleInfo.ModuleSettings : new Hashtable();

            var debug = false;

#if DEBUG
            debug = true;
#else
            if (HttpContext.Current != null)
            {
                debug = HttpContext.Current.IsDebuggingEnabled;
            }
#endif

            return(new Hashtable
            {
                { "anonymous", PortalSettings.Current.UserId < 0 },
                { "currentUserId", PortalSettings.Current.UserId },
                { "debug", debug },
                { "culture", CultureInfo.CurrentUICulture.Name },
                { "showMissingKeys", Localization.ShowMissingKeys },
                { "portalId", portalSettings.PortalId },
                { "moduleId", moduleId },
                { "moduleSettings", moduleSettings },
                { "moduleTitle", moduleTitle },
                { "moduleRoot", moduleRoot },
                { "navigationKey", navigationKey },
                { "sessionTimeout", Convert.ToInt32(GetSessionTimeout().TotalMinutes) },
                { "sharedResources", GetSharedResources() },
                { "authorizationUrl", GetLoginUrl(portalSettings) },
                { "usePopup", usePopup },
                { "returnUrl", HttpContext.Current.Request.UrlReferrer },
                { "uniqueId", uniqueId },
            });
        }
 public void Before()
 {
     ctrl = new AuthenticationController()
     {
         Request       = new HttpRequestMessage(),
         Configuration = new System.Web.Http.HttpConfiguration()
     };
 }
Esempio n. 25
0
        public void Init(HttpApplication application)
        {
            //Call this method to make sure that portalsettings is stored in Context
            PortalSettings portalSettings = Globals.GetPortalSettings();

            AuthenticationController.SetStatus(portalSettings.PortalId, AuthenticationStatus.Undefined);
            application.AuthenticateRequest += new EventHandler(this.OnAuthenticateRequest);
        }
Esempio n. 26
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         usernameInput.Text = AuthenticationController.getEmailFromCookie(Request);
         passwordInput.Attributes.Add("value", AuthenticationController.getPasswordFromCookie(Request));
     }
 }
Esempio n. 27
0
        public async void Register_Returns_422Error_WithEmptyUserDto()
        {
            var testUserService = CreateMockUserService(null, null);
            var testController  = new AuthenticationController(testUserService.Object);
            var result          = await testController.Register(new UserDto());

            Assert.IsType <UnprocessableEntityObjectResult>(result);
        }
 public void Initialize()
 {
     httpContext      = new MockHttpContextWrapper();
     controllerToTest = new AuthenticationController();
     controllerToTest.ControllerContext = new ControllerContext(httpContext.Context.Object, new RouteData(), controllerToTest);
     dbContext = new DAL.SchoolContext(this.ConnectionString);
     controllerToTest.DbContext = dbContext;
 }
        public void SignUpPostTest()
        {
            AuthenticationController controller = new AuthenticationController();
            ViewResult  result = controller.SignUp(DataProvider.NegativeSignUpData[0]) as ViewResult;
            SignUpModel model  = (SignUpModel)result.ViewData.Model;

            Assert.AreEqual(DataProvider.NegativeSignUpData[0].Username, model.Username);
        }
Esempio n. 30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            AuthenticationController controller = new AuthenticationController();

            controller.Logout();

            FormsAuthentication.SignOut();
        }
        public void LoginReturnsCorrectViewTest()
        {
            AuthenticationController controller = new AuthenticationController();

            ViewResult result = controller.Login() as ViewResult;

            Assert.IsNotNull(result);
        }
        public void LoginReturnsCorrectViewIfUsernameNotFoundTest()
        {
            Mock<IUserManager> umMock = new Mock<IUserManager>();
            Mock<IFormsAuthenticationWrap> formsAuthMock = new Mock<IFormsAuthenticationWrap>();
            AuthenticationController controller = new AuthenticationController(umMock.Object, formsAuthMock.Object);

            LoginView loginView = new LoginView();
            loginView.Username = "******";

            umMock.Setup(um => um.IsUsernameInUse(It.Is<string>(s => s.Equals(loginView.Username)))).Returns(false);

            ViewResult result = controller.Login(loginView) as ViewResult;

            Assert.IsNotNull(result);
            ModelState paramState;
            Assert.IsTrue(controller.ModelState.TryGetValue("non_existent_user", out paramState));
            Assert.DoesNotThrow(() =>
                paramState.Errors.Single(s => s.ErrorMessage.Equals("User doesn't exist.")));

            umMock.Verify(um => um.IsUsernameInUse(It.Is<string>(s => s.Equals(loginView.Username))), Times.Once());
        }
    void HandleOnLoginStateChange(AuthenticationController.LoginStates state)
    {
        switch(state)
        {
            case AuthenticationController.LoginStates.Auto:
                green.transform.FindChild("Text").GetComponent<Text>().text = "Enter Account Manually";
                yellow.transform.FindChild("Text").GetComponent<Text>().text = "Register";
                //red.transform.FindChild("Text").GetComponent<Text>().text = "Exit";
            break;

            case AuthenticationController.LoginStates.Manual:
                green.transform.FindChild("Text").GetComponent<Text>().text = "Use Device Id";
                yellow.transform.FindChild("Text").GetComponent<Text>().text = "Register";
                //red.transform.FindChild("Text").GetComponent<Text>().text = "Exit";
            break;

            case AuthenticationController.LoginStates.Register:
                green.transform.FindChild("Text").GetComponent<Text>().text = "Use Device Id";
                yellow.transform.FindChild("Text").GetComponent<Text>().text = "Enter Account Manually";
                //red.transform.FindChild("Text").GetComponent<Text>().text = "Exit";
            break;
        }
    }
        public void LoginReturnsCorrectViewIfLoginSucceedsTest()
        {
            Mock<IUserManager> umMock = new Mock<IUserManager>();
            Mock<IFormsAuthenticationWrap> formsAuthMock = new Mock<IFormsAuthenticationWrap>();
            AuthenticationController controller = new AuthenticationController(umMock.Object, formsAuthMock.Object);

            LoginView loginView = new LoginView();
            loginView.Username = "******";

            umMock.Setup(um => um.IsUsernameInUse(It.Is<string>(s => s.Equals(loginView.Username)))).Returns(true);
            umMock.Setup(um => um.LoginCheck(It.Is<LoginView>(lw => lw.Equals(loginView)))).Returns(true);

            RedirectToRouteResult result = controller.Login(loginView) as RedirectToRouteResult;

            Assert.IsNotNull(result);

            Assert.AreEqual("Index", result.RouteValues["action"]);
            Assert.AreEqual("Home", result.RouteValues["controller"]);

            umMock.Verify(um => um.IsUsernameInUse(It.Is<string>(s => s.Equals(loginView.Username))), Times.Once());
            umMock.Verify(um => um.LoginCheck(It.Is<LoginView>(lw => lw.Equals(loginView))), Times.Once());
            formsAuthMock.Verify(fam => fam.SetAuthCookie(It.Is<string>(s => s.Equals(loginView.Username)), false), Times.Once());
        }
 public static void VerifyExternalLinkExpiredResult(AuthenticationController controller, ActionResult result) {
     ResultAssert.IsRedirectToRoute(result, new { action = "LogOn" });
     Assert.Equal(Strings.ExternalAccountLinkExpired, controller.TempData["Message"]);
 }
        public void LoginReturnsCorrectViewIfModelStateIsInvalidTest()
        {
            Mock<IUserManager> umMock = new Mock<IUserManager>();
            Mock<IFormsAuthenticationWrap> formsAuthMock = new Mock<IFormsAuthenticationWrap>();
            AuthenticationController controller = new AuthenticationController(umMock.Object, formsAuthMock.Object);

            controller.ModelState.AddModelError("key", "error message");

            ViewResult result = controller.Login(new LoginView()) as ViewResult;

            Assert.IsNotNull(result);
        }
        public void RegisterReturnsCorrectViewOnNonMatchingPasswordsTest()
        {
            AuthenticationController controller = new AuthenticationController(null, null);

            RegisterView registerView = new RegisterView();
            registerView.Password = "******";
            registerView.PasswordVerify = "abc123";
            
            ViewResult result = controller.Register(registerView) as ViewResult;
            Assert.IsNotNull(result);
            ModelState paramState;
            Assert.IsTrue(controller.ModelState.TryGetValue("verify_pass", out paramState));
            Assert.DoesNotThrow(() =>
                paramState.Errors.Single(s => s.ErrorMessage.Equals("Password verification failed!")));
        }
        public void RegisterReturnsCorrectViewOnTakenUsernameTest()
        {
            Mock<IUserManager> umMock = new Mock<IUserManager>();
            AuthenticationController controller = new AuthenticationController(umMock.Object, null);

            RegisterView registerView = new RegisterView();
            registerView.Username = "******";
            registerView.Password = registerView.PasswordVerify = "pass";

            umMock.Setup(um => um.IsUsernameInUse(It.Is<string>(s => s.Equals(registerView.Username)))).Returns(true);

            ViewResult result = controller.Register(registerView) as ViewResult;

            Assert.IsNotNull(result);
            ModelState paramState;
            Assert.IsTrue(controller.ModelState.TryGetValue("username_in_use", out paramState));
            Assert.DoesNotThrow(() =>
                paramState.Errors.Single(s => s.ErrorMessage.Equals("Username already in use!")));

            umMock.Verify(um => um.IsUsernameInUse(It.Is<string>(s => s.Equals(registerView.Username))), Times.Once());
        }
        public void SignOutRedirectsToHomeTest()
        {
            Mock<IUserManager> umMock = new Mock<IUserManager>();
            Mock<IFormsAuthenticationWrap> formsAuthMock = new Mock<IFormsAuthenticationWrap>();
            AuthenticationController controller = new AuthenticationController(umMock.Object, formsAuthMock.Object);

            RedirectToRouteResult result = controller.SignOut() as RedirectToRouteResult;

            Assert.AreEqual("Index", result.RouteValues["action"]);
            Assert.AreEqual("Home", result.RouteValues["controller"]);
        }
        public void SignOutSignsUserOutTest()
        {
            Mock<IUserManager> umMock = new Mock<IUserManager>();
            Mock<IFormsAuthenticationWrap> formsAuthMock = new Mock<IFormsAuthenticationWrap>();
            AuthenticationController controller = new AuthenticationController(umMock.Object, formsAuthMock.Object);

            controller.SignOut();

            formsAuthMock.Verify(fam => fam.SignOut(), Times.Once());
        }