Added support for basic auth

Also included some code cleanup along the way.