summaryrefslogtreecommitdiffstats
path: root/ipa-server/ipa-gui/ipagui/subcontrollers/principal.py
blob: d7b25d8c38c0cc0ca3fb2586a5651d5fc60350c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# Copyright (C) 2007  Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; version 2 only
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
 
import os
from pickle import dumps, loads
from base64 import b64encode, b64decode
import copy
import logging

import cherrypy
import turbogears
from turbogears import controllers, expose, flash
from turbogears import validators, validate
from turbogears import widgets, paginate
from turbogears import error_handler
from turbogears import identity

from ipacontroller import IPAController
from ipa.entity import utf8_encode_values
from ipa import ipaerror
import ipagui.forms.principal

import ldap.dn

log = logging.getLogger(__name__)

principal_new_form = ipagui.forms.principal.PrincipalNewForm()
principal_fields = ['*']

class PrincipalController(IPAController):

    @expose()
    @identity.require(identity.in_group("admins"))
    def index(self, tg_errors=None):
        raise turbogears.redirect("/principal/list")

    @expose("ipagui.templates.principalnew")
    @identity.require(identity.in_group("admins"))
    def new(self, tg_errors=None):
        """Displays the new service principal form"""
        if tg_errors:
            turbogears.flash("There were validation errors.<br/>" +
                             "Please see the messages below for details.")

        client = self.get_ipaclient()

        return dict(form=principal_new_form, principal={})

    @expose()
    @identity.require(identity.in_group("admins"))
    def create(self, **kw):
        """Creates a service principal group"""
        self.restrict_post()
        client = self.get_ipaclient()

        if kw.get('submit') == 'Cancel':
            turbogears.flash("Add principal cancelled")
            raise turbogears.redirect('/')

        tg_errors, kw = self.principalcreatevalidate(**kw)
        if tg_errors:
            turbogears.flash("There were validation errors.<br/>" +
                             "Please see the messages below for details.")
            return dict(form=principal_new_form, principal=kw,
                    tg_template='ipagui.templates.principalnew')

        principal_name = ""
        hostname = kw.get('hostname')
        #
        # Create the principal itself
        #
        try:
            if kw.get('service') == "other":
                service = kw.get('other')
                if not service:
                    turbogears.flash("Service type must be provided")
                    return dict(form=principal_new_form, principal=kw,
                            tg_template='ipagui.templates.principalnew')
            else:
                service = kw.get('service')

            # The realm is added by add_service_principal
            principal_name = utf8_encode_values(service + "/" + kw.get('hostname'))

            rv = client.add_service_principal(principal_name)
        except ipaerror.exception_for(ipaerror.LDAP_DUPLICATE):
            turbogears.flash("Service principal '%s' already exists" %
                    principal_name)
            return dict(form=principal_new_form, principal=kw,
                    tg_template='ipagui.templates.principalnew')
        except ipaerror.IPAError, e:
            turbogears.flash("Service principal add failed: " + str(e) + "<br/>" + e.detail[0]['desc'])
            return dict(form=principal_new_form, principal=kw,
                    tg_template='ipagui.templates.principalnew')

        turbogears.flash("%s added!" % principal_name)
        raise turbogears.redirect('/principal/list', hostname=hostname)

    @expose("ipagui.templates.principallist")
    @identity.require(identity.not_anonymous())
    def list(self, **kw):
        """Searches for service principals and displays list of results"""
        client = self.get_ipaclient()

        principals = None
        counter = 0
        hostname = kw.get('hostname')
        if hostname != None and len(hostname) > 0:
            try:
                principals = client.find_service_principal(hostname.encode('utf-8'), principal_fields, 0, 2)
                counter = principals[0]
                principals = principals[1:]

                if counter == -1:
                    turbogears.flash("These results are truncated.<br />" +
                                    "Please refine your search and try again.")

                # For each entry break out service type and hostname
                for i in range(len(principals)):
                    (service,host) = principals[i].krbprincipalname.split('/')
                    h = host.split('@')
                    principals[i].setValue('service', service)
                    principals[i].setValue('hostname', h[0])

            except ipaerror.IPAError, e:
                turbogears.flash("principal list failed: " + str(e) + "<br/>" + e.detail[0]['desc'])
                raise turbogears.redirect("/principal/list")

        return dict(principals=principals, hostname=hostname, fields=ipagui.forms.principal.PrincipalFields())

    @expose("ipagui.templates.principalshow")
    @identity.require(identity.not_anonymous())
    def show(self, **kw):
        """Display a single service principal"""

        try:
            princ = kw['principal']
            princ_dn = kw['principal_dn']
        except KeyError, e:
            turbogears.flash("Principal show failed. Unable to find key %s" % e)
            raise turbogears.redirect("/principal/list")
       
        principal = {}

        try:
            # The principal info is passed in. Not going to both to re-query this.
            (service,host) = princ.split('/')
            h = host.split('@')
            principal['service'] = service
            principal['hostname'] = h[0]
            principal['principal_dn'] = princ_dn

            return dict(principal=principal)
        except:
            turbogears.flash("Principal show failed %s" % princ)
            raise turbogears.redirect("/")

    @expose()
    @identity.require(identity.in_group("admins"))
    def delete(self, principal):
        """Delete a service principal"""
        self.restrict_post()
        client = self.get_ipaclient()

        print "Deleting %s" % principal

        try:
            client.delete_service_principal(principal)

            turbogears.flash("Service principal deleted")
            raise turbogears.redirect('/principal/list')
        except (SyntaxError, ipaerror.IPAError), e:
            turbogears.flash("Service principal deletion failed: " + str(e) + "<br/>" + e.detail[0]['desc'])
            raise turbogears.redirect('/principal/list')

    @validate(form=principal_new_form)
    @identity.require(identity.not_anonymous())
    def principalcreatevalidate(self, tg_errors=None, **kw):
        return tg_errors, kw