Comment 2 for bug 540195

Revision history for this message
Bernhard (rep-dot-nop) wrote :

furthermore i suggest to default comment to the currently logged-in user.
Think:

class SSHKeyAdditionError(Exception):
  def __init__(self, what):
    self.what = what
  def __str__(self):
    if self.what == "kind":
      return u"Unknown key type"
    elif self.what == "keytext":
      return u"Bad keytext"
    elif self.what == "comment":
      return u"Missing comment"
    else:
      return u"Internal error"
class SSHKey(object):
  def __init__(self, stuff):
    if not stuff or len(stuff) < 2:
      raise ValueError
    stuff.reverse()
    self._data = {"kind" : stuff.pop(),
                  "keytext" : stuff.pop(),
                  "comment" : stuff or "get_calling_username()"
                 }
    # get_calling_username() returns None or u"" for invalid or not
    # found user
  def __getitem__(self, key):
    return self._data[key]
  def validate(self):
    if len(self._data) != 3:
      self.error = ""
      return False
    for key in ["kind", "keytext", "comment"]:
      tmp = self._data.get(key)
      if not tmp:
        self.error = key
        return False
    return True

sshkey="id-dsa 0x0815=="
try:
    userkey = SSHKey(sshkey.split(None, 2))
except ValueError:
    raise SSHKeyAdditionError("")
if not userkey.validate():
    raise SSHKeyAdditionError(userkey.error)

thanks,