There is a lot of duplicate code here.  It should exist in one place and be imported everywhere that uses it.