Completed
Push — master ( b7eb8c...589bde )
by Egor
01:15
created

grant_permissions()   B

Complexity

Conditions 4

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 28
rs 8.5806
cc 4
1
# -*- coding: utf-8 -*-
2
from __future__ import unicode_literals
3
4
from django.db import migrations, connection
5
from django.conf import settings
6
7
8
def get_group(user, cursor):
9
    tmpl = """SELECT
10
        rolname
11
    FROM
12
        pg_user
13
    JOIN pg_auth_members ON(
14
        pg_user.usesysid = pg_auth_members. MEMBER
15
    )
16
    JOIN pg_roles ON(
17
        pg_roles.oid = pg_auth_members.roleid
18
    )
19
    WHERE
20
        pg_user.usename = %s;
21
    """
22
    cursor.execute(tmpl, [user])
23
    row = cursor.fetchone()
24
    return row[0] if row else ''
25
26
27
def grant_permissions(apps, schema_editor):
28
    cursor = connection.cursor()
29
30
    cursor.execute("select * from pg_catalog.pg_user where usename=%s;", [settings.DB_PUBLIC_USER])
31
    if not cursor.fetchall():
32
        cursor.execute("CREATE USER %s WITH PASSWORD '%s';" % (settings.DB_PUBLIC_USER, settings.DB_PUBLIC_PASSWORD))
33
34
    cursor.execute("select * from pg_catalog.pg_group where groname=%s;", [settings.DB_PUBLIC_ROLE])
35
    if not cursor.fetchall():
36
        cursor.execute("CREATE GROUP %s;" % settings.DB_PUBLIC_ROLE)
37
38
    if not get_group(settings.DB_PUBLIC_USER, cursor) == settings.DB_PUBLIC_ROLE:
39
        cursor.execute("ALTER GROUP %s ADD USER %s;" % (settings.DB_PUBLIC_ROLE, settings.DB_PUBLIC_USER))
40
41
    cursor.execute('GRANT SELECT ON TABLE applications, platforms, platforms_id_seq, '
42
                   'channels, channels_id_seq, versions, versions_id_seq, actions, '
43
                   'actions_id_seq, omaha_data, omaha_data_id_seq, omaha_partialupdate, '
44
                   'omaha_partialupdate_id_seq TO GROUP %s;' % settings.DB_PUBLIC_ROLE)
45
46
    cursor.execute('GRANT SELECT, INSERT, UPDATE ON TABLE omaha_apprequest, '
47
                   'omaha_apprequest_id_seq, omaha_apprequest_events, '
48
                   'omaha_apprequest_events_id_seq, omaha_event, omaha_event_id_seq, omaha_hw, '
49
                   'omaha_hw_id_seq, omaha_os, omaha_os_id_seq, omaha_request, '
50
                   'omaha_request_id_seq TO GROUP %s;' % settings.DB_PUBLIC_ROLE)
51
52
    # grant permissions to a user for all sequences in a schema
53
    cursor.execute('GRANT SELECT, USAGE ON ALL SEQUENCES IN SCHEMA public to %s;' % settings.DB_PUBLIC_ROLE)
54
    cursor.execute('GRANT UPDATE, USAGE ON ALL SEQUENCES IN SCHEMA public to %s;' % settings.DB_PUBLIC_ROLE)
55
56
class Migration(migrations.Migration):
57
    dependencies = [
58
        ('omaha', '0020_auto_20150710_0913'),
59
    ]
60
61
    operations = [
62
        migrations.RunPython(grant_permissions, reverse_code=migrations.RunPython.noop),
63
    ]
64