changed name from sync_user_key
[tests.git] / qaapi / qa / tests / sync_user_key.py
1 #!/usr/bin/env /usr/share/plc_api/plcsh
2 import os, sys
3 from Test import Test
4 from qa import utils
5
6 class sync_person_key(Test):
7     """
8     Make sure specified users public key on file matches whats 
9     recorded at plc. Create a public/private keypair for the 
10     specified user if one doesnt exist already.  
11     """
12
13     def make_keys(self, path, name):
14         if not os.path.isdir(path):
15             os.mkdir(path)
16         key_path = path + os.sep + name
17         command = "ssh-keygen -f %(key_path)s -t rsa -N ''"  % locals()
18         (stdout, stderr) = utils.popen(command)
19
20     def call(self, email):
21         email_parts = email.split("@")
22         keys_filename = email_parts[0]
23         keys_path = self.config.KEYS_PATH 
24         private_key_path = keys_path + os.sep + keys_filename
25         public_key_path = private_key_path + ".pub"
26         
27         # Validate person
28         persons = GetPersons([email], ['person_id', 'key_ids'])
29         if not persons:
30             raise Exception, "No such person %(email)s"
31         person = persons[0]
32
33         # make keys if they dont already exist  
34         if not os.path.isfile(private_key_path) or \
35            not os.path.isfile(public_key_path):
36             # Make new keys
37             self.make_keys(keys_path, keys_filename)
38             if self.config.verbose:
39                 utils.header("Made new key pair %(private_key_path)s %(public_key_path)s " %\
40                 locals())
41             
42         # sync public key  
43         public_key_file = open(public_key_path, 'r')
44         public_key = public_key_file.readline()
45                 
46         keys = GetKeys(person['key_ids'])
47         if not keys:
48             # Add current key to db
49             key_fields = {'key_type': 'ssh',
50                           'key': public_key}
51             AddPersonKey(person['person_id'], key_fields)
52             if self.config.verbose:
53                 utils.header("Added public key in %(public_key_path)s to db" % locals() )
54         else:
55             # keys need to be checked and possibly updated
56             key = keys[0]
57             if key['key'] != public_key:
58                 UpdateKey(key['key_id'], public_key)
59                 if self.config.verbose:
60                     utils.header("Updated plc with new public key in %(public_key_path)s " % locals())
61             else:
62                 if self.config.verbose:
63                     utils.header("Key in %(public_key_path)s matchs public key in plc" % locals())                      
64
65 if __name__ == '__main__':
66     args = tuple(sys.argv[1:])
67     sync_person_key()(*args)