Skip to content

Commit

Permalink
#18101 UserMod updates when user logs in, invalidates JWT cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
jdotcms committed Mar 23, 2020
1 parent facf58a commit 68e4518
Show file tree
Hide file tree
Showing 30 changed files with 1,201 additions and 218 deletions.
Expand Up @@ -12,19 +12,23 @@
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.exception.DotSecurityException;
import com.dotmarketing.util.DateUtil;
import com.dotmarketing.util.UUIDGenerator;
import com.liferay.portal.model.User;
import org.junit.BeforeClass;
import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public class JsonWebTokenUtilsIntegrationTest {

private static final String jwtId = "jwt1";
private static String userId;
private static String clusterId;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Expand All @@ -45,7 +49,7 @@ public static void prepare() throws Exception {
userAPI = APILocator.getUserAPI();

//Create User
final User newUser = new UserDataGen().nextPersisted();
final User newUser = new UserDataGen().skinId(UUIDGenerator.generateUuid()).nextPersisted();
APILocator.getRoleAPI().addRoleToUser(APILocator.getRoleAPI().loadCMSAdminRole(), newUser);
assertTrue(userAPI.isCMSAdmin(newUser));
userId = newUser.getUserId();
Expand All @@ -66,9 +70,13 @@ public void get_user_in_token()
assertNotNull(jsonWebTokenService);

//Generate a new token
String jsonWebToken = jsonWebTokenService.generateUserToken(new UserToken(jwtId,
userId, date, DateUtil.daysToMillis(2)
));
final String jwtId = user.getRememberMeToken();
final UserToken userToken = new UserToken.Builder()
.id(jwtId).subject(userId)
.modificationDate(date)
.expiresDate(DateUtil.daysToMillis(2))
.build();
String jsonWebToken = jsonWebTokenService.generateUserToken(userToken);
System.out.println(jsonWebToken);
assertNotNull(jsonWebToken);

Expand Down Expand Up @@ -102,10 +110,13 @@ public void get_user_in_token_modified()
JsonWebTokenFactory.getInstance().getJsonWebTokenService();
assertNotNull(jsonWebTokenService);

final String jwtId = APILocator.getUserAPI().loadUserById(userId).getRememberMeToken();
//Generate a new token
String jsonWebToken = jsonWebTokenService.generateUserToken(new UserToken(jwtId,
userId, date, DateUtil.daysToMillis(2)
));
final UserToken userToken = new UserToken.Builder().id(jwtId).subject(userId).modificationDate(date)
.expiresDate(DateUtil.daysToMillis(2))
.build();
String jsonWebToken = jsonWebTokenService.generateUserToken(userToken);

System.out.println(jsonWebToken);
assertNotNull(jsonWebToken);

Expand All @@ -120,7 +131,7 @@ public void get_user_in_token_modified()

Thread.sleep(1000);

userAPI.loadUserById(userId).setModificationDate(new Date());
userAPI.loadUserById(userId).setSkinId("xxxx");

//Get the user
JsonWebTokenUtils jsonWebTokenUtils = new JsonWebTokenUtils(jsonWebTokenService);
Expand Down
Expand Up @@ -2,6 +2,7 @@

import com.dotcms.auth.providers.jwt.beans.ApiToken;
import com.dotcms.auth.providers.jwt.beans.JWToken;
import com.dotcms.datagen.CompanyDataGen;
import com.dotcms.datagen.UserDataGen;
import com.dotcms.enterprise.cluster.ClusterFactory;
import com.dotcms.repackage.org.apache.commons.net.util.SubnetUtils;
Expand All @@ -10,6 +11,9 @@
import com.dotmarketing.business.CacheLocator;
import com.dotmarketing.business.DotStateException;
import com.dotmarketing.util.DateUtil;
import com.dotmarketing.util.UUIDGenerator;
import com.liferay.portal.ejb.CompanyUtil;
import com.liferay.portal.model.Company;
import com.liferay.portal.model.User;
import org.junit.BeforeClass;
import org.junit.Test;
Expand Down Expand Up @@ -357,7 +361,26 @@ public void test_expired_ApiToken() throws Exception {
@Test
public void test_user_must_be_active_to_validate_ApiToken() throws Exception {

User user = new UserDataGen().nextPersisted();
final Company company = new CompanyDataGen()
.name("TestCompany")
.shortName("TC")
.authType("email")
.autoLogin(true)
.emailAddress("lol2@dotCMS.com")
.homeURL("localhost")
.city("NYC")
.mx("MX")
.type("test")
.phone("5552368")
.portalURL("/portalURL")
.nextPersisted();
assertNotNull(company.getCompanyId());
final Company retrievedCompany = CompanyUtil.findByPrimaryKey(company.getCompanyId());
assertEquals(company.getCompanyId(), retrievedCompany.getCompanyId());
User user = new UserDataGen().active(true)
.skinId(UUIDGenerator.generateUuid())
.companyId(retrievedCompany.getCompanyId())
.nextPersisted();
assertTrue(user.isActive());

ApiToken skinnyToken = ApiToken.from(getSkinnyToken()).withUserId(user.getUserId()).build();
Expand Down
Expand Up @@ -56,18 +56,26 @@ public static void prepare() throws Exception {
* Testing the generateToken JsonWebTokenServiceTest
*/
@Test
public void generateTokenTest() {
public void generateTokenTest() throws DotSecurityException, DotDataException {

final User user = APILocator.getUserAPI().loadUserById(userId);
//Generate a new token
String jsonWebToken = jsonWebTokenService.generateUserToken(new UserToken(jwtId,
userId, new Date(), DateUtil.daysToMillis(2)));
final String jwtokenId = user.getRememberMeToken();
final UserToken userToken = new UserToken.Builder()
.id(jwtokenId)
.subject(userId)
.issuer(clusterId)
.expiresDate(DateUtil.daysToMillis(2))
.claims(ImmutableMap.of())
.build();
String jsonWebToken = jsonWebTokenService.generateUserToken(userToken);
System.out.println(jsonWebToken);
assertNotNull(jsonWebToken);

//Parse the generated token
final JWToken jwtBean = jsonWebTokenService.parseToken(jsonWebToken);
assertNotNull(jwtBean);
assertEquals(jwtBean.getId(), jwtId);
assertEquals(jwtBean.getId(), jwtokenId);
assertEquals(jwtBean.getIssuer(), clusterId);
final String subject = jwtBean.getSubject();
assertNotNull(subject);
Expand All @@ -80,9 +88,15 @@ public void generateTokenTest() {
@Test(expected = ExpiredJwtException.class)
public void generateToken_expired_token_Test() throws ParseException, DotSecurityException, DotDataException {

final User user = APILocator.getUserAPI().loadUserById(userId);
//Generate a new token
final UserToken userToken = new UserToken(jwtId, userId,clusterId, new Date(),
DateUtil.addDate(new Date(), Calendar.MONTH,-2), ImmutableMap.of());
final UserToken userToken = new UserToken.Builder().id(user.getRememberMeToken())
.subject(userId)
.issuer(clusterId)
.modificationDate(new Date())
.expiresDate(DateUtil.addDate(new Date(), Calendar.MONTH,-2))
.claims(ImmutableMap.of())
.build();

final String jsonWebToken = jsonWebTokenService.generateUserToken(userToken);

Expand All @@ -98,12 +112,13 @@ public void generateToken_expired_token_Test() throws ParseException, DotSecurit
* different server.
*/
@Test(expected = IncorrectClaimException.class)
public void generateToken_incorrect_issuer() {
public void generateToken_incorrect_issuer() throws DotSecurityException, DotDataException {

final User user = APILocator.getUserAPI().loadUserById(userId);
//Generate a new token
final String jsonWebToken = jsonWebTokenService.generateUserToken(new UserToken(jwtId,
userId, new Date(), DateUtil.daysToMillis(2)
));

final String jsonWebToken = jsonWebTokenService.generateUserToken(
new UserToken.Builder().id(user.getRememberMeToken()).subject(userId).expiresDate(DateUtil.daysToMillis(2)).build());
System.out.println(jsonWebToken);
assertNotNull(jsonWebToken);

Expand Down
Expand Up @@ -24,13 +24,15 @@
import com.dotcms.contenttype.model.type.BaseContentType;
import com.dotcms.contenttype.model.type.ContentType;
import com.dotcms.datagen.CategoryDataGen;
import com.dotcms.datagen.CompanyDataGen;
import com.dotcms.datagen.ContentTypeDataGen;
import com.dotcms.datagen.ContentletDataGen;
import com.dotcms.datagen.FieldDataGen;
import com.dotcms.datagen.RoleDataGen;
import com.dotcms.datagen.SiteDataGen;
import com.dotcms.datagen.TestUserUtils;
import com.dotcms.datagen.TestWorkflowUtils;
import com.dotcms.datagen.UserDataGen;
import com.dotcms.datagen.WorkflowDataGen;
import com.dotcms.mock.request.MockAttributeRequest;
import com.dotcms.mock.request.MockHeaderRequest;
Expand Down Expand Up @@ -62,10 +64,13 @@
import com.dotmarketing.portlets.structure.model.Relationship;
import com.dotmarketing.portlets.workflows.business.WorkflowAPI;
import com.dotmarketing.portlets.workflows.model.WorkflowScheme;
import com.dotmarketing.util.UUIDGenerator;
import com.dotmarketing.util.UtilMethods;
import com.dotmarketing.util.WebKeys.Relationship.RELATIONSHIP_CARDINALITY;
import com.google.common.collect.Sets;
import com.liferay.portal.model.Company;
import com.liferay.portal.model.User;
import com.liferay.portal.util.WebKeys;
import com.liferay.util.StringPool;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
Expand Down Expand Up @@ -133,6 +138,7 @@ public class ContentResourceTest extends IntegrationTestBase {
private static RelationshipAPI relationshipAPI;
private static RoleAPI roleAPI;
private static User user;
private static User adminUser;
private static UserAPI userAPI;
private static Role adminRole;
private static Host host;
Expand Down Expand Up @@ -167,7 +173,7 @@ public static void prepare() throws Exception {

// Test host
host = new SiteDataGen().nextPersisted();

adminUser = TestUserUtils.getAdminUser();
}

@AfterClass
Expand Down Expand Up @@ -537,11 +543,24 @@ public void test_getContent_shouldReturnRelationships(final TestCase testCase)
if (testCase.limitedUser){
newRole = createRole();

createdLimitedUser = TestUserUtils
.getUser(newRole, "email" + System.currentTimeMillis() + "@dotcms.com",
"name" + System.currentTimeMillis(),
"lastName" + System.currentTimeMillis(),
"password" + System.currentTimeMillis());
final Company company = new CompanyDataGen()
.name("TestCompany")
.shortName("TC")
.authType("email")
.autoLogin(true)
.emailAddress("lol@dotCMS.com")
.homeURL("localhost")
.city("NYC")
.mx("MX")
.type("test")
.phone("5552368")
.portalURL("/portalURL")
.nextPersisted();

createdLimitedUser =
new UserDataGen().firstName("name").lastName("lastName").companyId(company.getCompanyId())
.emailAddress("email" + System.currentTimeMillis() + "@dotcms.com").skinId(UUIDGenerator.generateUuid())
.password("password" + System.currentTimeMillis()).roles(newRole, TestUserUtils.getFrontendRole(), TestUserUtils.getBackendRole()).nextPersisted();

//set individual permissions to the child
permissionAPI.save(new Permission(PermissionAPI.INDIVIDUAL_PERMISSION_TYPE,
Expand Down Expand Up @@ -572,7 +591,7 @@ public void test_getContent_shouldReturnRelationships(final TestCase testCase)
//calls endpoint
final ContentResource contentResource = new ContentResource();
final HttpServletRequest request = createHttpRequest(null,
testCase.limitedUser ? createdLimitedUser : null);
testCase.limitedUser ? createdLimitedUser : adminUser);
final HttpServletResponse response = mock(HttpServletResponse.class);
final Response endpointResponse = contentResource.getContent(request, response,
"/id/" + parent.getIdentifier() + "/live/false/type/" + testCase.responseType
Expand Down Expand Up @@ -1333,6 +1352,7 @@ private HttpServletRequest createHttpRequest(final String jsonPayload, final Use
}

when(request.getContentType()).thenReturn(MediaType.APPLICATION_JSON);
request.setAttribute(WebKeys.USER,user);

return request;

Expand Down
@@ -1,9 +1,5 @@
package com.dotcms.datagen;

import static com.dotmarketing.business.Role.ADMINISTRATOR;
import static com.dotmarketing.business.Role.DOTCMS_BACK_END_USER;
import static com.dotmarketing.business.Role.DOTCMS_FRONT_END_USER;

import com.dotcms.business.WrapInTransaction;
import com.dotmarketing.beans.Host;
import com.dotmarketing.beans.Permission;
Expand All @@ -17,12 +13,18 @@
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.exception.DotRuntimeException;
import com.dotmarketing.exception.DotSecurityException;
import com.dotmarketing.util.UUIDGenerator;
import com.dotmarketing.util.UtilMethods;
import com.google.common.collect.ImmutableMap;
import com.liferay.portal.model.User;

import java.util.List;
import java.util.Map;

import static com.dotmarketing.business.Role.ADMINISTRATOR;
import static com.dotmarketing.business.Role.DOTCMS_BACK_END_USER;
import static com.dotmarketing.business.Role.DOTCMS_FRONT_END_USER;

/**
* @author Jonathan Gamba 2019-06-11
*/
Expand Down Expand Up @@ -174,7 +176,7 @@ public static User getUser(final Role role, final String email,
if (UtilMethods.isSet(users)) {
return users.get(0);
}
return new UserDataGen().firstName(name).lastName(lastName).emailAddress(email)
return new UserDataGen().firstName(name).lastName(lastName).emailAddress(email).skinId(UUIDGenerator.generateUuid())
.password(password).roles(role, getFrontendRole(), getBackendRole()).nextPersisted();
}

Expand Down Expand Up @@ -354,4 +356,4 @@ public static String getRandomUserId(final DotConnect dotConnect) throws DotData
throw new IllegalStateException("dunno What Db 'Im running on");
}

}
}
Expand Up @@ -6,6 +6,7 @@
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.exception.DotSecurityException;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.UUIDGenerator;
import com.dotmarketing.util.UUIDUtil;
import com.liferay.portal.model.User;
import java.util.ArrayList;
Expand All @@ -22,6 +23,8 @@ public class UserDataGen extends AbstractDataGen<User> {
private String lastName = "testLastName" + currentTime;
private String emailAddress = "testEmailAddress@" + currentTime + ".com";
private String password = String.valueOf(currentTime);
private String skinIdentifier = UUIDGenerator.generateUuid();
private String companyId = UUIDGenerator.generateUuid();
private List<Role> roles = new ArrayList<>();

@SuppressWarnings("unused")
Expand All @@ -30,6 +33,17 @@ public UserDataGen id(final String id) {
return this;
}

public UserDataGen companyId(final String companyId) {
this.companyId = companyId;
return this;
}

@SuppressWarnings("unused")
public UserDataGen skinId(final String skinIdentifier) {
this.skinIdentifier = skinIdentifier;
return this;
}

@SuppressWarnings("unused")
public UserDataGen active(final Boolean active) {
this.active = active;
Expand Down Expand Up @@ -75,6 +89,8 @@ public User next() {
user.setLastName(lastName);
user.setEmailAddress(emailAddress);
user.setPassword(password);
user.setSkinId(this.skinIdentifier);
user.setCompanyId(companyId);

return user;
}
Expand All @@ -90,6 +106,8 @@ public User persist(User user) {
newUser.setLastName(user.getLastName());
newUser.setPassword(user.getPassword());
newUser.setActive(user.getActive());
newUser.setSkinId(user.getSkinId());
newUser.setCompanyId(user.getCompanyId());
APILocator.getUserAPI().save(newUser, APILocator.systemUser(), false);

for(final Role role:roles){
Expand Down Expand Up @@ -133,4 +151,4 @@ public static void remove(final User user, final Boolean failSilently) {
}
}

}
}

0 comments on commit 68e4518

Please sign in to comment.