KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > roller > business > utils > PasswordUtility


1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. The ASF licenses this file to You
4 * under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License. For additional information regarding
15 * copyright in this work, please see the NOTICE file in the top level
16 * directory of this distribution.
17 */

18
19 package org.apache.roller.business.utils;
20
21 import java.io.FileInputStream JavaDoc;
22 import java.io.FileOutputStream JavaDoc;
23 import java.sql.Connection JavaDoc;
24 import java.sql.DriverManager JavaDoc;
25 import java.sql.PreparedStatement JavaDoc;
26 import java.sql.ResultSet JavaDoc;
27 import java.util.Enumeration JavaDoc;
28 import java.util.Properties JavaDoc;
29 import org.apache.roller.util.Utilities;
30
31 /**
32  * Roller password utility: don't run this unless you know what you are doing!</br >
33  *
34  * <p>Configuration:<br />
35  *
36  * Program looks in current directory for db.properties file with database
37  * connection properties driverClassName and connectionUrl.
38  *
39  * Program expects JDBC driver jar to be on classpath.</p>
40  *
41  * <p>Usage:<br />
42  *
43  * java -cp ./WEB-INF/lib/rollerbeans.jar;./jdbc.jar org.apache.roller.business.utils.PasswordUtility<br />
44  *
45  * <br />Options:<br />
46  *
47  * -save &lt;file-name&gt;: Save username/passwords in property file<br />
48  * -encrypt : turn on encryption and encrypt passwords<br />
49  * -restore &lt;file-name> : turn off encryption and restore passwords from file<br />
50  * -reset &lt;username&gt; &lt;password&gt;: reset users password<br />
51  * -grant_admin &lt;username&gt;<br />
52  * -revoke_admin &lt;username&gt;</p>
53  */

54 public class PasswordUtility
55 {
56     public static void main(String JavaDoc[] args) throws Exception JavaDoc
57     {
58         Properties JavaDoc props = new Properties JavaDoc();
59         props.load(new FileInputStream JavaDoc("rollerdb.properties"));
60         
61         String JavaDoc algorithm = props.getProperty("algorithm");
62         
63         Connection JavaDoc con = ConsistencyCheck.createConnection(props,"");
64         
65         if (args.length == 2 && args[0].equals("-save"))
66         {
67             savePasswords(con, args[1]);
68         }
69         else if (args.length == 1 && args[0].equals("-encrypt"))
70         {
71             encryptionOn(con, algorithm);
72         }
73         else if (args.length == 2 && args[0].equals("-restore"))
74         {
75             encryptionOff(con, args[1]);
76         }
77         else if (args.length == 3 && args[0].equals("-reset"))
78         {
79             resetPassword(con, args[1], args[2], algorithm);
80         }
81         else if (args.length == 2 && args[0].equals("-grant_admin"))
82         {
83             grantAdmin(con, args[1]);
84         }
85         else if (args.length == 2 && args[0].equals("-revoke_admin"))
86         {
87             revokeAdmin(con, args[1]);
88         }
89         else
90         {
91             System.out.println("");
92             System.out.println("USAGE: save passwords to a properties file");
93             System.out.println(" rollerpw -save <file-name>");
94             System.out.println("");
95             System.out.println("USAGE: turn ON password encryption and encrypt existing passwords");
96             System.out.println(" rollerpw -encrypt");
97             System.out.println("");
98             System.out.println("USAGE: turn OFF password encryption and restore saved passwords");
99             System.out.println(" rollerpw -restore <file-name>");
100             System.out.println("");
101             System.out.println("USAGE: reset a user password");
102             System.out.println(" rollerpw -password <username> <new-password>");
103             System.out.println("");
104             System.out.println("USAGE: grant admin rights to user");
105             System.out.println(" rollerpw -grant_admin <username>");
106             System.out.println("");
107             System.out.println("USAGE: revoke admin right from user");
108             System.out.println(" rollerpw -revoke_admin <username>");
109             System.out.println("");
110         }
111     }
112     
113     /**
114      * Saves usernames and passwords to properties file, passwords keyed by usernames
115      */

116     private static void savePasswords(
117                     Connection JavaDoc con, String JavaDoc fileName) throws Exception JavaDoc
118     {
119         Properties JavaDoc newprops = new Properties JavaDoc();
120         PreparedStatement JavaDoc userquery = con.prepareStatement(
121            "select username,passphrase from rolleruser");
122         ResultSet JavaDoc users = userquery.executeQuery();
123         while (users.next())
124         {
125             String JavaDoc username = users.getString(1);
126             String JavaDoc passphrase = users.getString(2);
127             newprops.put(username, passphrase);
128         }
129         FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(fileName);
130         newprops.save(fos, "Generated by Roller Password Utility");
131         fos.close();
132     }
133
134     /**
135      * Encrypt all passwords in rolleruser and turn ON encryption flag in rollerconfig
136      */

137     private static void encryptionOn(
138                     Connection JavaDoc con, String JavaDoc algorithm) throws Exception JavaDoc
139     {
140         PreparedStatement JavaDoc userQuery = con
141             .prepareStatement("select username,passphrase from rolleruser");
142         PreparedStatement JavaDoc userUpdate = con
143             .prepareStatement("update rolleruser set passphrase=? where username=?");
144         PreparedStatement JavaDoc configUpdate = con
145             .prepareStatement("update rollerconfig set encryptpasswords=?");
146
147         Properties JavaDoc props = new Properties JavaDoc();
148         ResultSet JavaDoc users = userQuery.executeQuery();
149         while (users.next())
150         {
151             String JavaDoc username = users.getString(1);
152             String JavaDoc passphrase = users.getString(2);
153             props.put(username, passphrase);
154         }
155         Enumeration JavaDoc usernames = props.keys();
156         while (usernames.hasMoreElements())
157         {
158             String JavaDoc username = (String JavaDoc)usernames.nextElement();
159             String JavaDoc passphrase = (String JavaDoc)props.get(username);
160             userUpdate.clearParameters();
161             userUpdate.setString(1, Utilities.encodePassword(passphrase, algorithm));
162             userUpdate.setString(2, username);
163             userUpdate.executeUpdate();
164             System.out.println("Encrypted password for user: " + username);
165         }
166         
167         configUpdate.setBoolean(1, true);
168         configUpdate.executeUpdate();
169     }
170
171     /**
172      * Restore passwords in rolleruser and turn OFF encryption flag in rollerconfig
173      */

174     private static void encryptionOff(
175                     Connection JavaDoc con, String JavaDoc fileName) throws Exception JavaDoc
176     {
177         PreparedStatement JavaDoc userUpdate = con
178             .prepareStatement("update rolleruser set passphrase=? where username=?");
179         PreparedStatement JavaDoc configUpdate = con
180             .prepareStatement("update rollerconfig set encryptpasswords=?");
181
182         Properties JavaDoc props = new Properties JavaDoc();
183         props.load(new FileInputStream JavaDoc(fileName));
184         Enumeration JavaDoc usernames = props.keys();
185         while (usernames.hasMoreElements())
186         {
187             String JavaDoc username = (String JavaDoc)usernames.nextElement();
188             String JavaDoc password = (String JavaDoc)props.get(username);
189             userUpdate.clearParameters();
190             userUpdate.setString(1, password);
191             userUpdate.setString(2, username);
192             userUpdate.executeUpdate();
193         }
194         
195         configUpdate.setBoolean(1, false);
196         configUpdate.executeUpdate();
197     }
198
199     /**
200      * Reset user's password to specified value using specified algorythm (if needed)
201      */

202     private static void resetPassword(
203                     Connection JavaDoc con, String JavaDoc username, String JavaDoc password, String JavaDoc algorithm)
204             throws Exception JavaDoc
205     {
206         PreparedStatement JavaDoc encryptionQuery =
207             con.prepareStatement("select encryptpasswords from rollerconfig");
208         PreparedStatement JavaDoc userUpdate =
209             con.prepareStatement("update rolleruser set passphrase=? where username=?");
210         
211         ResultSet JavaDoc rs = encryptionQuery.executeQuery();
212         rs.next();
213         boolean encryption = rs.getBoolean(1);
214         
215         String JavaDoc newpassword =
216             encryption ? Utilities.encodePassword(password, algorithm) : password;
217         userUpdate.setString(1, newpassword);
218         userUpdate.setString(2, username);
219         userUpdate.executeUpdate();
220     }
221     
222     /**
223      * Grant admin role to user by adding admin role for user to userrole table
224      */

225     private static void grantAdmin(Connection JavaDoc con, String JavaDoc userName) throws Exception JavaDoc
226     {
227         // Find userid of specified user
228
String JavaDoc userid = null;
229         PreparedStatement JavaDoc userQuery = con.prepareStatement(
230            "select id from rolleruser where username=?");
231         userQuery.setString(1, userName);
232         ResultSet JavaDoc userRS = userQuery.executeQuery();
233         if (!userRS.next())
234         {
235             System.err.println("ERROR: username not found in database");
236             return;
237         }
238         else
239         {
240             userid = userRS.getString(1);
241         }
242         
243         // Is user already an admin?
244
PreparedStatement JavaDoc roleQuery = con.prepareStatement(
245            "select username from userrole where username=? and rolename='admin'");
246         roleQuery.setString(1, userName);
247         ResultSet JavaDoc roleRS = roleQuery.executeQuery();
248         if (!roleRS.next()) // then no, user is not admin
249
{
250             // Add admin role for user
251
PreparedStatement JavaDoc adminInsert = con.prepareStatement(
252                "insert into userrole (id,rolename,username,userid) values (?,?,?,?)");
253             adminInsert.setString(1, userName);
254             adminInsert.setString(2, "admin");
255             adminInsert.setString(3, userName);
256             adminInsert.setString(4, userid);
257             adminInsert.executeUpdate();
258             System.out.println("User granted admin role");
259         }
260         else
261         {
262             System.out.println("User was already an admin");
263         }
264     }
265
266     /**
267      * Revoke admin role from user by removing admin role from userrole table
268      */

269     private static void revokeAdmin(Connection JavaDoc con, String JavaDoc userName) throws Exception JavaDoc
270     {
271         // Find userid of specified user
272
String JavaDoc userid = null;
273         PreparedStatement JavaDoc userQuery = con.prepareStatement(
274            "select id from rolleruser where username=?");
275         userQuery.setString(1, userName);
276         ResultSet JavaDoc userRS = userQuery.executeQuery();
277         if (!userRS.next())
278         {
279             System.err.println("ERROR: username not found in database");
280             return;
281         }
282         else
283         {
284             userid = userRS.getString(1);
285         }
286         
287         // Delete user's admin entries from userrole table
288
PreparedStatement JavaDoc roleDelete = con.prepareStatement(
289            "delete from userrole where userid=? and rolename='admin'");
290         roleDelete.setString(1, userid);
291         roleDelete.executeUpdate();
292     }
293 }
294
Popular Tags