842917b598115a8f81f5dcc186deea7ae3442291
[cocanwiki.git] / scripts / cocanwiki.ml
1 (* COCANWIKI scripts.
2  * Written by Richard W.M. Jones <rich@merjis.com>.
3  * Copyright (C) 2004 Merjis Ltd.
4  * $Id: cocanwiki.ml,v 1.5 2004/09/09 09:35:33 rich Exp $
5  *)
6
7 open Apache
8 open Registry
9 open Cgi
10 open Printf
11
12 open Cocanwiki_ok
13
14 module Pool = DbiPool (Dbi_postgres)
15
16 (* This function is used to grab a database handle.  It's used in a couple
17  * of very special places, and is not for general consumption.
18  *)
19 let _get_dbh r = Pool.get r "cocanwiki"
20
21 (* The [CgiExit] exception should be folded back into the base
22  * mod_caml code at some point.  It just causes the 'run' function to
23  * return at that point safely.  (XXX)
24  *)
25 exception CgiExit
26
27 (* Permissions and restrictions.
28  *
29  * Use the optional ~restrict parameter to register_script to restrict
30  * who can use the script.  For example:
31  *   register_script ~restrict:[CanEdit ; CanManageUsers] run
32  *)
33 type permissions_t = CanEdit | CanManageUsers
34
35 (* The "user object". *)
36 type user_t = Anonymous                 (* Not logged in. *)
37             | User of int * string * permissions_t list
38                                         (* Userid, name, permissions. *)
39
40 let test_permission edit_anon perm user =
41   if perm = CanEdit && edit_anon then true
42   else match user with
43       Anonymous -> false
44     | User (_, _, perms) -> List.mem perm perms
45
46 let can_edit edit_anon = test_permission edit_anon CanEdit
47 let can_manage_users = test_permission false CanManageUsers
48
49 (* The "host object". *)
50 type host_t = { hostname : string;
51                 edit_anon : bool; }
52
53 (* Our wrapper around the standard [register_script] function.
54  *
55  * The optional ~restrict and ~anonymous parameters work as follows:
56  *
57  * By default (neither parameter given), anonymous or logged-in users
58  * at any level are permitted to run the script.
59  *
60  * If ~anonymous:false then a user must be logged in to use the script.
61  *
62  * If ~restrict contains a list of permissions (eg. CanEdit, etc.) then
63  * the user must have the ability to do AT LEAST ONE of those actions.
64  * (Note that this does not necessarily imply that the user must be
65  * logged in, because in some circumstances even anonymous users have
66  * the CanEdit permission - very typical for a wiki).
67  *
68  * If ~anonymous:false and ~restrict is given then the user must be
69  * logged in AND have the ability to do AT LEAST ONE of those actions.
70  *)
71 let register_script ?(restrict = []) ?(anonymous = true) run =
72   (* Actually register the script with the real [Registry] module. *)
73   register_script
74     (fun r ->
75        let q = new cgi r in
76        let dbh = _get_dbh r in
77
78        (* Get the host ID, by comparing the Host: header with the hostnames
79         * table in the database.
80         *)
81        let hostid, hostname, edit_anon =
82          let hostname = try Request.hostname r
83          with Not_found -> failwith "No ``Host:'' header in request" in
84          let hostname = String.lowercase hostname in
85
86          let sth =
87            dbh#prepare_cached
88              "select h.id, h.canonical_hostname, h.edit_anon
89                 from hostnames hn, hosts h
90                where hn.name = ? and hn.hostid = h.id" in
91          sth#execute [`String hostname];
92
93          try
94            (match sth#fetch1 () with
95                 [ `Int id; `String hostname; `Bool edit_anon ] ->
96                   id, hostname, edit_anon
97               | _ -> assert false)
98          with
99              Not_found ->
100                failwith ("Hostname ``" ^ hostname ^ "'' not found in " ^
101                          "the hosts/hostnames tables in the database.") in
102
103        (* Create the host object. *)
104        let host = { hostname = hostname; edit_anon = edit_anon; } in
105
106        (* Look for the user's cookie, and determine from this the user
107         * object.
108         *)
109        let user =
110          try
111            let cookie =
112              (* Allow the user to deliberately specify an extra "cookie"
113               * parameter, which we will send back as a cookie.  This is
114               * useful for "mail my password"-type scripts.
115               *)
116              if q#param_exists "cookie" then (
117                let value = q#param "cookie" in
118                let cookie = Cookie.cookie ~name:"auth" ~value ~path:"/" () in
119                Table.set (Request.headers_out r) "Set-Cookie" cookie#as_string;
120                value
121              ) else (
122                (* Normal cookie, from the headers. *)
123                let header = Table.get (Request.headers_in r) "Cookie" in
124                let cookies = Cookie.parse header in
125                let cookie =
126                  List.find (fun cookie -> cookie#name = "auth") cookies in
127                cookie#value
128              ) in
129
130            let sth =
131              dbh#prepare_cached
132                "select u.id, u.name, u.can_edit, u.can_manage_users
133                   from usercookies uc, users u
134                  where uc.cookie = ? and uc.userid = u.id and u.hostid = ?" in
135            sth#execute [`String cookie; `Int hostid];
136            (match sth#fetch1 () with
137                 [ `Int userid; `String name;
138                   `Bool can_edit; `Bool can_manage_users ] ->
139                   let perms =
140                     (if can_edit then [ CanEdit ] else []) @
141                     (if can_manage_users then [ CanManageUsers ] else []) in
142                   User (userid, name, perms)
143               | _ -> assert false)
144          with
145              Not_found -> Anonymous
146        in
147
148        (* If the ~restrict parameter is given, then we want to check that
149         * the user has sufficient permission to run this script.
150         *)
151        let permitted =
152          if not anonymous && user = Anonymous then false
153          else
154            match restrict with
155                [] -> true               (* empty list = no restrictions *)
156              | rs ->
157                  List.fold_left ((||)) false
158                    (List.map (fun r -> test_permission edit_anon r user) rs) in
159
160        if permitted then (
161          (* Call the actual CGI script. *)
162          try
163            run r q dbh hostid host user
164          with
165              CgiExit -> ()
166        ) else
167          error ~back_button:true
168            ~title:"Access denied"
169            q "You do not have permission to access this part of the site."
170     )