Projet

Général

Profil

Paste
Télécharger (2,33 ko) Statistiques
| Branche: | Révision:

root / scripts_divers / fix-cas.py @ ef98b98a

1
#!/usr/bin/env python3
2

    
3
# This script is intended to fix the cas_user table. Just give the database name.
4

    
5
import argparse
6
from getpass import getpass
7

    
8
def fix_cas(db, host, user, password, prefix, roles):
9
    import pymysql as mysql
10

    
11
    while not password:
12
        password = getpass('Please enter the password: ')
13
    password = password.strip()
14

    
15
    conn = mysql.connect(host=host, user=user, passwd=password, db=db, charset='utf8')
16
    with conn:
17
        cur = conn.cursor()
18

    
19
        # We format the name of the tables according to prefix
20
        tables = {'users': '{}users', 'users_roles': '{}users_roles',\
21
                  'role': '{}role', 'cas_user': '{}cas_user'}
22
        for key, elt in tables.items():
23
            tables[key] = elt.format(prefix)
24

    
25
        # We take into account the roles to modify
26
        for role in roles:
27
            i = roles.index(role)
28
            roles[i] = "'" + role + "'"
29
        format_dict = {'roles_to_modify': ', '.join(roles)}
30

    
31
        # We are ready to format queries
32
        format_dict.update(tables)
33

    
34
        select = """SELECT {users}.name, {users}.uid FROM {users}
35
        JOIN {users_roles} ON {users_roles}.uid = {users}.uid
36
        JOIN {role} ON {role}.rid = {users_roles}.rid
37
        WHERE {role}.name IN ({roles_to_modify}) AND {users}.uid NOT IN
38
        (SELECT uid FROM {cas_user})
39
        """.format(**format_dict)
40

    
41
        insert = """INSERT INTO {cas_user} (uid, cas_name)
42
        VALUES (%s, %s)
43
        """.format(**format_dict)
44

    
45
        cur.execute(select)
46
        rows = cur.fetchall()
47

    
48
        for name, uid in rows:
49
            cur.execute(insert, (uid, name))
50

    
51
        conn.commit()
52

    
53

    
54

    
55
###### Main
56

    
57
parser = argparse.ArgumentParser(description='Fill the cas_user table from the users table for a specific role or all roles. Requires pymysql to query the database.')
58
parser.add_argument('database', metavar='database', help='name of the database to fix')
59
parser.add_argument('--host', dest='host', default='localhost')
60
parser.add_argument('--user', '-u', dest='user', default='root')
61
parser.add_argument('--password', '--passwd', '-p', dest='password')
62
parser.add_argument('--prefix', dest='prefix', default='')
63
parser.add_argument('--roles', '-r', dest='roles', nargs='+', default=['authenticated user'])
64

    
65
args = parser.parse_args()
66
fix_cas(args.database, args.host, args.user, args.password, args.prefix, args.roles)