1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.talika.jsm;
24
25 import java.security.*;
26 import java.sql.*;
27 import javax.sql.*;
28 import java.util.Set;
29
30 import org.jboss.security.RealmMapping;
31 import org.jboss.security.EJBSecurityManager;
32
33 /***
34 *
35 * @author Jose M. Palomar <josem@talika.org>
36 * @version $Revision: 3 $
37 */
38 public class DatabaseSecurityModule
39 implements RealmMapping, EJBSecurityManager
40 {
41
42 /*** Creates new DatabaseSecurityModule */
43 public DatabaseSecurityModule(DataSource ds) {
44 _ds = ds;
45 }
46
47 public Principal getPrincipal(Principal principal) {
48 return principal;
49 }
50
51 public boolean doesUserHaveRole(Principal principal, Set roles) {
52
53 boolean hasRole = false;
54
55 if(principal != null && roles != null) {
56
57 Connection con = null;
58
59 try {
60
61 con = _ds.getConnection();
62 PreparedStatement psmt = con.prepareStatement(ROLES_QUERY_STRING);
63 psmt.setString(1,principal.getName());
64 ResultSet rs = psmt.executeQuery();
65
66 while(rs.next() && !hasRole) {
67
68 String role = rs.getString(1).trim();
69 if (roles.contains(role))
70 hasRole = true;
71
72 }
73
74 psmt.close();
75 rs.close();
76
77 }
78 catch(SQLException sqle) {
79 sqle.printStackTrace();
80 }
81 finally {
82
83 try {
84 if (con != null) con.close();
85 }
86 catch (Exception e) {}
87
88 }
89
90 }
91
92 return hasRole;
93
94 }
95
96 public boolean isValid(Principal principal, Object credential) {
97
98 boolean valid = false;
99
100 if(principal != null && credential != null) {
101
102 Connection con = null;
103
104 try {
105
106 con = _ds.getConnection();
107 PreparedStatement psmt = con.prepareStatement(USERS_QUERY_STRING);
108 psmt.setString(1,principal.getName());
109 ResultSet rs = psmt.executeQuery();
110
111 if(rs.next()) {
112
113 String dbCredential = rs.getString(1).trim();
114 if(dbCredential.equals(credential.toString().trim()))
115 valid = true;
116
117 }
118
119 psmt.close();
120 rs.close();
121
122 }
123 catch(SQLException sqle) {
124 sqle.printStackTrace();
125 }
126 finally {
127
128 try {
129 if (con != null) con.close();
130 }
131 catch (Exception e) {}
132
133 }
134
135 }
136
137 return valid;
138
139 }
140
141 private DataSource _ds = null;
142
143 public final static String USERS_TABLE = "j2ee_users";
144 public final static String ROLES_TABLE = "j2ee_roles";
145 public final static String USER_FIELD = "username";
146 public final static String PASSWORD_FIELD = "password";
147 public final static String ROLE_FIELD = "rolename";
148
149 private final static String USERS_QUERY_STRING =
150 "select " + PASSWORD_FIELD + " from " + USERS_TABLE + " where " + USER_FIELD +"=?";
151 private final static String ROLES_QUERY_STRING =
152 "select " + ROLE_FIELD + " from " + ROLES_TABLE + " where " + USER_FIELD +"=?";
153
154 }