Change password form.
[cocanwiki.git] / scripts / change_password.ml
1 (* COCANWIKI - a wiki written in Objective CAML.
2  * Written by Richard W.M. Jones <rich@merjis.com>.
3  * Copyright (C) 2004 Merjis Ltd.
4  * $Id: change_password.ml,v 1.1 2004/09/25 13:17:00 rich Exp $
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; see the file COPYING.  If not, write to
18  * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *)
21
22 open Apache
23 open Registry
24 open Cgi
25 open Printf
26
27 open Cocanwiki
28 open Cocanwiki_ok
29
30 let run r (q : cgi) (dbh : Dbi.connection) hostid _ user =
31   let old_password = q#param "old_password" in
32
33   (* Check the old password was supplied correctly. *)
34   let userid =
35     match user with
36         Anonymous -> assert false (* cannot happen *)
37       | User (userid, _, _) -> userid in
38
39   let sth = dbh#prepare_cached "select 1 from users
40                                  where id = ? and password = ?" in
41   sth#execute [`Int userid; `String old_password];
42
43   let old_password_ok =
44     try 1 = sth#fetch1int ()
45     with
46         Not_found -> false in
47
48   if not old_password_ok then (
49     error ~title:"Bad password"
50       ~back_button:true
51       q "The password you gave is wrong.";
52     return ()
53   );
54
55   let password1 = q#param "password1" in
56   let password2 = q#param "password2" in
57
58   if password1 = "" || password2 = "" then (
59     error ~back_button:true ~title:"Bad password"
60       q "The password you gave is empty.";
61     return ()
62   );
63
64   if password1 <> password2 then (
65     error ~back_button:true ~title:"Passwords don't match"
66       q "The two passwords you gave aren't identical.";
67     return ()
68   );
69
70   let password = password1 in
71
72   (* Change the password. *)
73   let sth =
74     dbh#prepare_cached
75       "update users set password = ?, force_password_change = false
76         where id = ?" in
77   sth#execute [`String password; `Int userid];
78
79   dbh#commit ();
80
81   let buttons = [ ok_button "/" ] in
82   ok ~buttons ~title:"Password changed"
83     q "The password was changed."
84
85 let () =
86   register_script ~anonymous:false run