Skip to content

Commit

Permalink
add active field and update functionality to userMfaConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
6palace authored and Bharath committed Oct 31, 2017
1 parent c1a10a9 commit b16ffe0
Show file tree
Hide file tree
Showing 10 changed files with 90 additions and 30 deletions.
Expand Up @@ -5,16 +5,23 @@
public class UserGoogleMfaCredentials { public class UserGoogleMfaCredentials {
private String userId; private String userId;
private String secretKey; private String secretKey;
private boolean active;
private List<Integer> scratchCodes; private List<Integer> scratchCodes;
private int validationCode; private int validationCode;


public UserGoogleMfaCredentials(String userId, String secretKey, int validationCode, List<Integer> scratchCodes) { public UserGoogleMfaCredentials(String userId, String secretKey, int validationCode, List<Integer> scratchCodes) {
this(userId, secretKey, validationCode, scratchCodes, false);
}

public UserGoogleMfaCredentials(String userId, String secretKey, int validationCode, List<Integer> scratchCodes, boolean active) {
this.userId = userId; this.userId = userId;
this.secretKey = secretKey; this.secretKey = secretKey;
this.scratchCodes = scratchCodes; this.scratchCodes = scratchCodes;
this.validationCode = validationCode; this.validationCode = validationCode;
this.active = active;
} }



public String getUserId() { public String getUserId() {
return userId; return userId;
} }
Expand Down Expand Up @@ -46,4 +53,12 @@ public int getValidationCode() {
public void setValidationCode(int validationCode) { public void setValidationCode(int validationCode) {
this.validationCode = validationCode; this.validationCode = validationCode;
} }

public boolean isActive() {
return active;
}

public void setActive(boolean active) {
this.active = active;
}
} }
Expand Up @@ -53,7 +53,7 @@ public String generateQrUrl(HttpSession session, Model model) throws NoSuchAlgor
} }


//TODO and credential is active //TODO and credential is active
if(userGoogleMfaCredentialsProvisioning.userCredentialExists(uaaPrincipal.getId())) { if(userGoogleMfaCredentialsProvisioning.activeUserCredentialExists(uaaPrincipal.getId())) {
return "enter_code"; return "enter_code";
} else{ } else{
//TODO set credential to inactive //TODO set credential to inactive
Expand Down
Expand Up @@ -6,6 +6,8 @@
import org.cloudfoundry.identity.uaa.mfa_provider.exception.UserMfaConfigDoesNotExistException; import org.cloudfoundry.identity.uaa.mfa_provider.exception.UserMfaConfigDoesNotExistException;
import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.RowMapper;


Expand All @@ -21,10 +23,13 @@ public class UserGoogleMfaCredentialsProvisioning implements UserMfaCredentialsP
public static final String TABLE_NAME = "user_google_mfa_credentials"; public static final String TABLE_NAME = "user_google_mfa_credentials";


private static final String CREATE_USER_MFA_CONFIG_SQL = private static final String CREATE_USER_MFA_CONFIG_SQL =
"INSERT INTO " + TABLE_NAME + "(user_id, secret_key, validation_code, scratch_codes) VALUES (?,?,?,?)"; "INSERT INTO " + TABLE_NAME + "(user_id, secret_key, validation_code, scratch_codes, active) VALUES (?,?,?,?,?)";


private static final String QUERY_USER_MFA_CONFIG_SQL = "SELECT * FROM " + TABLE_NAME + " WHERE user_id=? AND active=true"; private static final String UPDATE_USER_MFA_CONFIG_SQL =
private static final String QUERY_USER_MFA_CONFIG_INACTIVE_SQL = "SELECT * FROM " + TABLE_NAME + " WHERE user_id=? AND active=true"; "UPDATE " + TABLE_NAME + " SET secret_key=?, validation_code=?, scratch_codes=?, active=? WHERE user_id=?";

private static final String QUERY_USER_MFA_CONFIG_ACTIVE_SQL = "SELECT * FROM " + TABLE_NAME + " WHERE user_id=? AND active=true";
private static final String QUERY_USER_MFA_CONFIG_ALL_SQL = "SELECT * FROM " + TABLE_NAME + " WHERE user_id=?";


private static final String DELETE_USER_MFA_CONFIG_SQL = "DELETE FROM " + TABLE_NAME + " WHERE user_id=?"; private static final String DELETE_USER_MFA_CONFIG_SQL = "DELETE FROM " + TABLE_NAME + " WHERE user_id=?";


Expand All @@ -35,7 +40,7 @@ public UserGoogleMfaCredentialsProvisioning(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate; this.jdbcTemplate = jdbcTemplate;
} }


public boolean userCredentialExists(String userId) { public boolean activeUserCredentialExists(String userId) {
try { try {
retrieveActive(userId); retrieveActive(userId);
return true; return true;
Expand Down Expand Up @@ -65,23 +70,41 @@ public void save(UserGoogleMfaCredentials credentials) {
ps.setString(pos++, credentials.getSecretKey()); ps.setString(pos++, credentials.getSecretKey());
ps.setInt(pos++, credentials.getValidationCode()); ps.setInt(pos++, credentials.getValidationCode());
ps.setString(pos++, toCSScratchCode(credentials.getScratchCodes())); ps.setString(pos++, toCSScratchCode(credentials.getScratchCodes()));
ps.setBoolean(pos++, credentials.isActive());
}); });
} catch (DuplicateKeyException e) { } catch (DuplicateKeyException e) {
throw new UserMfaConfigAlreadyExistsException(e.getMostSpecificCause().getMessage()); throw new UserMfaConfigAlreadyExistsException(e.getMostSpecificCause().getMessage());
} }
} }


@Override
public void update(UserGoogleMfaCredentials credentials) {
int updated = jdbcTemplate.update(UPDATE_USER_MFA_CONFIG_SQL, ps -> {
int pos = 1;
ps.setString(pos++, credentials.getSecretKey());
ps.setInt(pos++, credentials.getValidationCode());
ps.setString(pos++, toCSScratchCode(credentials.getScratchCodes()));
ps.setBoolean(pos++, credentials.isActive());
ps.setString(pos++, credentials.getUserId());
});
retrieve(credentials.getUserId());
}

@Override @Override
public UserGoogleMfaCredentials retrieve(String userId) { public UserGoogleMfaCredentials retrieve(String userId) {
try{ try{
return jdbcTemplate.queryForObject(QUERY_USER_MFA_CONFIG_SQL, mapper, userId); return jdbcTemplate.queryForObject(QUERY_USER_MFA_CONFIG_ALL_SQL, mapper, userId);
} catch(EmptyResultDataAccessException e) { } catch(EmptyResultDataAccessException e) {
throw new UserMfaConfigDoesNotExistException("No Creds for user " +userId); throw new UserMfaConfigDoesNotExistException("No Creds for user " +userId);
} }
} }


public UserGoogleMfaCredentials retrieveActive(String userId) { public UserGoogleMfaCredentials retrieveActive(String userId) {
return null; try{
return jdbcTemplate.queryForObject(QUERY_USER_MFA_CONFIG_ACTIVE_SQL, mapper, userId);
} catch(EmptyResultDataAccessException e) {
throw new UserMfaConfigDoesNotExistException("No Creds for user " +userId);
}
} }


@Override @Override
Expand All @@ -100,7 +123,8 @@ public UserGoogleMfaCredentials mapRow(ResultSet rs, int rowNum) throws SQLExcep
rs.getString("user_id"), rs.getString("user_id"),
rs.getString("secret_key"), rs.getString("secret_key"),
rs.getInt("validation_code"), rs.getInt("validation_code"),
fromSCString(rs.getString("scratch_codes")) fromSCString(rs.getString("scratch_codes")),
rs.getBoolean("active")
); );
} }


Expand Down
Expand Up @@ -2,6 +2,7 @@


public interface UserMfaCredentialsProvisioning<T extends UserGoogleMfaCredentials> { public interface UserMfaCredentialsProvisioning<T extends UserGoogleMfaCredentials> {
void save(T credentials); void save(T credentials);
void update(T credentials);
T retrieve(String userId); T retrieve(String userId);
int delete(String userID); int delete(String userID);
} }
Expand Up @@ -2,5 +2,6 @@ CREATE TABLE user_google_mfa_credentials (
user_id VARCHAR(36) NOT NULL PRIMARY KEY, user_id VARCHAR(36) NOT NULL PRIMARY KEY,
secret_key VARCHAR(255) NOT NULL, secret_key VARCHAR(255) NOT NULL,
validation_code INTEGER NOT NULL, validation_code INTEGER NOT NULL,
scratch_codes VARCHAR(255) NOT NULL scratch_codes VARCHAR(255) NOT NULL,
active BOOLEAN NOT NULL,
); );
Expand Up @@ -3,5 +3,6 @@ CREATE TABLE `user_google_mfa_credentials` (
`secret_key` VARCHAR(255) NOT NULL, `secret_key` VARCHAR(255) NOT NULL,
`validation_code` INTEGER NOT NULL, `validation_code` INTEGER NOT NULL,
`scratch_codes` VARCHAR(255) NOT NULL, `scratch_codes` VARCHAR(255) NOT NULL,
`active` BOOLEAN NOT NULL,
PRIMARY KEY (`user_id`) PRIMARY KEY (`user_id`)
); );
Expand Up @@ -2,5 +2,7 @@ CREATE TABLE `user_google_mfa_credentials` (
`user_id` VARCHAR(36) NOT NULL PRIMARY KEY, `user_id` VARCHAR(36) NOT NULL PRIMARY KEY,
`secret_key` VARCHAR(255) NOT NULL, `secret_key` VARCHAR(255) NOT NULL,
`validation_code` INTEGER NOT NULL, `validation_code` INTEGER NOT NULL,
`scratch_codes` VARCHAR(255) NOT NULL `scratch_codes` VARCHAR(255) NOT NULL,
`active` BOOLEAN NOT NULL

); );
Expand Up @@ -3,5 +3,6 @@ CREATE TABLE user_google_mfa_credentials (
secret_key NVARCHAR(255) NOT NULL, secret_key NVARCHAR(255) NOT NULL,
validation_code INTEGER NOT NULL, validation_code INTEGER NOT NULL,
scratch_codes NVARCHAR(255) NOT NULL, scratch_codes NVARCHAR(255) NOT NULL,
active BIT not null,
PRIMARY KEY (user_id) PRIMARY KEY (user_id)
); );
Expand Up @@ -56,7 +56,7 @@ public void testCreateCredentials() {
@Test @Test
public void testGenerateQrUrl() throws Exception{ public void testGenerateQrUrl() throws Exception{
when(uaaAuthentication.getPrincipal()).thenReturn(new UaaPrincipal(userId, "Marissa", null, null, null, null), null, null); when(uaaAuthentication.getPrincipal()).thenReturn(new UaaPrincipal(userId, "Marissa", null, null, null, null), null, null);
when(userGoogleMfaCredentialsProvisioning.userCredentialExists(userId)).thenReturn(false); when(userGoogleMfaCredentialsProvisioning.activeUserCredentialExists(userId)).thenReturn(false);


String returnView = endpoint.generateQrUrl(session, mock(Model.class)); String returnView = endpoint.generateQrUrl(session, mock(Model.class));


Expand All @@ -66,7 +66,7 @@ public void testGenerateQrUrl() throws Exception{
@Test @Test
public void testGenerateQrUrlForNewUserRegistration() throws Exception{ public void testGenerateQrUrlForNewUserRegistration() throws Exception{
when(uaaAuthentication.getPrincipal()).thenReturn(new UaaPrincipal(userId, "Marissa", null, null, null, null), null, null); when(uaaAuthentication.getPrincipal()).thenReturn(new UaaPrincipal(userId, "Marissa", null, null, null, null), null, null);
when(userGoogleMfaCredentialsProvisioning.userCredentialExists(userId)).thenReturn(true); when(userGoogleMfaCredentialsProvisioning.activeUserCredentialExists(userId)).thenReturn(true);


String returnView = endpoint.generateQrUrl(session, mock(Model.class)); String returnView = endpoint.generateQrUrl(session, mock(Model.class));


Expand Down
Expand Up @@ -6,6 +6,7 @@
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.dao.EmptyResultDataAccessException;


import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
Expand All @@ -21,23 +22,6 @@ public class UserGoogleMfaCredentialsProvisioningTest extends JdbcTestBase {
@Before @Before
public void initJdbcScimUserProvisioningTests() throws Exception { public void initJdbcScimUserProvisioningTests() throws Exception {
db = new UserGoogleMfaCredentialsProvisioning(jdbcTemplate); db = new UserGoogleMfaCredentialsProvisioning(jdbcTemplate);
// zoneDb = new JdbcIdentityZoneProvisioning(jdbcTemplate);
// providerDb = new JdbcIdentityProviderProvisioning(jdbcTemplate);
// SimpleSearchQueryConverter filterConverter = new SimpleSearchQueryConverter();
// Map<String, String> replaceWith = new HashMap<String, String>();
// replaceWith.put("emails\\.value", "email");
// replaceWith.put("groups\\.display", "authorities");
// replaceWith.put("phoneNumbers\\.value", "phoneNumber");
// filterConverter.setAttributeNameMapper(new SimpleAttributeNameMapper(replaceWith));
// db.setQueryConverter(filterConverter);
// BCryptPasswordEncoder pe = new BCryptPasswordEncoder(4);
//
// existingUserCount = jdbcTemplate.queryForObject("select count(id) from users", Integer.class);
//
// defaultIdentityProviderId = jdbcTemplate.queryForObject("select id from identity_provider where origin_key = ? and identity_zone_id = ?", String.class, OriginKeys.UAA, "uaa");
//
// addUser(JOE_ID, "joe", pe.encode("joespassword"), "joe@joe.com", "Joe", "User", "+1-222-1234567", defaultIdentityProviderId, "uaa");
// addUser(MABEL_ID, "mabel", pe.encode("mabelspassword"), "mabel@mabel.com", "Mabel", "User", "", defaultIdentityProviderId, "uaa");
} }




Expand All @@ -52,7 +36,8 @@ public void testSaveUserGoogleMfaCredentials(){
UserGoogleMfaCredentials userGoogleMfaCredentials = new UserGoogleMfaCredentials("jabbahut", UserGoogleMfaCredentials userGoogleMfaCredentials = new UserGoogleMfaCredentials("jabbahut",
"very_sercret_key", "very_sercret_key",
74718234, 74718234,
Arrays.asList(1,22)); Arrays.asList(1,22),
true);


db.save(userGoogleMfaCredentials); db.save(userGoogleMfaCredentials);
List<Map<String, Object>> credentials = jdbcTemplate.queryForList("SELECT * FROM user_google_mfa_credentials"); List<Map<String, Object>> credentials = jdbcTemplate.queryForList("SELECT * FROM user_google_mfa_credentials");
Expand All @@ -62,6 +47,7 @@ public void testSaveUserGoogleMfaCredentials(){
assertEquals("very_sercret_key", record.get("secret_key")); assertEquals("very_sercret_key", record.get("secret_key"));
assertEquals(74718234, record.get("validation_code")); assertEquals(74718234, record.get("validation_code"));
assertEquals("1,22", record.get("scratch_codes")); assertEquals("1,22", record.get("scratch_codes"));
assertTrue((boolean) record.get("active"));
} }


@Test(expected = UserMfaConfigAlreadyExistsException.class) @Test(expected = UserMfaConfigAlreadyExistsException.class)
Expand All @@ -76,6 +62,35 @@ public void testSaveUserGoogleMfaCredentials_whenExistsForUser(){
db.save(userGoogleMfaCredentials); db.save(userGoogleMfaCredentials);
} }


@Test(expected = UserMfaConfigDoesNotExistException.class)
public void testUpdateUserGoogleMfaCredentials_noUser() {
assertEquals(0, jdbcTemplate.queryForList("SELECT * FROM user_google_mfa_credentials").size());
UserGoogleMfaCredentials userGoogleMfaCredentials = new UserGoogleMfaCredentials("jabbahut",
"very_sercret_key",
74718234,
Arrays.asList(1,22));
db.update(userGoogleMfaCredentials);
}


@Test
public void testUpdateUserGoogleMfaCredentials(){
assertEquals(0, jdbcTemplate.queryForList("SELECT * FROM user_google_mfa_credentials").size());
UserGoogleMfaCredentials userGoogleMfaCredentials = new UserGoogleMfaCredentials("jabbahut",
"very_sercret_key",
74718234,
Arrays.asList(1,22));

db.save(userGoogleMfaCredentials);
userGoogleMfaCredentials.setActive(true);
userGoogleMfaCredentials.setSecretKey("new_secret_key");
db.update(userGoogleMfaCredentials);

UserGoogleMfaCredentials updated = db.retrieve(userGoogleMfaCredentials.getUserId());
assertEquals("new_secret_key", updated.getSecretKey());
assertEquals(true, updated.isActive());
}

@Test @Test
public void testRetrieveExisting() { public void testRetrieveExisting() {
db.save(new UserGoogleMfaCredentials("user1", "secret", 12345, Collections.singletonList(123))); db.save(new UserGoogleMfaCredentials("user1", "secret", 12345, Collections.singletonList(123)));
Expand Down

0 comments on commit b16ffe0

Please sign in to comment.