from urllib2 import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, build_opener, urlopen, install_opener, HTTPCookieProcessor

top_level_url = "http://dekiwiki/@api/deki/users/authenticate"
username = "ozten"
password = "pass"

# create a password manager
password_mgr = HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
password_mgr.add_password(None, top_level_url, username, password)


handler = HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = build_opener(handler)

# Install the opener.
# Now all calls to urllib2.urlopen use our opener.
#install_opener(opener)

resp = opener.open(top_level_url)
authtoken = resp.read()
print("We got an authoken %s" % authtoken)


#import cookielib, Cookie
#cj = cookielib.CookieJar()
#cj.set_cookie(Cookie.SimpleCookie({'authtoken': authtoken}))
#processor = HTTPCookieProcessor(cj)
#opener = build_opener(processor)

opener = build_opener()
opener.addheaders = [('Cookie', ("authtoken=\"%s\"" % authtoken))]
resp = opener.open("http://dekiwiki/@api/deki/users/current")
print(str(resp))
profile = resp.read()
print("We got an profile %s" % profile)

from xml.dom import minidom
xmldoc = minidom.parse(profile)
userEl = None
username = None
deki_user_id = 0
deki_fullname = ""

for c in xmldoc.childNodes:
    if c.nodeName == 'user':
        userEl = c
        break
for c in userEl.childNodes:
    if c.nodeName == 'username':
        username = c.firstChild.nodeValue
        break
<user 
      id="115908"><nick>Anonymous</nick>
      <username>Anonymous</username>
      <fullname/><email/><hash.email>d41d8cd98f00b204e9800998ecf8427e</hash.email>
      <uri.gravatar>http://www.gravatar.com/avatar/d41d8cd98f00b204e9800998ecf8427e.png</uri.gravatar>
      <date.created>2005-03-15T23:42:24Z</date.created>
      <status>active</status>
      <date.lastlogin>2010-12-05T21:27:31Z</date.lastlogin>
      <language/>
      <timezone/>
      <service.authentication href="http://dekiwiki/@api/deki/site/services/1" id="1"/>
      <permissions.user><operations mask="15">LOGIN,BROWSE,READ,SUBSCRIBE</operations><role href="http://dekiwiki/@api/deki/site/roles/3" id="3">Viewer</role></permissions.user><permissions.effective><operations mask="15">LOGIN,BROWSE,READ,SUBSCRIBE</operations></permissions.effective><groups/><properties count="0" href="http://dekiwiki/@api/deki/users/115908/properties"/></user>
