Search in sources :

Example 11 with UserModel

use of com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel in project ma-modules-public by infiniteautomation.

the class LoginRestV2Controller method loginPost.

/**
 * The actual authentication for the login occurs in the core, by the time this
 * end point is actually reached the user is either already authenticated or not
 * The Spring Security authentication success handler forwards the request here
 *
 * Ensure that the URLs in MangoSecurityConfiguration are changed if you change the @RequestMapping value
 *
 * @throws IOException
 */
@ApiOperation(value = "Login", notes = "Used to login using POST and JSON credentials")
@RequestMapping(method = RequestMethod.POST, produces = { "application/json" })
public ResponseEntity<UserModel> loginPost(@AuthenticationPrincipal User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
    AuthenticationException ex = (AuthenticationException) request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    if (ex != null) {
        // return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        response.sendError(HttpStatus.UNAUTHORIZED.value(), ex.getMessage());
        return null;
    }
    if (user == null) {
        return new ResponseEntity<>(HttpStatus.OK);
    } else {
        String loggedInUri = DefaultPagesDefinition.getDefaultUri(request, response, user);
        response.setHeader(LOGIN_DEFAULT_URI_HEADER, loggedInUri);
        return new ResponseEntity<>(new UserModel(user), HttpStatus.OK);
    }
}
Also used : UserModel(com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel) ResponseEntity(org.springframework.http.ResponseEntity) AuthenticationException(org.springframework.security.core.AuthenticationException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 12 with UserModel

use of com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel in project ma-modules-public by infiniteautomation.

the class LoginRestV2Controller method switchUser.

/**
 * The actual authentication for the switch user occurs in the core by the SwitchUserFilter,
 *  by the time this end point is actually reached the user is either already authenticated or not
 * The Spring Security authentication success handler forwards the request here
 *
 * Ensure that the URLs in MangoSecurityConfiguration are changed if you change the @RequestMapping value
 *
 * @throws IOException
 */
@ApiOperation(value = "Switch User", notes = "Used to switch User using GET")
@RequestMapping(method = RequestMethod.POST, value = "/su", produces = { "application/json" })
public ResponseEntity<UserModel> switchUser(@ApiParam(value = "Username to switch to", required = true, allowMultiple = false) @RequestParam(required = true) String username, @AuthenticationPrincipal User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
    AuthenticationException ex = (AuthenticationException) request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    if (ex != null) {
        // return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        response.sendError(HttpStatus.UNAUTHORIZED.value(), ex.getMessage());
        return null;
    }
    if (user == null) {
        return new ResponseEntity<>(HttpStatus.OK);
    } else {
        String loggedInUri = DefaultPagesDefinition.getDefaultUri(request, response, user);
        response.setHeader(LOGIN_DEFAULT_URI_HEADER, loggedInUri);
        return new ResponseEntity<>(new UserModel(user), HttpStatus.OK);
    }
}
Also used : UserModel(com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel) ResponseEntity(org.springframework.http.ResponseEntity) AuthenticationException(org.springframework.security.core.AuthenticationException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 13 with UserModel

use of com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel in project ma-modules-public by infiniteautomation.

the class LoginFunctionalTests method testLogin.

public void testLogin() {
    User standardUser = UserTestData.standardUser();
    // Mock the Dao Get User Call
    when(userDao.getUser(standardUser.getUsername())).thenReturn(standardUser);
    try {
        MvcResult result = this.mockMvc.perform(post("/v1/login/{username}", standardUser.getUsername()).param("password", UserTestData.standardPassword).accept(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk()).andReturn();
        UserModel loggedInUserModel = this.objectMapper.readValue(result.getResponse().getContentAsString(), UserModel.class);
        User loggedInUser = loggedInUserModel.getData();
        // Check to see that the User is correct
        assertEquals(standardUser.getUsername(), loggedInUser.getUsername());
        // Check to see that the Proper URI is in the Response
        String defaultLoginUri = result.getResponse().getHeader(LoginRestV2Controller.LOGIN_DEFAULT_URI_HEADER).toString();
        assertEquals(standardUser.getHomeUrl(), defaultLoginUri);
        // Ensure the User is in the Session
        // Because Common.SESSION_USER is not public
        User sessionUser = (User) result.getRequest().getSession().getAttribute("sessionUser");
        assertEquals(standardUser.getUsername(), sessionUser.getUsername());
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
Also used : UserModel(com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel) User(com.serotonin.m2m2.vo.User) MvcResult(org.springframework.test.web.servlet.MvcResult)

Example 14 with UserModel

use of com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel in project ma-modules-public by infiniteautomation.

the class UserFunctionalTests method testAdminCreateUser.

/**
 * Test Creating a User
 * TODO This test fails!!!! Because we don't render the password in the JSON property yet. :(
 */
public void testAdminCreateUser() {
    User standardUser = UserTestData.standardUser();
    User adminUser = UserTestData.adminUser();
    List<User> users = new ArrayList<>();
    users.add(standardUser);
    // This will ensure that the getUsers() method returns
    // the mock list of users
    when(userDao.getUser(standardUser.getUsername())).thenReturn(null);
    ObjectWriter writer = this.objectMapper.writerWithView(JsonViews.Test.class);
    try {
        String userJson = writer.writeValueAsString(new UserModel(standardUser));
        this.mockMvc.perform(post("/v1/users/").content(userJson).contentType(MediaType.APPLICATION_JSON).sessionAttr("sessionUser", adminUser).accept(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isCreated());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : UserModel(com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel) User(com.serotonin.m2m2.vo.User) JsonViews(com.serotonin.m2m2.web.mvc.rest.v1.mapping.JsonViews) ArrayList(java.util.ArrayList) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter)

Example 15 with UserModel

use of com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel in project ma-modules-public by infiniteautomation.

the class UserFunctionalTests method testGetAllAdmin.

@SuppressWarnings({ "unchecked" })
public void testGetAllAdmin() {
    List<User> users = new ArrayList<>();
    User adminUser = UserTestData.adminUser();
    users.add(adminUser);
    users.add(UserTestData.newAdminUser());
    users.add(UserTestData.standardUser());
    // This will ensure that the getUsers() method returns
    // the mock list of users
    when(userDao.getUsers()).thenReturn(users);
    try {
        MvcResult result = this.mockMvc.perform(get("/v1/users").sessionAttr("sessionUser", adminUser).accept(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk()).andReturn();
        List<UserModel> models = this.objectMapper.readValue(result.getResponse().getContentAsString(), objectMapper.getTypeFactory().constructCollectionType(List.class, UserModel.class));
        // Check the size
        assertEquals(users.size(), models.size());
    } catch (Exception e) {
        fail(e.getMessage());
    }
// Check the data
}
Also used : UserModel(com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel) User(com.serotonin.m2m2.vo.User) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) MvcResult(org.springframework.test.web.servlet.MvcResult)

Aggregations

UserModel (com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel)21 User (com.serotonin.m2m2.vo.User)17 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)14 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)14 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)11 ArrayList (java.util.ArrayList)7 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)5 AccessDeniedException (com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException)4 List (java.util.List)4 ProcessMessage (com.serotonin.m2m2.i18n.ProcessMessage)3 ResponseEntity (org.springframework.http.ResponseEntity)3 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)3 AuthenticationException (org.springframework.security.core.AuthenticationException)3 MvcResult (org.springframework.test.web.servlet.MvcResult)3 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)2 JsonViews (com.serotonin.m2m2.web.mvc.rest.v1.mapping.JsonViews)2 UserAccessModel (com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserAccessModel)2 URI (java.net.URI)2 InvalidRQLRestException (com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException)1 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)1