#!/usr/bin/env python import os, sys import MySQLdb import tempfile from optparse import OptionParser from deter import fedid class opt_parser(OptionParser): def __init__(self): OptionParser.__init__(self, usage="%prog [opts] (--help for details)", version="0.1") self.add_option('-u', '--user', dest='users', action='append', default=[], help="Users to extract from DB") self.add_option('-p', '--project', dest='projects', action='append', default=[], help="Projects to extract from DB") self.add_option('-U', '--no-user-access', dest='user_access', default=True, action='store_false', help='do not output a user-only access entry') self.add_option('-P', '--no-project-access', dest='project_access', default=True, action='store_false', help='do not output project-based access entries') def cert_to_fid(cstr): fd, path = tempfile.mkstemp('.pem') try: try: f = os.fdopen(fd, "w") print >>f, cstr f.close() except IOError, e: print >>sys.stderr, "Error creating user %s" % u return fedid(file=path) finally: os.remove(path) def add_list(l, field): str = "" for x in l: if str: str += " OR " else: str = " AND (" str += "%s='%s'" % (field, x) if str: str += ")" return str fids = { } q_start = """ SELECT g.uid, CASE g.gid WHEN g.pid THEN g.pid ELSE CONCAT(g.pid, '/', g.gid) END, CONCAT('-----BEGIN CERTIFICATE-----\\n', s.cert, '-----END CERTIFICATE-----\\n'), encrypted FROM group_membership g INNER JOIN user_sslcerts s ON g.uid = s.uid WHERE revoked is NULL """ q_end =""" ORDER BY s.uid """ opts, args = opt_parser().parse_args() if not ( opts.project_access or opts.user_access): sys.exit("No output if both --no-project-access and " +\ "--no-user-access are given") user_clause= add_list(opts.users, 'g.uid') project_clause= add_list(opts.projects, 'g.pid') query = q_start + user_clause + project_clause + q_end db = MySQLdb.connect(db='tbdb') c = db.cursor() c.execute(query) for u, p, c, e in c.fetchall(): fid = fids.get(c, None) if not fid: fid = cert_to_fid(c) fids[c] = fid if e: print "# %s (encrypted)" % u else: print "# %s" % u if opts.user_access: print "fedid:%s->%s" % (fid, u) if opts.project_access: print "fedid:%s->(%s,%s)" % (fid, p, u)