Looking at this, I wonder why the key error? Must be when looking up username in the session. However, that should always be there and the conditional also needs to consider aws login as well. I'll simplify.