public async Task<IHttpActionResult> RegisterUser(UserAccountBindingModel model) { if (model == null) { return this.BadRequest("Invalid user data"); } if (!this.ModelState.IsValid) { return this.BadRequest(this.ModelState); } var user = new User { UserName = model.Username }; var identityResult = await this.UserManager.CreateAsync(user, model.Password); if (!identityResult.Succeeded) { return this.GetErrorResult(identityResult); } // Auto login after registrаtion (successful user registration should return access_token) var loginResult = await this.LoginUser(new UserAccountBindingModel { Username = model.Username, Password = model.Password }); return loginResult; }
public async Task<IHttpActionResult> LoginUser(UserAccountBindingModel model) { if (model == null) { return this.BadRequest("Invalid user data"); } // Invoke the "token" OWIN service to perform the login (POST /api/token) var testServer = TestServer.Create<Startup>(); var requestParams = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("grant_type", "password"), new KeyValuePair<string, string>("username", model.Username), new KeyValuePair<string, string>("password", model.Password) }; var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams); var tokenServiceResponse = await testServer.HttpClient.PostAsync( Startup.TokenEndpointPath, requestParamsFormUrlEncoded); return this.ResponseMessage(tokenServiceResponse); }
// // This test will not run corectly, because we cannot mock the "POST /api/token" acion // // [TestMethod] public void Login_ValidUser_ShouldReturn200OkSessionToken() { // Arrange -> mock the data layer var dataLayerMock = new MessagesDataMock(); var userStoreMock = dataLayerMock.UserStore; var userManagerMock = new ApplicationUserManager(userStoreMock); string username = "******"; string password = "******"; userManagerMock.CreateAsync(new User() { UserName = username }, password); var accountController = new AccountController(dataLayerMock); this.SetupControllerForTesting(accountController, "user"); // Act -> Get channel by ID var userModel = new UserAccountBindingModel() { Username = username, Password = password }; var httpResponse = accountController.LoginUser(userModel) .Result.ExecuteAsync(new CancellationToken()).Result; // Assert -> HTTP status code 200 (OK) + correct user data Assert.AreEqual(HttpStatusCode.OK, httpResponse.StatusCode); var userSession = httpResponse.Content.ReadAsAsync<UserSessionModel>().Result; Assert.AreEqual(username, userSession.UserName); Assert.IsNotNull(userSession.Access_Token); }