Moves common code to abstract class, improves security and tests