chiark / gitweb /
{cgi,cmd-cgi,httpauth}.py: Check request methods on CGI commands.
[chopwood] / cmd-cgi.py
CommitLineData
a2916c06
MW
1### -*-python-*-
2###
3### CGI commands
4###
5### (c) 2013 Mark Wooding
6###
7
8###----- Licensing notice ---------------------------------------------------
9###
10### This file is part of Chopwood: a password-changing service.
11###
12### Chopwood is free software; you can redistribute it and/or modify
13### it under the terms of the GNU Affero General Public License as
14### published by the Free Software Foundation; either version 3 of the
15### License, or (at your option) any later version.
16###
17### Chopwood is distributed in the hope that it will be useful,
18### but WITHOUT ANY WARRANTY; without even the implied warranty of
19### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20### GNU Affero General Public License for more details.
21###
22### You should have received a copy of the GNU Affero General Public
23### License along with Chopwood; if not, see
24### <http://www.gnu.org/licenses/>.
25
26from __future__ import with_statement
27
28import errno as E
29import os as OS
30
31from auto import PACKAGE, VERSION
32import agpl as AGPL
33import cgi as CGI
34import cmdutil as CU
35import dbmaint as D
36import httpauth as HA
37import operation as OP
38import output as O; OUT = O.OUT; PRINT = O.PRINT
39import service as S
40import subcommand as SC
41import util as U
42
43###--------------------------------------------------------------------------
44### Utilities.
45
46def operate(what, op, services, *args, **kw):
47 accts = CU.resolve_accounts(CU.USER, services)
48 o, ii, rq, ops = OP.operate(op, accts, *args, **kw)
49 CGI.page('operate.fhtml',
50 header = dict(pragma = 'no-cache', cache_control = 'no-cache'),
51 title = 'Chopwood: %s' % what,
52 what = what,
53 outcome = o, info = ii, results = ops)
54
55###--------------------------------------------------------------------------
56### Commands.
57
58@CGI.subcommand('list', ['cgi-query'], 'List available accounts')
59def cmd_list_cgi():
60 CGI.page('list.fhtml',
6a749ccf 61 header = dict(pragma = 'no-cache', cache_control = 'no-cache'),
a2916c06
MW
62 title = 'Chopwood: accounts list',
63 accts = CU.list_accounts(CU.USER),
64 nonce = HA.NONCE)
65
66@CGI.subcommand(
67 'set', ['cgi'], 'Set password for a collection of services.',
9e574017 68 methods = ['POST'],
a2916c06
MW
69 params = [SC.Arg('first'), SC.Arg('second')],
70 rparam = SC.Arg('services'))
71def cmd_set_cgi(first, second, services = []):
72 if first != second: raise U.ExpectedError, (400, "Passwords don't match")
73 operate('set passwords', 'set', services, first)
74
75@CGI.subcommand(
76 'reset', ['cgi'],
77 'Reset passwords for a collection of services.',
9e574017 78 methods = ['POST'],
a2916c06
MW
79 rparam = SC.Arg('services'))
80def cmd_reset_cgi(services = []):
81 operate('reset passwords', 'reset', services)
82
83@CGI.subcommand(
84 'clear', ['cgi'],
85 'Clear passwords for a collection of services.',
9e574017 86 methods = ['POST'],
a2916c06
MW
87 rparam = SC.Arg('services'))
88def cmd_clear_cgi(services = []):
89 operate('clear passwords', 'clear', services)
90
170f1769
MW
91@CGI.subcommand(
92 'logout', ['cgi'],
9e574017
MW
93 'Log out of the web interface.',
94 methods = ['POST'])
170f1769
MW
95def cmd_logout_cgi():
96 CGI.redirect(CGI.action('login', why = 'LOGOUT'),
97 set_cookie = HA.bake_cookie('logged-out'))
98
a2916c06
MW
99@CGI.subcommand(
100 'fail', ['cgi-noauth'],
101 'Raise an exception, to test the error reporting machinery.',
102 opts = [SC.Opt('partial', '-p', '--partial',
103 'Raise exception after producing partial output.')])
104def cmd_fail_cgi(partial = False):
105 if partial:
106 OUT.header(content_type = 'text/html')
107 PRINT("""\
108<html>
109<head><title>Chopwood: filler text</title></head>
110<body>
111<h1>Failure expected soon
112<p>This is some normal output which will be rudely interrupted.""")
113 raise Exception, 'You asked for this.'
114
115###--------------------------------------------------------------------------
116### Static content.
117
118## A map of file names to content objects. See below.
119CONTENT = {}
120
121class PlainOutput (O.FileOutput):
122 def header(me, **kw):
123 pass
124
125class StaticContent (object):
126 def __init__(me, type):
127 me._type = type
128 def emit(me):
129 OUT.header(content_type = me._type)
130 me._emit()
131 def _write(me, dest):
132 with open(dest, 'w') as f:
133 with OUT.redirect_to(PlainOutput(f)):
134 me.emit()
135 def write(me, dest):
136 new = dest + '.new'
137 try: OS.unlink(new)
138 except OSError, e:
139 if e.errno != E.ENOENT: raise
140 me._write(new)
141 OS.rename(new, dest)
142
143class TemplateContent (StaticContent):
144 def __init__(me, template, *args, **kw):
145 super(TemplateContent, me).__init__(*args, **kw)
146 me._template = template
147 def _emit(me):
148 CGI.format_tmpl(CGI.TMPL[me._template])
149
150class HTMLContent (StaticContent):
151 def __init__(me, title, template, type = 'text/html', *args, **kw):
152 super(HTMLContent, me).__init__(type = type, *args, **kw)
153 me._template = template
154 me._title = title
155 def emit(me):
156 CGI.page(me._template, title = me._title)
157
158CONTENT.update({
159 'chpwd.css': TemplateContent(template = 'chpwd.css',
160 type = 'text/css'),
161 'chpwd.js': TemplateContent(template = 'chpwd.js',
162 type = 'text/javascript'),
163 'about.html': HTMLContent('Chopwood: about this program',
164 template = 'about.fhtml'),
165 'cookies.html': HTMLContent('Chopwood: use of cookies',
166 template = 'cookies.fhtml')
167})
168
169@CGI.subcommand(
170 'static', ['cgi-noauth'], 'Output a static file.',
171 rparam = SC.Arg('path'))
172def cmd_static_cgi(path):
173 name = '/'.join(path)
174 try: content = CONTENT[name]
175 except KeyError: raise U.ExpectedError, (404, "Unknown file `%s'" % name)
176 content.emit()
177
178@SC.subcommand(
179 'static', ['admin'], 'Write the static files to DIR.',
180 params = [SC.Arg('dir')])
181def cmd_static_admin(dir):
182 try: OS.makedirs(dir, 0777)
183 except OSError, e:
184 if e.errno != E.EEXIST: raise
185 for f, c in CONTENT.iteritems():
186 c.write(OS.path.join(dir, f))
187
188TARBALL = '%s-%s.tar.gz' % (PACKAGE, VERSION)
189@CGI.subcommand(TARBALL, ['cgi-noauth'], """\
190Download source code (in `.tar.gz' format).""")
191def cmd_source_cgi():
192 OUT.header(content_type = 'application/octet-stream')
193 AGPL.source(OUT)
194
195@CGI.subcommand('source', ['cgi-noauth'], """\
d674bfda 196Redirect to the source code tarball (so that it's correctly named).""")
a2916c06
MW
197def cmd_sourceredirect_cgi():
198 CGI.redirect(CGI.action(TARBALL))
199
200###----- That's all, folks --------------------------------------------------