@POST @Consumes("application/json") @Path("/add") public Response addUser(User user) { String name = user.getName(); log.info("Adding new user " + name + " .."); LDAPUserStoreManager ldapUserStoreManager; try { ldapUserStoreManager = LDAPUserStoreManager.getInstance(host, port, connectionName, connectionPassword); // Create groups if (user.getRoles() != null && user.getRoles().size() > 0) { for (String role : user.getRoles()) { ldapUserStoreManager.addGroup(role, role); } } ldapUserStoreManager.addUserAndAssignGroups( user.getName(), user.getFirstName(), user.getLastName(), user.getPassword(), user.getEmail(), user.getRoles()); log.info("User " + name + " successfully added .."); } catch (NamingException e) { log.error("Exception occurred while adding user " + name, e); return Response.status(Response.Status.EXPECTATION_FAILED).build(); } return Response.status(Response.Status.OK) .entity("User " + name + " successfully added") .build(); }
@POST @Consumes("application/json") @Path("/login") public Response authenticate(User user) { String name = user.getName(); log.info("Authenticating user " + name + " .."); String jwt; boolean isAuthenticated; try { LDAPUserStoreManager ldapUserStoreManager = LDAPUserStoreManager.getInstance(host, port, connectionName, connectionPassword); isAuthenticated = ldapUserStoreManager.isValidUser(name, user.getPassword()); if (isAuthenticated) { User userFromUserStore = new User(); userFromUserStore.setName(name); userFromUserStore.setEmail(ldapUserStoreManager.getAttributeValue(name, "mail")); userFromUserStore.setLastName(ldapUserStoreManager.getAttributeValue(name, "sn")); JWTGenerator jwtGenerator = new JWTGenerator(); jwt = jwtGenerator.generateJWT(userFromUserStore); String msg = "User " + name + " authenticated successfully"; log.info(msg); return Response.ok(msg).header(JWT_HEADER, jwt).build(); } } catch (Exception e) { log.error("Exception occurred while trying to authenticate user " + name, e); return Response.status(Response.Status.EXPECTATION_FAILED).build(); } log.warn("Failed login attempt by user " + name); return Response.status(Response.Status.UNAUTHORIZED).entity("Invalid login attempt.").build(); }