KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > core > ejb > ra > LocalUserAdminSessionBean


1 /*************************************************************************
2  * *
3  * EJBCA: The OpenSource Certificate Authority *
4  * *
5  * This software is free software; you can redistribute it and/or *
6  * modify it under the terms of the GNU Lesser General Public *
7  * License as published by the Free Software Foundation; either *
8  * version 2.1 of the License, or any later version. *
9  * *
10  * See terms of license at gnu.org. *
11  * *
12  *************************************************************************/

13
14 package org.ejbca.core.ejb.ra;
15
16 import java.awt.print.PrinterException JavaDoc;
17 import java.math.BigInteger JavaDoc;
18 import java.sql.Connection JavaDoc;
19 import java.sql.PreparedStatement JavaDoc;
20 import java.sql.ResultSet JavaDoc;
21 import java.util.ArrayList JavaDoc;
22 import java.util.Collection JavaDoc;
23 import java.util.Date JavaDoc;
24 import java.util.HashMap JavaDoc;
25 import java.util.Iterator JavaDoc;
26
27 import javax.ejb.CreateException JavaDoc;
28 import javax.ejb.DuplicateKeyException JavaDoc;
29 import javax.ejb.EJBException JavaDoc;
30 import javax.ejb.FinderException JavaDoc;
31 import javax.ejb.ObjectNotFoundException JavaDoc;
32 import javax.ejb.RemoveException JavaDoc;
33 import javax.mail.Message JavaDoc;
34 import javax.mail.Session JavaDoc;
35 import javax.mail.Transport JavaDoc;
36 import javax.mail.internet.InternetAddress JavaDoc;
37
38 import org.ejbca.core.ejb.BaseSessionBean;
39 import org.ejbca.core.ejb.JNDINames;
40 import org.ejbca.core.ejb.approval.IApprovalSessionLocal;
41 import org.ejbca.core.ejb.approval.IApprovalSessionLocalHome;
42 import org.ejbca.core.ejb.authorization.IAuthorizationSessionLocal;
43 import org.ejbca.core.ejb.authorization.IAuthorizationSessionLocalHome;
44 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionLocal;
45 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionLocalHome;
46 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocal;
47 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocalHome;
48 import org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionLocal;
49 import org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionLocalHome;
50 import org.ejbca.core.ejb.log.ILogSessionLocal;
51 import org.ejbca.core.ejb.log.ILogSessionLocalHome;
52 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionLocal;
53 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionLocalHome;
54 import org.ejbca.core.model.InternalResources;
55 import org.ejbca.core.model.SecConst;
56 import org.ejbca.core.model.approval.ApprovalException;
57 import org.ejbca.core.model.approval.ApprovalExecutorUtil;
58 import org.ejbca.core.model.approval.ApprovalOveradableClassName;
59 import org.ejbca.core.model.approval.WaitingForApprovalException;
60 import org.ejbca.core.model.approval.approvalrequests.AddEndEntityApprovalRequest;
61 import org.ejbca.core.model.approval.approvalrequests.ChangeStatusEndEntityApprovalRequest;
62 import org.ejbca.core.model.approval.approvalrequests.EditEndEntityApprovalRequest;
63 import org.ejbca.core.model.authorization.AuthorizationDeniedException;
64 import org.ejbca.core.model.authorization.AvailableAccessRules;
65 import org.ejbca.core.model.ca.caadmin.CAInfo;
66 import org.ejbca.core.model.ca.certificateprofiles.CertificateProfile;
67 import org.ejbca.core.model.ca.crl.RevokedCertInfo;
68 import org.ejbca.core.model.log.Admin;
69 import org.ejbca.core.model.log.LogConstants;
70 import org.ejbca.core.model.log.LogEntry;
71 import org.ejbca.core.model.ra.ExtendedInformation;
72 import org.ejbca.core.model.ra.NotFoundException;
73 import org.ejbca.core.model.ra.RAAuthorization;
74 import org.ejbca.core.model.ra.UserAdminConstants;
75 import org.ejbca.core.model.ra.UserDataConstants;
76 import org.ejbca.core.model.ra.UserDataVO;
77 import org.ejbca.core.model.ra.raadmin.EndEntityProfile;
78 import org.ejbca.core.model.ra.raadmin.GlobalConfiguration;
79 import org.ejbca.core.model.ra.raadmin.UserDoesntFullfillEndEntityProfile;
80 import org.ejbca.util.CertTools;
81 import org.ejbca.util.JDBCUtil;
82 import org.ejbca.util.NotificationParamGen;
83 import org.ejbca.util.PrinterManager;
84 import org.ejbca.util.StringTools;
85 import org.ejbca.util.TemplateMimeMessage;
86 import org.ejbca.util.query.BasicMatch;
87 import org.ejbca.util.query.IllegalQueryException;
88 import org.ejbca.util.query.Query;
89 import org.ejbca.util.query.UserMatch;
90
91
92
93 /**
94  * Administrates users in the database using UserData Entity Bean.
95  * Uses JNDI name for datasource as defined in env 'Datasource' in ejb-jar.xml.
96  *
97  * @version $Id: LocalUserAdminSessionBean.java,v 1.38.2.3 2007/05/16 09:30:22 jeklund Exp $
98  *
99  * @ejb.bean
100  * display-name="UserAdminSB"
101  * name="UserAdminSession"
102  * jndi-name="UserAdminSession"
103  * view-type="both"
104  * type="Stateless"
105  * transaction-type="Container"
106  *
107  * @ejb.transaction type="Required"
108  *
109  * @weblogic.enable-call-by-reference True
110  *
111  * @ejb.env-entry
112  * name="DataSource"
113  * type="java.lang.String"
114  * value="${datasource.jndi-name-prefix}${datasource.jndi-name}"
115  *
116  * @ejb.env-entry
117  * description="Defines the JNDI name of the mail service used"
118  * name="MailJNDIName"
119  * type="java.lang.String"
120  * value="${mail.jndi-name}"
121  *
122  * @ejb.env-entry
123  * description="Defines the sender of the notification message"
124  * name="sender"
125  * type="java.lang.String"
126  * value="${mail.from}"
127  *
128  * @ejb.env-entry
129  * description="Defines the subject used in the notification message"
130  * name="subject"
131  * type="java.lang.String"
132  * value="${mail.subject}"
133  *
134  * @ejb.env-entry
135  * description="Defines the actual message of the notification. Use the values $Username, $Password, $CN, $O, $OU, $C, $DATE to indicate which texts that should be replaced (Case insensitive), $NL stands for newline."
136  * name="message"
137  * type="java.lang.String"
138  * value="${mail.message}"
139  *
140  * @ejb.home
141  * extends="javax.ejb.EJBHome"
142  * local-extends="javax.ejb.EJBLocalHome"
143  * local-class="org.ejbca.core.ejb.ra.IUserAdminSessionLocalHome"
144  * remote-class="org.ejbca.core.ejb.ra.IUserAdminSessionHome"
145  *
146  * @ejb.interface
147  * extends="javax.ejb.EJBObject"
148  * local-extends="javax.ejb.EJBLocalObject"
149  * local-class="org.ejbca.core.ejb.ra.IUserAdminSessionLocal"
150  * remote-class="org.ejbca.core.ejb.ra.IUserAdminSessionRemote"
151  *
152  * @ejb.ejb-external-ref
153  * description="The Certificate Store session bean"
154  * view-type="local"
155  * ref-name="ejb/CertificateStoreSessionLocal"
156  * type="Session"
157  * home="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocalHome"
158  * business="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocal"
159  * link="CertificateStoreSession"
160  *
161  * @ejb.ejb-external-ref
162  * description="The Log session bean"
163  * view-type="local"
164  * ref-name="ejb/LogSessionLocal"
165  * type="Session"
166  * home="org.ejbca.core.ejb.log.ILogSessionLocalHome"
167  * business="org.ejbca.core.ejb.log.ILogSessionLocal"
168  * link="LogSession"
169  *
170  * @ejb.ejb-external-ref
171  * description="The Authorization session bean"
172  * view-type="local"
173  * ref-name="ejb/AuthorizationSessionLocal"
174  * type="Session"
175  * home="org.ejbca.core.ejb.authorization.IAuthorizationSessionLocalHome"
176  * business="org.ejbca.core.ejb.authorization.IAuthorizationSessionLocal"
177  * link="AuthorizationSession"
178  *
179  * @ejb.ejb-external-ref
180  * description="The Ra Admin session bean"
181  * view-type="local"
182  * ref-name="ejb/RaAdminSessionLocal"
183  * type="Session"
184  * home="org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionLocalHome"
185  * business="org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionLocal"
186  * link="RaAdminSession"
187  *
188  * @ejb.ejb-external-ref
189  * description="The Key Recovery session bean"
190  * view-type="local"
191  * ref-name="ejb/KeyRecoverySessionLocal"
192  * type="Session"
193  * home="org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionLocalHome"
194  * business="org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionLocal"
195  * link="KeyRecoverySession"
196  *
197  * @ejb.ejb-external-ref description="The Approval Session Bean"
198  * view-type="local"
199  * ref-name="ejb/ApprovalSessionLocal"
200  * type="Session"
201  * home="org.ejbca.core.ejb.approval.IApprovalSessionLocalHome"
202  * business="org.ejbca.core.ejb.approval.IApprovalSessionLocal"
203  * link="ApprovalSession"
204  *
205  * @ejb.ejb-external-ref description="The CAAdmin Session Bean"
206  * view-type="local"
207  * ref-name="ejb/CAAdminSessionLocal"
208  * type="Session"
209  * home="org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionLocalHome"
210  * business="org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionLocal"
211  * link="CAAdminSession"
212  *
213  * @ejb.ejb-external-ref
214  * description="The User entity bean"
215  * view-type="local"
216  * ref-name="ejb/UserDataLocal"
217  * type="Entity"
218  * home="org.ejbca.core.ejb.ra.UserDataLocalHome"
219  * business="org.ejbca.core.ejb.ra.UserDataLocal"
220  * link="UserData"
221  *
222  * @ejb.resource-ref
223  * res-ref-name="mail/DefaultMail"
224  * res-type="javax.mail.Session"
225  * res-auth="Container"
226  *
227  * @weblogic.resource-description
228  * res-ref-name="mail/DefaultMail"
229  * jndi-name="EjbcaMail"
230  *
231  */

232 public class LocalUserAdminSessionBean extends BaseSessionBean {
233
234     /** Internal localization of logs and errors */
235     private static final InternalResources intres = InternalResources.getInstance();
236
237     /**
238      * The local interface of RaAdmin Session Bean.
239      */

240     private IRaAdminSessionLocal raadminsession;
241
242     /**
243      * The local interface of the certificate store session bean
244      */

245     private ICertificateStoreSessionLocal certificatesession;
246
247     /**
248      * The local interface of the authorization session bean
249      */

250     private IAuthorizationSessionLocal authorizationsession;
251
252     /**
253      * The local interface of the authorization session bean
254      */

255     private IKeyRecoverySessionLocal keyrecoverysession;
256     
257     /**
258      * The local interface of the caadmin session bean
259      */

260     private ICAAdminSessionLocal caadminsession;
261     
262     /**
263      * The local interface of the approval session bean
264      */

265     private IApprovalSessionLocal approvalsession;
266
267     /**
268      * The remote interface of the log session bean
269      */

270     private ILogSessionLocal logsession;
271
272     private UserDataLocalHome home = null;
273     /**
274      * Columns in the database used in select
275      */

276     private static final String JavaDoc USERDATA_COL = "username, subjectDN, subjectAltName, subjectEmail, status, type, clearpassword, timeCreated, timeModified, endEntityprofileId, certificateProfileId, tokenType, hardTokenIssuerId, cAId, extendedInformationData";
277
278     /**
279      * Default create for SessionBean.
280      *
281      * @throws CreateException if bean instance can't be created
282      * @see org.ejbca.core.model.log.Admin
283      */

284     public void ejbCreate() throws CreateException JavaDoc {
285         try {
286             home = (UserDataLocalHome) getLocator().getLocalHome(UserDataLocalHome.COMP_NAME);
287
288             ILogSessionLocalHome logsessionhome = (ILogSessionLocalHome) getLocator().getLocalHome(ILogSessionLocalHome.COMP_NAME);
289             logsession = logsessionhome.create();
290
291             IAuthorizationSessionLocalHome authorizationsessionhome = (IAuthorizationSessionLocalHome) getLocator().getLocalHome(IAuthorizationSessionLocalHome.COMP_NAME);
292             authorizationsession = authorizationsessionhome.create();
293
294             IRaAdminSessionLocalHome raadminsessionhome = (IRaAdminSessionLocalHome) getLocator().getLocalHome(IRaAdminSessionLocalHome.COMP_NAME);
295             raadminsession = raadminsessionhome.create();
296
297             ICertificateStoreSessionLocalHome certificatesessionhome = (ICertificateStoreSessionLocalHome) getLocator().getLocalHome(ICertificateStoreSessionLocalHome.COMP_NAME);
298             certificatesession = certificatesessionhome.create();
299             
300             
301             ICAAdminSessionLocalHome caadminsessionhome = (ICAAdminSessionLocalHome) getLocator().getLocalHome(ICAAdminSessionLocalHome.COMP_NAME);
302             caadminsession = caadminsessionhome.create();
303             
304
305         } catch (Exception JavaDoc e) {
306             error("Error creating session bean:", e);
307             throw new EJBException JavaDoc(e);
308         }
309
310     }
311     
312     private IApprovalSessionLocal getApprovalSession(){
313       if(approvalsession == null){
314           try {
315             IApprovalSessionLocalHome approvalsessionhome = (IApprovalSessionLocalHome) getLocator().getLocalHome(IApprovalSessionLocalHome.COMP_NAME);
316             approvalsession = approvalsessionhome.create();
317         } catch (CreateException JavaDoc e) {
318             throw new EJBException JavaDoc(e);
319         }
320       }
321       return approvalsession;
322     }
323
324     private IKeyRecoverySessionLocal getKeyRecoverySession(){
325         if(keyrecoverysession == null){
326             try {
327                 IKeyRecoverySessionLocalHome keyrecoverysessionhome = (IKeyRecoverySessionLocalHome) getLocator().getLocalHome(IKeyRecoverySessionLocalHome.COMP_NAME);
328                 keyrecoverysession = keyrecoverysessionhome.create();
329         } catch (CreateException JavaDoc e) {
330             throw new EJBException JavaDoc(e);
331         }
332         }
333         return keyrecoverysession;
334       }
335
336     
337     /**
338      * Gets the Global Configuration from ra admin session bean-
339      */

340     private GlobalConfiguration getGlobalConfiguration(Admin admin) {
341         return raadminsession.loadGlobalConfiguration(admin);
342     }
343
344     private boolean authorizedToCA(Admin admin, int caid) {
345         boolean returnval = false;
346         try {
347             returnval = authorizationsession.isAuthorizedNoLog(admin, AvailableAccessRules.CAPREFIX + caid);
348         } catch (AuthorizationDeniedException e) {
349         }
350         return returnval;
351     }
352
353     private boolean authorizedToEndEntityProfile(Admin admin, int profileid, String JavaDoc rights) {
354         boolean returnval = false;
355         try {
356             if (profileid == SecConst.EMPTY_ENDENTITYPROFILE && (rights.equals(AvailableAccessRules.CREATE_RIGHTS) || rights.equals(AvailableAccessRules.EDIT_RIGHTS)))
357                 returnval = authorizationsession.isAuthorizedNoLog(admin, "/super_administrator");
358             else
359                 returnval = authorizationsession.isAuthorizedNoLog(admin, AvailableAccessRules.ENDENTITYPROFILEPREFIX + profileid + rights) &&
360                             authorizationsession.isAuthorizedNoLog(admin, AvailableAccessRules.REGULAR_RAFUNCTIONALITY + rights);
361         } catch (AuthorizationDeniedException e) {
362         }
363         return returnval;
364     }
365
366
367     /**
368      * Implements IUserAdminSession::addUser.
369      * Implements a mechanism that uses UserDataEntity Bean.
370      *
371      * Important, this method is old and shouldn't be used, user addUser(..UserDataVO...) instead.
372      *
373      * @param admin the administrator pwrforming the action
374      * @param username the unique username.
375      * @param password the password used for authentication.
376      * @param subjectdn the DN the subject is given in his certificate.
377      * @param subjectaltname the Subject Alternative Name to be used.
378      * @param email the email of the subject or null.
379      * @param clearpwd true if the password will be stored in clear form in the db, otherwise it is
380      * hashed.
381      * @param endentityprofileid the id number of the end entity profile bound to this user.
382      * @param certificateprofileid the id number of the certificate profile that should be
383      * generated for the user.
384      * @param type of user i.e administrator, keyrecoverable and/or sendnotification, from SecConst.USER_XX.
385      * @param tokentype the type of token to be generated, one of SecConst.TOKEN constants
386      * @param hardwaretokenissuerid , if token should be hard, the id of the hard token issuer,
387      * else 0.
388      * @param caid the CA the user should be issued from.
389      * @throws WaitingForApprovalException
390      * @throws ApprovalException
391      * @ejb.interface-method
392      */

393     public void addUser(Admin admin, String JavaDoc username, String JavaDoc password, String JavaDoc subjectdn, String JavaDoc subjectaltname, String JavaDoc email, boolean clearpwd, int endentityprofileid, int certificateprofileid,
394                         int type, int tokentype, int hardwaretokenissuerid, int caid)
395             throws AuthorizationDeniedException, UserDoesntFullfillEndEntityProfile, DuplicateKeyException JavaDoc, ApprovalException, WaitingForApprovalException {
396         
397         UserDataVO userdata = new UserDataVO(username, subjectdn, caid, subjectaltname,
398                                              email, UserDataConstants.STATUS_NEW, type, endentityprofileid, certificateprofileid,
399                                              null,null, tokentype, hardwaretokenissuerid, null);
400         userdata.setPassword(password);
401         addUser(admin, userdata, clearpwd);
402     }
403
404     private static final ApprovalOveradableClassName[] NONAPPROVABLECLASSNAMES_ADDUSER = {
405         new ApprovalOveradableClassName("org.ejbca.core.model.approval.approvalrequests.AddEndEntityApprovalRequest",null),
406     };
407     
408     /**
409      * Implements IUserAdminSession::addUser.
410      * Implements a mechanism that uses UserDataEntity Bean.
411      *
412      * @param admin the administrator pwrforming the action
413      * @param userdata a UserDataVO object, the fields status, timecreated and timemodified will not be used.
414      * @param clearpwd true if the password will be stored in clear form in the db, otherwise it is
415      * hashed.
416      * @throws AuthorizationDeniedException if administrator isn't authorized to add user
417      * @throws UserDoesntFullfillEndEntityProfile if data doesn't fullfil requirements of end entity profile
418      * @throws DuplicateKeyException if user already exists
419      * @throws ApprovalException if an approval already is waiting for specified action
420      * @throws WaitingForApprovalException if approval is required and the action have been added in the approval queue.
421      *
422      * @ejb.interface-method
423      */

424     public void addUser(Admin admin, UserDataVO userdata, boolean clearpwd) throws AuthorizationDeniedException, UserDoesntFullfillEndEntityProfile, DuplicateKeyException JavaDoc, ApprovalException, WaitingForApprovalException {
425         // String used in SQL so strip it
426
String JavaDoc dn = CertTools.stringToBCDNString(userdata.getDN());
427         dn = StringTools.strip(dn);
428         String JavaDoc altName = StringTools.strip(userdata.getSubjectAltName());
429         String JavaDoc username = StringTools.strip(userdata.getUsername());
430         String JavaDoc email = StringTools.strip(userdata.getEmail());
431         userdata.setUsername(username);
432         userdata.setDN(dn);
433         userdata.setSubjectAltName(altName);
434         userdata.setEmail(email);
435         int type = userdata.getType();
436         String JavaDoc newpassword = userdata.getPassword();
437         debug(">addUser(" + userdata.getUsername() + ", password, " + dn + ", "+ userdata.getDN() + ", " + userdata.getSubjectAltName()+", "+userdata.getEmail() + ")");
438         int profileId = userdata.getEndEntityProfileId();
439         String JavaDoc profileName = raadminsession.getEndEntityProfileName(admin, profileId);
440         EndEntityProfile profile = raadminsession.getEndEntityProfile(admin, profileId);
441
442         if (profile.useAutoGeneratedPasswd() && userdata.getPassword() == null) {
443             // special case used to signal regeneraton of password
444
newpassword = profile.getAutoGeneratedPasswd();
445         }
446
447
448         if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
449             // Check if user fulfills it's profile.
450
try {
451                 profile.doesUserFullfillEndEntityProfile(userdata.getUsername(), userdata.getPassword(), dn, userdata.getSubjectAltName(), userdata.getExtendedinformation().getSubjectDirectoryAttributes(), userdata.getEmail(), userdata.getCertificateProfileId(), clearpwd,
452                         (type & SecConst.USER_ADMINISTRATOR) != 0, (type & SecConst.USER_KEYRECOVERABLE) != 0, (type & SecConst.USER_SENDNOTIFICATION) != 0,
453                         userdata.getTokenType(), userdata.getHardTokenIssuerId(), userdata.getCAId());
454             } catch (UserDoesntFullfillEndEntityProfile udfp) {
455                 String JavaDoc msg = intres.getLocalizedMessage("ra.errorfullfillprofile", profileName, dn, udfp.getMessage());
456                 logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_ERROR_ADDEDENDENTITY, msg);
457                 throw new UserDoesntFullfillEndEntityProfile(udfp.getMessage());
458             }
459
460             // Check if administrator is authorized to add user.
461
if (!authorizedToEndEntityProfile(admin, userdata.getEndEntityProfileId(), AvailableAccessRules.CREATE_RIGHTS)) {
462                 String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthprofile", profileName);
463                 logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_ERROR_ADDEDENDENTITY, msg);
464                 throw new AuthorizationDeniedException(msg);
465             }
466         }
467
468         // Check if administrator is authorized to add user to CA.
469
if (!authorizedToCA(admin, userdata.getCAId())) {
470             String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthca", new Integer JavaDoc(userdata.getCAId()));
471             logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_ERROR_ADDEDENDENTITY, msg);
472             throw new AuthorizationDeniedException(msg);
473         }
474
475         // Check if approvals is required.
476
int numOfApprovalsRequired = getNumOfApprovalRequired(admin, CAInfo.REQ_APPROVAL_ADDEDITENDENTITY, userdata.getCAId());
477         AddEndEntityApprovalRequest ar = new AddEndEntityApprovalRequest(userdata,clearpwd,admin,null,numOfApprovalsRequired,userdata.getCAId(),userdata.getEndEntityProfileId());
478         if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_ADDUSER)) {
479             getApprovalSession().addApprovalRequest(admin, ar);
480             String JavaDoc msg = intres.getLocalizedMessage("ra.approvalad");
481             throw new WaitingForApprovalException(msg);
482         }
483         
484         try {
485             UserDataLocal data1 = home.create(userdata.getUsername(), newpassword, dn, userdata.getCAId());
486             if (userdata.getSubjectAltName() != null)
487                 data1.setSubjectAltName(userdata.getSubjectAltName());
488
489             if (userdata.getEmail() != null)
490                 data1.setSubjectEmail(userdata.getEmail());
491
492             data1.setType(type);
493             data1.setEndEntityProfileId(userdata.getEndEntityProfileId());
494             data1.setCertificateProfileId(userdata.getCertificateProfileId());
495             data1.setTokenType(userdata.getTokenType());
496             data1.setHardTokenIssuerId(userdata.getHardTokenIssuerId());
497             data1.setExtendedInformation(userdata.getExtendedinformation());
498
499             if (clearpwd) {
500                 try {
501                     if (newpassword == null) {
502                         data1.setClearPassword("");
503                     } else {
504                         data1.setOpenPassword(newpassword);
505                     }
506                 } catch (java.security.NoSuchAlgorithmException JavaDoc nsae) {
507                     debug("NoSuchAlgorithmException while setting password for user " + userdata.getUsername());
508                     throw new EJBException JavaDoc(nsae);
509                 }
510             }
511             if ((type & SecConst.USER_SENDNOTIFICATION) != 0) {
512                 sendNotification(admin, profile, userdata.getUsername(), newpassword, dn, userdata.getEmail(), userdata.getCAId());
513             }
514             if ((type & SecConst.USER_PRINT) != 0) {
515                 print(admin,profile,userdata);
516             }
517             String JavaDoc msg = intres.getLocalizedMessage("ra.addedentity", userdata.getUsername());
518             logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_INFO_ADDEDENDENTITY, msg);
519
520         } catch (DuplicateKeyException JavaDoc e) {
521             String JavaDoc msg = intres.getLocalizedMessage("ra.errorentityexist", userdata.getUsername());
522             logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_ERROR_ADDEDENDENTITY, msg);
523             throw e;
524         } catch (Exception JavaDoc e) {
525             String JavaDoc msg = intres.getLocalizedMessage("ra.erroraddentity", userdata.getUsername());
526             logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_ERROR_ADDEDENDENTITY, msg, e);
527             error(msg, e);
528             throw new EJBException JavaDoc(e);
529         }
530
531         debug("<addUser(" + userdata.getUsername() + ", password, " + dn + ", " + userdata.getEmail() + ")");
532     } // addUser
533

534     /**
535      * Help method that checks the CA data config if specified action
536      * requires approvals and how many
537      * @param action one of CAInfo.REQ_APPROVAL_ constants
538      * @param caid of the ca to check
539      * @return 0 of no approvals is required othervise the number of approvals
540      */

541     private int getNumOfApprovalRequired(Admin admin,int action, int caid) {
542         CAInfo cainfo = caadminsession.getCAInfo(admin, caid);
543         return ApprovalExecutorUtil.getNumOfApprovalRequired(action, cainfo);
544     }
545
546     /**
547      * Changes data for a user in the database speciefied by username.
548      *
549      * Important, this method is old and shouldn't be used, user changeUser(..UserDataVO...) instead.
550      *
551      * @param username the unique username.
552      * @param password the password used for authentication.*
553      * @param subjectdn the DN the subject is given in his certificate.
554      * @param subjectaltname the Subject Alternative Name to be used.
555      * @param email the email of the subject or null.
556      * @param endentityprofileid the id number of the end entity profile bound to this user.
557      * @param certificateprofileid the id number of the certificate profile that should be generated for the user.
558      * @param type of user i.e administrator, keyrecoverable and/or sendnotification
559      * @param tokentype the type of token to be generated, one of SecConst.TOKEN constants
560      * @param hardwaretokenissuerid if token should be hard, the id of the hard token issuer, else 0.
561      * @param status the status of the user, from UserDataConstants.STATUS_X
562      * @param caid the id of the CA that should be used to issue the users certificate
563      *
564      * @throws AuthorizationDeniedException if administrator isn't authorized to add user
565      * @throws UserDoesntFullfillEndEntityProfile if data doesn't fullfil requirements of end entity profile
566      * @throws ApprovalException if an approval already is waiting for specified action
567      * @throws WaitingForApprovalException if approval is required and the action have been added in the approval queue.
568      * @throws EJBException if a communication or other error occurs.
569      * @ejb.interface-method
570      */

571     public void changeUser(Admin admin, String JavaDoc username, String JavaDoc password, String JavaDoc subjectdn, String JavaDoc subjectaltname, String JavaDoc email, boolean clearpwd, int endentityprofileid, int certificateprofileid,
572             int type, int tokentype, int hardwaretokenissuerid, int status, int caid)
573 throws AuthorizationDeniedException, UserDoesntFullfillEndEntityProfile, ApprovalException, WaitingForApprovalException {
574         UserDataVO userdata = new UserDataVO(username, subjectdn, caid, subjectaltname,
575                 email, status, type, endentityprofileid, certificateprofileid,
576                 null,null, tokentype, hardwaretokenissuerid, null);
577         
578         userdata.setPassword(password);
579         changeUser(admin, userdata, clearpwd);
580     }
581
582     private static final ApprovalOveradableClassName[] NONAPPROVABLECLASSNAMES_CHANGEUSER = {
583         new ApprovalOveradableClassName("org.ejbca.core.model.approval.approvalrequests.EditEndEntityApprovalRequest",null),
584         new ApprovalOveradableClassName("se.primeKey.cardPersonalization.ra.connection.ejbca.EjbcaConnection",null)
585     };
586
587     /**
588      * Implements IUserAdminSession::changeUser..
589      *
590      * @param admin the administrator performing the action
591      * @param userdata a UserDataVO object, timecreated and timemodified will not be used.
592      * @param clearpwd true if the password will be stored in clear form in the db, otherwise it is
593      * hashed.
594      *
595      * @throws AuthorizationDeniedException if administrator isn't authorized to add user
596      * @throws UserDoesntFullfillEndEntityProfile if data doesn't fullfil requirements of end entity profile
597      * @throws ApprovalException if an approval already is waiting for specified action
598      * @throws WaitingForApprovalException if approval is required and the action have been added in the approval queue.
599
600      * @ejb.interface-method
601      */

602     public void changeUser(Admin admin, UserDataVO userdata, boolean clearpwd)
603             throws AuthorizationDeniedException, UserDoesntFullfillEndEntityProfile, ApprovalException, WaitingForApprovalException {
604         // String used in SQL so strip it
605
String JavaDoc dn = CertTools.stringToBCDNString(userdata.getDN());
606         dn = StringTools.strip(dn);
607         String JavaDoc newpassword = userdata.getPassword();
608         int type = userdata.getType();
609         debug(">changeUser(" + userdata.getUsername() + ", " + dn + ", " + userdata.getEmail() + ")");
610         int oldstatus;
611         EndEntityProfile profile = raadminsession.getEndEntityProfile(admin, userdata.getEndEntityProfileId());
612
613         if (profile.useAutoGeneratedPasswd() && userdata.getPassword() != null) {
614             // special case used to signal regeneraton of password
615
newpassword = profile.getAutoGeneratedPasswd();
616         }
617
618         // Check if user fulfills it's profile.
619
if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
620             try {
621                 profile.doesUserFullfillEndEntityProfileWithoutPassword(userdata.getUsername(), dn, userdata.getSubjectAltName(), userdata.getExtendedinformation().getSubjectDirectoryAttributes(), userdata.getEmail(), userdata.getCertificateProfileId(),
622                         (type & SecConst.USER_ADMINISTRATOR) != 0, (type & SecConst.USER_KEYRECOVERABLE) != 0, (type & SecConst.USER_SENDNOTIFICATION) != 0,
623                         userdata.getTokenType(), userdata.getHardTokenIssuerId(), userdata.getCAId());
624             } catch (UserDoesntFullfillEndEntityProfile udfp) {
625                 String JavaDoc msg = intres.getLocalizedMessage("ra.errorfullfillprofile", new Integer JavaDoc(userdata.getEndEntityProfileId()), dn, udfp.getMessage());
626                 logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
627                 throw udfp;
628             }
629             // Check if administrator is authorized to edit user.
630
if (!authorizedToEndEntityProfile(admin, userdata.getEndEntityProfileId(), AvailableAccessRules.EDIT_RIGHTS)) {
631                 String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthprofile", new Integer JavaDoc(userdata.getEndEntityProfileId()));
632                 logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
633                 throw new AuthorizationDeniedException(msg);
634             }
635         }
636
637         // Check if administrator is authorized to edit user to CA.
638
if (!authorizedToCA(admin, userdata.getCAId())) {
639             String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthca", new Integer JavaDoc(userdata.getCAId()));
640             logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
641             throw new AuthorizationDeniedException(msg);
642         }
643         // Check if approvals is required.
644
int numOfApprovalsRequired = getNumOfApprovalRequired(admin, CAInfo.REQ_APPROVAL_ADDEDITENDENTITY, userdata.getCAId());
645         if (numOfApprovalsRequired > 0){
646             UserDataVO orguserdata;
647             try {
648                 orguserdata = findUser(admin, userdata.getUsername());
649             } catch (FinderException JavaDoc e) {
650                 String JavaDoc msg = intres.getLocalizedMessage("ra.errorentitynotexist", userdata.getUsername());
651                 throw new ApprovalException(msg);
652             }
653             EditEndEntityApprovalRequest ar = new EditEndEntityApprovalRequest(userdata, clearpwd, orguserdata, admin,null,numOfApprovalsRequired,userdata.getCAId(),userdata.getEndEntityProfileId());
654             if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_CHANGEUSER)){
655                 getApprovalSession().addApprovalRequest(admin, ar);
656                 String JavaDoc msg = intres.getLocalizedMessage("ra.approvaledit");
657                 throw new WaitingForApprovalException(msg);
658             }
659
660         }
661         
662         
663         try {
664             UserDataPK pk = new UserDataPK(userdata.getUsername());
665             UserDataLocal data1 = home.findByPrimaryKey(pk);
666             data1.setDN(dn);
667             if (userdata.getSubjectAltName() != null)
668                 data1.setSubjectAltName(userdata.getSubjectAltName());
669             if (userdata.getEmail() != null)
670                 data1.setSubjectEmail(userdata.getEmail());
671             data1.setCaId(userdata.getCAId());
672             data1.setType(type);
673             data1.setEndEntityProfileId(userdata.getEndEntityProfileId());
674             data1.setCertificateProfileId(userdata.getCertificateProfileId());
675             data1.setTokenType(userdata.getTokenType());
676             data1.setHardTokenIssuerId(userdata.getHardTokenIssuerId());
677             data1.setExtendedInformation(userdata.getExtendedinformation());
678             oldstatus = data1.getStatus();
679             if(oldstatus == UserDataConstants.STATUS_KEYRECOVERY && !(userdata.getStatus() == UserDataConstants.STATUS_KEYRECOVERY || userdata.getStatus() == UserDataConstants.STATUS_INPROCESS)){
680               getKeyRecoverySession().unmarkUser(admin,userdata.getUsername());
681             }
682             data1.setStatus(userdata.getStatus());
683             data1.setTimeModified((new java.util.Date JavaDoc()).getTime());
684
685             if(newpassword != null){
686                 if(clearpwd) {
687                     try {
688                         data1.setOpenPassword(newpassword);
689                     } catch (java.security.NoSuchAlgorithmException JavaDoc nsae) {
690                         debug("NoSuchAlgorithmException while setting password for user "+userdata.getUsername());
691                         throw new EJBException JavaDoc(nsae);
692                     }
693                 } else {
694                     data1.setPassword(newpassword);
695                 }
696             }
697
698             boolean statuschanged = userdata.getStatus() != oldstatus;
699             // Send notification fi it should be sent. Should only be sent if new status is NEW, KEYRECOVERY or INITIALIZED, you don't send a notification to a user that has no use of the password
700
if ((type & SecConst.USER_SENDNOTIFICATION) != 0 && (userdata.getStatus() == UserDataConstants.STATUS_NEW || userdata.getStatus() == UserDataConstants.STATUS_KEYRECOVERY || userdata.getStatus() == UserDataConstants.STATUS_INITIALIZED)) {
701
702                 sendNotification(admin, profile, userdata.getUsername(), newpassword, dn, userdata.getEmail(), userdata.getCAId());
703             }
704             // Only print stuff on a printer on the same conditions as for notifications, we also only print if the status changes, not for every time we press save
705
if ((type & SecConst.USER_PRINT) != 0 && statuschanged && (userdata.getStatus() == UserDataConstants.STATUS_NEW || userdata.getStatus() == UserDataConstants.STATUS_KEYRECOVERY || userdata.getStatus() == UserDataConstants.STATUS_INITIALIZED)) {
706                 print(admin,profile,userdata);
707             }
708             if (statuschanged) {
709                 String JavaDoc msg = intres.getLocalizedMessage("ra.editedentitystatus", userdata.getUsername(), new Integer JavaDoc(userdata.getStatus()));
710                 logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_INFO_CHANGEDENDENTITY, msg );
711             } else {
712                 String JavaDoc msg = intres.getLocalizedMessage("ra.editedentity", userdata.getUsername());
713                 logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_INFO_CHANGEDENDENTITY, msg);
714             }
715         } catch (Exception JavaDoc e) {
716             String JavaDoc msg = intres.getLocalizedMessage("ra.erroreditentity", userdata.getUsername());
717             logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), userdata.getUsername(), null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
718             error("ChangeUser:", e);
719             throw new EJBException JavaDoc(e);
720         }
721         debug("<changeUser(" + userdata.getUsername() + ", password, " + dn + ", " + userdata.getEmail() + ")");
722     } // changeUser
723

724
725     /**
726      * Deletes a user from the database. The users certificates must be revoked BEFORE this method is called.
727      *
728      * @param username the unique username.
729      * @throws NotFoundException if the user does not exist
730      * @throws RemoveException if the user could not be removed
731      * @ejb.interface-method
732      */

733     public void deleteUser(Admin admin, String JavaDoc username) throws AuthorizationDeniedException, NotFoundException JavaDoc, RemoveException JavaDoc {
734         debug(">deleteUser(" + username + ")");
735         // Check if administrator is authorized to delete user.
736
int caid = LogConstants.INTERNALCAID;
737         try {
738             UserDataPK pk = new UserDataPK(username);
739             UserDataLocal data1 = home.findByPrimaryKey(pk);
740             caid = data1.getCaId();
741
742             if (!authorizedToCA(admin, caid)) {
743                 String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthca", new Integer JavaDoc(caid));
744                 logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_DELETEENDENTITY, msg);
745                 throw new AuthorizationDeniedException(msg);
746             }
747
748             if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
749                 if (!authorizedToEndEntityProfile(admin, data1.getEndEntityProfileId(), AvailableAccessRules.DELETE_RIGHTS)) {
750                     String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthprofile", new Integer JavaDoc(data1.getEndEntityProfileId()));
751                     logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_DELETEENDENTITY, msg);
752                     throw new AuthorizationDeniedException(msg);
753                 }
754             }
755         } catch (FinderException JavaDoc e) {
756             String JavaDoc msg = intres.getLocalizedMessage("ra.errorentitynotexist", username);
757             logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_DELETEENDENTITY, msg);
758             throw new NotFoundException JavaDoc(msg);
759         }
760         try {
761             UserDataPK pk = new UserDataPK(username);
762             home.remove(pk);
763             String JavaDoc msg = intres.getLocalizedMessage("ra.removedentity", username);
764             logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_INFO_DELETEDENDENTITY, msg);
765         } catch (EJBException JavaDoc e) {
766             String JavaDoc msg = intres.getLocalizedMessage("ra.errorremoveentity", username);
767             logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_DELETEENDENTITY, msg);
768             throw new RemoveException JavaDoc(msg);
769         }
770         debug("<deleteUser(" + username + ")");
771     } // deleteUser
772

773     private static final ApprovalOveradableClassName[] NONAPPROVABLECLASSNAMES_SETUSERSTATUS = {
774         new ApprovalOveradableClassName("org.ejbca.core.model.approval.approvalrequests.ChangeStatusEndEntityApprovalRequest",null),
775         new ApprovalOveradableClassName("org.ejbca.core.ejb.ra.LocalUserAdminSessionBean","revokeUser"),
776         new ApprovalOveradableClassName("org.ejbca.core.ejb.ra.LocalUserAdminSessionBean","revokeCert"),
777         new ApprovalOveradableClassName("org.ejbca.ui.web.admin.rainterface.RAInterfaceBean","unrevokeCert"),
778         new ApprovalOveradableClassName("org.ejbca.ui.web.admin.rainterface.RAInterfaceBean","markForRecovery"),
779         new ApprovalOveradableClassName("org.ejbca.extra.caservice.ExtRACAProcess","processExtRARevocationRequest"),
780         new ApprovalOveradableClassName("se.primeKey.cardPersonalization.ra.connection.ejbca.EjbcaConnection",null)
781     };
782     
783     /**
784      * Changes status of a user.
785      *
786      * @param username the unique username.
787      * @param status the new status, from 'UserData'.
788      * @param approvalflag approvalflag that indicates if approvals should be used or not
789      * @throws ApprovalException if an approval already is waiting for specified action
790      * @throws WaitingForApprovalException if approval is required and the action have been added in the approval queue.
791      * @ejb.interface-method
792      */

793     public void setUserStatus(Admin admin, String JavaDoc username, int status) throws AuthorizationDeniedException, FinderException JavaDoc, ApprovalException, WaitingForApprovalException {
794         debug(">setUserStatus(" + username + ", " + status + ")");
795         // Check if administrator is authorized to edit user.
796
int caid = LogConstants.INTERNALCAID;
797         try {
798             UserDataPK pk = new UserDataPK(username);
799             UserDataLocal data1 = home.findByPrimaryKey(pk);
800             caid = data1.getCaId();
801
802             if (!authorizedToCA(admin, caid)) {
803                 String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthca", new Integer JavaDoc(caid));
804                 logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
805                 throw new AuthorizationDeniedException(msg);
806             }
807
808
809             if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
810                 if (!authorizedToEndEntityProfile(admin, data1.getEndEntityProfileId(), AvailableAccessRules.EDIT_RIGHTS)) {
811                     String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthprofile", new Integer JavaDoc(data1.getEndEntityProfileId()));
812                     logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
813                     throw new AuthorizationDeniedException(msg);
814                 }
815             }
816             
817             // Check if approvals is required.
818
int numOfApprovalsRequired = getNumOfApprovalRequired(admin, CAInfo.REQ_APPROVAL_ADDEDITENDENTITY, caid);
819             ChangeStatusEndEntityApprovalRequest ar = new ChangeStatusEndEntityApprovalRequest(username, data1.getStatus(), status , admin,null,numOfApprovalsRequired,data1.getCaId(),data1.getEndEntityProfileId());
820             if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_SETUSERSTATUS)){
821                 getApprovalSession().addApprovalRequest(admin, ar);
822                 String JavaDoc msg = intres.getLocalizedMessage("ra.approvaledit");
823                 throw new WaitingForApprovalException(msg);
824             }
825             
826             if(data1.getStatus() == UserDataConstants.STATUS_KEYRECOVERY && !(status == UserDataConstants.STATUS_KEYRECOVERY || status == UserDataConstants.STATUS_INPROCESS || status == UserDataConstants.STATUS_INITIALIZED)){
827                 getKeyRecoverySession().unmarkUser(admin,username);
828             }
829             
830             data1.setStatus(status);
831             data1.setTimeModified((new java.util.Date JavaDoc()).getTime());
832             String JavaDoc msg = intres.getLocalizedMessage("ra.editedentitystatus", username, new Integer JavaDoc(status));
833             logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_INFO_CHANGEDENDENTITY, msg);
834         } catch (FinderException JavaDoc e) {
835             String JavaDoc msg = intres.getLocalizedMessage("ra.errorentitynotexist", username);
836             logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
837             throw e;
838         }
839
840         debug("<setUserStatus(" + username + ", " + status + ")");
841     } // setUserStatus
842

843
844     /**
845      * Sets a new password for a user.
846      *
847      * @param admin the administrator pwrforming the action
848      * @param username the unique username.
849      * @param password the new password for the user, NOT null.
850      * @ejb.interface-method
851      */

852     public void setPassword(Admin admin, String JavaDoc username, String JavaDoc password) throws UserDoesntFullfillEndEntityProfile, AuthorizationDeniedException, FinderException JavaDoc {
853         setPassword(admin, username, password, false);
854     } // setPassword
855

856     /**
857      * Sets a clear text password for a user.
858      *
859      * @param admin the administrator pwrforming the action
860      * @param username the unique username.
861      * @param password the new password to be stored in clear text. Setting password to 'null'
862      * effectively deletes any previous clear text password.
863      * @ejb.interface-method
864      */

865     public void setClearTextPassword(Admin admin, String JavaDoc username, String JavaDoc password) throws UserDoesntFullfillEndEntityProfile, AuthorizationDeniedException, FinderException JavaDoc {
866         setPassword(admin, username, password, true);
867     } // setClearTextPassword
868

869     /**
870      * Sets a password, hashed or clear text, for a user.
871      *
872      * @param admin the administrator pwrforming the action
873      * @param username the unique username.
874      * @param password the new password to be stored in clear text. Setting password to 'null'
875      * effectively deletes any previous clear text password.
876      * @param cleartext true gives cleartext password, false hashed
877      */

878     private void setPassword(Admin admin, String JavaDoc username, String JavaDoc password, boolean cleartext) throws UserDoesntFullfillEndEntityProfile, AuthorizationDeniedException, FinderException JavaDoc {
879         debug(">setPassword(" + username + ", hiddenpwd), " + cleartext);
880         // Find user
881
String JavaDoc newpasswd = password;
882         UserDataPK pk = new UserDataPK(username);
883         UserDataLocal data = home.findByPrimaryKey(pk);
884         int caid = data.getCaId();
885         String JavaDoc dn = data.getSubjectDN();
886
887         EndEntityProfile profile = raadminsession.getEndEntityProfile(admin, data.getEndEntityProfileId());
888
889         if (profile.useAutoGeneratedPasswd())
890             newpasswd = profile.getAutoGeneratedPasswd();
891
892         if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
893             // Check if user fulfills it's profile.
894
try {
895                 profile.doesPasswordFulfillEndEntityProfile(password, true);
896             } catch (UserDoesntFullfillEndEntityProfile ufe) {
897                 String JavaDoc msg = intres.getLocalizedMessage("ra.errorfullfillprofile", new Integer JavaDoc(data.getEndEntityProfileId()), dn, ufe.getMessage());
898                 logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
899                 throw ufe;
900             }
901
902             // Check if administrator is authorized to edit user.
903
if (!authorizedToEndEntityProfile(admin, data.getEndEntityProfileId(), AvailableAccessRules.EDIT_RIGHTS)) {
904                 String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthprofile", new Integer JavaDoc(data.getEndEntityProfileId()));
905                 logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
906                 throw new AuthorizationDeniedException(msg);
907             }
908         }
909
910         if (!authorizedToCA(admin, caid)) {
911             String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthca", new Integer JavaDoc(caid));
912             logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
913             throw new AuthorizationDeniedException(msg);
914         }
915
916         try {
917             if ((newpasswd == null) && (cleartext)) {
918                 data.setClearPassword("");
919                 data.setTimeModified((new java.util.Date JavaDoc()).getTime());
920             } else {
921                 if (cleartext) {
922                     data.setOpenPassword(newpasswd);
923                 } else {
924                     data.setPassword(newpasswd);
925                 }
926                 data.setTimeModified((new java.util.Date JavaDoc()).getTime());
927             }
928             String JavaDoc msg = intres.getLocalizedMessage("ra.editpwdentity", username);
929             logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_INFO_CHANGEDENDENTITY, msg);
930         } catch (java.security.NoSuchAlgorithmException JavaDoc nsae) {
931             error("NoSuchAlgorithmException while setting password for user " + username);
932             throw new EJBException JavaDoc(nsae);
933         }
934         debug("<setPassword(" + username + ", hiddenpwd), " + cleartext);
935     } // setPassword
936

937     /**
938      * Verifies a password for a user.
939      *
940      * @param admin the administrator pwrforming the action
941      * @param username the unique username.
942      * @param password the password to be verified.
943      * @ejb.interface-method
944      */

945     public boolean verifyPassword(Admin admin, String JavaDoc username, String JavaDoc password) throws UserDoesntFullfillEndEntityProfile, AuthorizationDeniedException, FinderException JavaDoc {
946         debug(">verifyPassword(" + username + ", hiddenpwd)");
947         boolean ret = false;
948         // Find user
949
UserDataPK pk = new UserDataPK(username);
950         UserDataLocal data = home.findByPrimaryKey(pk);
951         int caid = data.getCaId();
952
953         if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
954             // Check if administrator is authorized to edit user.
955
if (!authorizedToEndEntityProfile(admin, data.getEndEntityProfileId(), AvailableAccessRules.EDIT_RIGHTS)) {
956                 String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthprofile", new Integer JavaDoc(data.getEndEntityProfileId()));
957                 logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
958                 throw new AuthorizationDeniedException(msg);
959             }
960         }
961
962         if (!authorizedToCA(admin, caid)) {
963             String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthca", new Integer JavaDoc(caid));
964             logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_CHANGEDENDENTITY, msg);
965             throw new AuthorizationDeniedException(msg);
966         }
967
968         try {
969             ret = data.comparePassword(password);
970         } catch (java.security.NoSuchAlgorithmException JavaDoc nsae) {
971             debug("NoSuchAlgorithmException while verifying password for user " + username);
972             throw new EJBException JavaDoc(nsae);
973         }
974         debug("<verifyPassword(" + username + ", hiddenpwd)");
975         return ret;
976     } // verifyPassword
977

978     /**
979      * Method that revokes a user.
980      *
981      * @param username the username to revoke.
982      * @ejb.interface-method
983      */

984     public void revokeUser(Admin admin, String JavaDoc username, int reason) throws AuthorizationDeniedException, FinderException JavaDoc {
985         debug(">revokeUser(" + username + ")");
986         UserDataPK pk = new UserDataPK(username);
987         UserDataLocal data;
988         try {
989             data = home.findByPrimaryKey(pk);
990         } catch (ObjectNotFoundException JavaDoc oe) {
991             throw new EJBException JavaDoc(oe);
992         }
993
994         int caid = data.getCaId();
995         if (!authorizedToCA(admin, caid)) {
996             String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthca", new Integer JavaDoc(caid));
997             logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_REVOKEDENDENTITY, msg);
998             throw new AuthorizationDeniedException(msg);
999         }
1000
1001        if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
1002            if (!authorizedToEndEntityProfile(admin, data.getEndEntityProfileId(), AvailableAccessRules.REVOKE_RIGHTS)) {
1003                String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthprofile", new Integer JavaDoc(data.getEndEntityProfileId()));
1004                logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_REVOKEDENDENTITY, msg);
1005                throw new AuthorizationDeniedException(msg);
1006            }
1007        }
1008
1009        CertificateProfile prof = this.certificatesession.getCertificateProfile(admin, data.getCertificateProfileId());
1010        Collection JavaDoc publishers;
1011        if (prof == null) {
1012            publishers = new ArrayList JavaDoc();
1013        } else {
1014            publishers = prof.getPublisherList();
1015        }
1016        String JavaDoc actionMessage = "ra.revokedentity";
1017        try {
1018            if ( reason == RevokedCertInfo.NOT_REVOKED ) {
1019                setUserStatus(admin, username, UserDataConstants.STATUS_GENERATED);
1020                actionMessage = "ra.unrevokedentity";
1021            } else {
1022                setUserStatus(admin, username, UserDataConstants.STATUS_REVOKED);
1023            }
1024        } catch (ApprovalException e) {
1025            throw new EJBException JavaDoc("This should never happen",e);
1026        } catch (WaitingForApprovalException e) {
1027            throw new EJBException JavaDoc("This should never happen",e);
1028        }
1029        certificatesession.setRevokeStatus(admin, username, publishers, reason); // Revoke/unrevoke all possible user certificates
1030
String JavaDoc msg = intres.getLocalizedMessage(actionMessage, username);
1031        logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_INFO_REVOKEDENDENTITY, msg);
1032        debug("<revokeUser()");
1033    } // revokeUser
1034

1035    /**
1036     * Method that revokes a certificate.
1037     *
1038     * @param admin the adminsitrator performing the action
1039     * @param certserno the serno of certificate to revoke.
1040     * @param username the username to revoke.
1041     * @param reason the reason of revokation, one of the RevokedCertInfo.XX constants.
1042     * @ejb.interface-method
1043     */

1044    public void revokeCert(Admin admin, BigInteger JavaDoc certserno, String JavaDoc issuerdn, String JavaDoc username, int reason) throws AuthorizationDeniedException, FinderException JavaDoc {
1045        debug(">revokeCert(" + certserno + ", IssuerDN: " + issuerdn + ", username, " + username + ")");
1046        UserDataPK pk = new UserDataPK(username);
1047        UserDataLocal data;
1048        try {
1049            data = home.findByPrimaryKey(pk);
1050        } catch (ObjectNotFoundException JavaDoc oe) {
1051            throw new FinderException JavaDoc(oe.getMessage()+": username");
1052        }
1053        // Check that the user have revokation rigths.
1054
authorizationsession.isAuthorizedNoLog(admin, AvailableAccessRules.REGULAR_REVOKEENDENTITY);
1055
1056        int caid = data.getCaId();
1057        if (!authorizedToCA(admin, caid)) {
1058            String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthca", new Integer JavaDoc(caid));
1059            logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_REVOKEDENDENTITY, msg);
1060            throw new AuthorizationDeniedException(msg);
1061        }
1062
1063        if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
1064            if (!authorizedToEndEntityProfile(admin, data.getEndEntityProfileId(), AvailableAccessRules.REVOKE_RIGHTS)) {
1065                String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthprofile", new Integer JavaDoc(data.getEndEntityProfileId()));
1066                logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_REVOKEDENDENTITY, msg);
1067                throw new AuthorizationDeniedException(msg);
1068            }
1069        }
1070        // Check that unrevocation is not done on anything that can not be unrevoked
1071
if (reason == RevokedCertInfo.NOT_REVOKED) {
1072            RevokedCertInfo revinfo = certificatesession.isRevoked(admin, issuerdn, certserno);
1073            if ( (revinfo == null) || (revinfo != null && revinfo.getReason() != RevokedCertInfo.REVOKATION_REASON_CERTIFICATEHOLD) ) {
1074                String JavaDoc msg = intres.getLocalizedMessage("ra.errorunrevokenotonhold", issuerdn, certserno.toString(16));
1075                logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_ERROR_REVOKEDENDENTITY, msg);
1076                throw new AuthorizationDeniedException(msg);
1077            }
1078        }
1079        CertificateProfile prof = this.certificatesession.getCertificateProfile(admin, data.getCertificateProfileId());
1080        Collection JavaDoc publishers;
1081        if (prof == null) {
1082            publishers = new ArrayList JavaDoc();
1083        } else {
1084            publishers = prof.getPublisherList();
1085        }
1086        // revoke certificate in database and all publishers
1087
certificatesession.setRevokeStatus(admin, issuerdn, certserno, publishers, reason);
1088        
1089        // Reset the revocation code identifier used in XKMS
1090
ExtendedInformation inf = data.getExtendedInformation();
1091        if (inf != null) {
1092            inf.setRevocationCodeIdentifier(null);
1093        }
1094        
1095        if (certificatesession.checkIfAllRevoked(admin, username)) {
1096            try {
1097                setUserStatus(admin, username, UserDataConstants.STATUS_REVOKED);
1098            } catch (ApprovalException e) {
1099                throw new EJBException JavaDoc("This should never happen",e);
1100            } catch (WaitingForApprovalException e) {
1101                throw new EJBException JavaDoc("This should never happen",e);
1102            }
1103            String JavaDoc msg = intres.getLocalizedMessage("ra.revokedentitycert", issuerdn, certserno.toString(16));
1104            logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_INFO_REVOKEDENDENTITY, msg);
1105        } else if (reason == RevokedCertInfo.NOT_REVOKED) {
1106            // Don't change status if it is already the same
1107
if (data.getStatus() != UserDataConstants.STATUS_GENERATED) {
1108                try {
1109                    setUserStatus(admin, username, UserDataConstants.STATUS_GENERATED);
1110                } catch (ApprovalException e) {
1111                    throw new EJBException JavaDoc("This should never happen",e);
1112                } catch (WaitingForApprovalException e) {
1113                    throw new EJBException JavaDoc("This should never happen",e);
1114                }
1115            }
1116        }
1117        debug("<revokeCert()");
1118    } // revokeCert
1119

1120    /**
1121     * Reactivates the certificate with certificate serno.
1122     *
1123     * @param admin the adminsitrator performing the action
1124     * @param certserno serial number of certificate to reactivate.
1125     * @param issuerdn the issuerdn of certificate to reactivate.
1126     * @param username the username joined to the certificate.
1127     * @ejb.interface-method
1128     */

1129    public void unRevokeCert(Admin admin, BigInteger JavaDoc certserno, String JavaDoc issuerdn, String JavaDoc username) throws AuthorizationDeniedException, FinderException JavaDoc {
1130        log.debug(">unrevokeCert()");
1131        revokeCert(admin, certserno, issuerdn, username, RevokedCertInfo.NOT_REVOKED);
1132        log.debug("<unrevokeCert()");
1133    }
1134    
1135    /**
1136     * Finds a user.
1137     *
1138     * @param admin the administrator performing the action
1139     * @param username username.
1140     * @return UserDataVO or null if the user is not found.
1141     * @ejb.interface-method
1142     * @ejb.transaction type="Supports"
1143     */

1144    public UserDataVO findUser(Admin admin, String JavaDoc username) throws FinderException JavaDoc, AuthorizationDeniedException {
1145        debug(">findUser(" + username + ")");
1146        UserDataPK pk = new UserDataPK(username);
1147        UserDataLocal data;
1148        try {
1149            data = home.findByPrimaryKey(pk);
1150        } catch (ObjectNotFoundException JavaDoc oe) {
1151            return null;
1152        }
1153
1154        if (!authorizedToCA(admin, data.getCaId())) {
1155            String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthca", new Integer JavaDoc(data.getCaId()));
1156            throw new AuthorizationDeniedException(msg);
1157        }
1158
1159        if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
1160            // Check if administrator is authorized to view user.
1161
if (!authorizedToEndEntityProfile(admin, data.getEndEntityProfileId(), AvailableAccessRules.VIEW_RIGHTS)){
1162                String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthprofile", new Integer JavaDoc(data.getEndEntityProfileId()));
1163                throw new AuthorizationDeniedException(msg);
1164            }
1165        }
1166
1167        UserDataVO ret = new UserDataVO(data.getUsername(), data.getSubjectDN(), data.getCaId(), data.getSubjectAltName(), data.getSubjectEmail(), data.getStatus()
1168                , data.getType(), data.getEndEntityProfileId(), data.getCertificateProfileId()
1169                , new java.util.Date JavaDoc(data.getTimeCreated()), new java.util.Date JavaDoc(data.getTimeModified())
1170                , data.getTokenType(), data.getHardTokenIssuerId(), data.getExtendedInformation());
1171        ret.setPassword(data.getClearPassword());
1172        debug("<findUser(" + username + ")");
1173        return ret;
1174    } // findUser
1175

1176    /**
1177     * Finds a user by its subject and issuer DN.
1178     *
1179     * @param admin
1180     * @param subjectdn
1181     * @param issuerdn
1182     * @return UserDataVO or null if the user is not found.
1183     * @ejb.interface-method
1184     * @ejb.transaction type="Supports"
1185     */

1186    public UserDataVO findUserBySubjectAndIssuerDN(Admin admin, String JavaDoc subjectdn, String JavaDoc issuerdn) throws AuthorizationDeniedException {
1187        debug(">findUserBySubjectAndIssuerDN(" + subjectdn + ", "+issuerdn+")");
1188        String JavaDoc bcdn = CertTools.stringToBCDNString(subjectdn);
1189        // String used in SQL so strip it
1190
String JavaDoc dn = StringTools.strip(bcdn);
1191        debug("Looking for users with subjectdn: " + dn + ", issuerdn : " + issuerdn);
1192        UserDataVO returnval = null;
1193
1194        UserDataLocal data = null;
1195
1196        try {
1197            data = home.findBySubjectDNAndCAId(dn, issuerdn.hashCode());
1198        } catch (FinderException JavaDoc e) {
1199            log.debug("Cannot find user with DN='" + dn + "'");
1200        }
1201        returnval = returnUserDataVO(admin, returnval, data);
1202        debug("<findUserBySubjectAndIssuerDN(" + subjectdn + ", "+issuerdn+")");
1203        return returnval;
1204    } // findUserBySubjectDN
1205

1206    /**
1207     * Finds a user by its subject DN.
1208     *
1209     * @param admin
1210     * @param subjectdn
1211     * @return UserDataVO or null if the user is not found.
1212     * @ejb.interface-method
1213     * @ejb.transaction type="Supports"
1214     */

1215    public UserDataVO findUserBySubjectDN(Admin admin, String JavaDoc subjectdn) throws AuthorizationDeniedException {
1216        debug(">findUserBySubjectDN(" + subjectdn + ")");
1217        String JavaDoc bcdn = CertTools.stringToBCDNString(subjectdn);
1218        // String used in SQL so strip it
1219
String JavaDoc dn = StringTools.strip(bcdn);
1220        debug("Looking for users with subjectdn: " + dn);
1221        UserDataVO returnval = null;
1222
1223        UserDataLocal data = null;
1224
1225        try {
1226            data = home.findBySubjectDN(dn);
1227        } catch (FinderException JavaDoc e) {
1228            log.debug("Cannot find user with DN='" + dn + "'");
1229        }
1230        returnval = returnUserDataVO(admin, returnval, data);
1231        debug("<findUserBySubjectDN(" + subjectdn + ")");
1232        return returnval;
1233    } // findUserBySubjectDN
1234

1235    private UserDataVO returnUserDataVO(Admin admin, UserDataVO returnval, UserDataLocal data) throws AuthorizationDeniedException {
1236        if (data != null) {
1237            if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
1238                // Check if administrator is authorized to view user.
1239
if (!authorizedToEndEntityProfile(admin, data.getEndEntityProfileId(), AvailableAccessRules.VIEW_RIGHTS)) {
1240                    String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthprofile", new Integer JavaDoc(data.getEndEntityProfileId()));
1241                    throw new AuthorizationDeniedException(msg);
1242                }
1243            }
1244
1245            if (!authorizedToCA(admin, data.getCaId())) {
1246                String JavaDoc msg = intres.getLocalizedMessage("ra.errorauthca", new Integer JavaDoc(data.getCaId()));
1247                throw new AuthorizationDeniedException(msg);
1248            }
1249
1250            returnval = new UserDataVO(data.getUsername(), data.getSubjectDN(), data.getCaId(), data.getSubjectAltName(), data.getSubjectEmail(), data.getStatus()
1251                    , data.getType(), data.getEndEntityProfileId(), data.getCertificateProfileId()
1252                    , new java.util.Date JavaDoc(data.getTimeCreated()), new java.util.Date JavaDoc(data.getTimeModified())
1253                    , data.getTokenType(), data.getHardTokenIssuerId(), data.getExtendedInformation());
1254
1255            returnval.setPassword(data.getClearPassword());
1256        }
1257        return returnval;
1258    }
1259
1260    /**
1261     * Finds a user by its Email.
1262     *
1263     * @param email
1264     * @return UserDataVO or null if the user is not found.
1265     * @ejb.interface-method
1266     * @ejb.transaction type="Supports"
1267     */

1268    public Collection JavaDoc findUserByEmail(Admin admin, String JavaDoc email) throws AuthorizationDeniedException {
1269        debug(">findUserByEmail(" + email + ")");
1270        debug("Looking for user with email: " + email);
1271        ArrayList JavaDoc returnval = new ArrayList JavaDoc();
1272
1273        Collection JavaDoc result = null;
1274        try {
1275            result = home.findBySubjectEmail(email);
1276        } catch (FinderException JavaDoc e) {
1277            log.debug("Cannot find user with Email='" + email + "'");
1278        }
1279
1280        Iterator JavaDoc iter = result.iterator();
1281        while (iter.hasNext()) {
1282            UserDataLocal data = (UserDataLocal) iter.next();
1283
1284            if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
1285                // Check if administrator is authorized to view user.
1286
if (!authorizedToEndEntityProfile(admin, data.getEndEntityProfileId(), AvailableAccessRules.VIEW_RIGHTS))
1287                    break;
1288            }
1289
1290            if (!authorizedToCA(admin, data.getCaId())) {
1291                break;
1292            }
1293
1294            UserDataVO user = new UserDataVO(data.getUsername(), data.getSubjectDN(), data.getCaId(), data.getSubjectAltName(), data.getSubjectEmail(), data.getStatus()
1295                    , data.getType(), data.getEndEntityProfileId(), data.getCertificateProfileId()
1296                    , new java.util.Date JavaDoc(data.getTimeCreated()), new java.util.Date JavaDoc(data.getTimeModified())
1297                    , data.getTokenType(), data.getHardTokenIssuerId(), data.getExtendedInformation());
1298            user.setPassword(data.getClearPassword());
1299            returnval.add(user);
1300        }
1301        debug("<findUserByEmail(" + email + ")");
1302        return returnval;
1303    } // findUserBySubjectDN
1304

1305    /**
1306     * Method that checks if user with specified users certificate exists in database and is set as administrator.
1307     *
1308     * @param subjectdn
1309     * @throws AuthorizationDeniedException if user isn't an administrator.
1310     * @ejb.interface-method
1311     * @ejb.transaction type="Supports"
1312     */

1313    public void checkIfCertificateBelongToAdmin(Admin admin, BigInteger JavaDoc certificatesnr, String JavaDoc issuerdn) throws AuthorizationDeniedException {
1314        debug(">checkIfCertificateBelongToAdmin(" + certificatesnr + ")");
1315        String JavaDoc username = certificatesession.findUsernameByCertSerno(admin, certificatesnr, issuerdn);
1316
1317        UserDataLocal data = null;
1318        if (username != null) {
1319            UserDataPK pk = new UserDataPK(username);
1320            try {
1321                data = home.findByPrimaryKey(pk);
1322            } catch (FinderException JavaDoc e) {
1323                log.debug("Cannot find user with username='" + username + "'");
1324            }
1325        }
1326
1327        if (data != null) {
1328            int type = data.getType();
1329            if ((type & SecConst.USER_ADMINISTRATOR) == 0) {
1330                String JavaDoc msg = intres.getLocalizedMessage("ra.errorcertnoadmin", issuerdn, certificatesnr.toString(16));
1331                logsession.log(admin, data.getCaId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_ADMINISTRATORLOGGEDIN, msg);
1332                throw new AuthorizationDeniedException(msg);
1333            }
1334        } else {
1335            String JavaDoc msg = intres.getLocalizedMessage("ra.errorcertnouser", issuerdn, certificatesnr.toString(16));
1336            logsession.log(admin, LogConstants.INTERNALCAID, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_ADMINISTRATORLOGGEDIN, msg);
1337            throw new AuthorizationDeniedException(msg);
1338        }
1339
1340        debug("<checkIfCertificateBelongToAdmin()");
1341    } // checkIfCertificateBelongToAdmin
1342

1343
1344    /**
1345     * Finds all users with a specified status.
1346     *
1347     * @param status the status to look for, from 'UserData'.
1348     * @return Collection of UserDataVO
1349     * @ejb.interface-method
1350     * @ejb.transaction type="Supports"
1351     */

1352    public Collection JavaDoc findAllUsersByStatus(Admin admin, int status) throws FinderException JavaDoc {
1353        debug(">findAllUsersByStatus(" + status + ")");
1354        debug("Looking for users with status: " + status);
1355
1356        Query query = new Query(Query.TYPE_USERQUERY);
1357        query.add(UserMatch.MATCH_WITH_STATUS, BasicMatch.MATCH_TYPE_EQUALS, Integer.toString(status));
1358        Collection JavaDoc returnval = null;
1359
1360        try {
1361            returnval = query(admin, query, false, null, null, false,0);
1362        } catch (IllegalQueryException e) {
1363        }
1364        debug("found " + returnval.size() + " user(s) with status=" + status);
1365        debug("<findAllUsersByStatus(" + status + ")");
1366        return returnval;
1367    }
1368    /**
1369     * Finds all users registered to a specified ca.
1370     *
1371     * @param caid the caid of the CA, from 'UserData'.
1372     * @return Collection of UserDataVO
1373     * @ejb.interface-method
1374     * @ejb.transaction type="Supports"
1375     */

1376     public Collection JavaDoc findAllUsersByCaId(Admin admin, int caid) throws FinderException JavaDoc {
1377         debug(">findAllUsersByCaId("+caid+")");
1378         debug("Looking for users with caid: " + caid);
1379         
1380         Query query = new Query(Query.TYPE_USERQUERY);
1381         query.add(UserMatch.MATCH_WITH_CA, BasicMatch.MATCH_TYPE_EQUALS, Integer.toString(caid));
1382         Collection JavaDoc returnval = null;
1383         
1384         try{
1385           returnval = query(admin, query, false, null, null, false,0);
1386         }catch(IllegalQueryException e){}
1387         debug("found "+returnval.size()+" user(s) with caid="+caid);
1388         debug("<findAllUsersByCaId("+caid+")");
1389         return returnval;
1390     }
1391
1392
1393    /**
1394     * Finds all users and returns the first MAXIMUM_QUERY_ROWCOUNT.
1395     *
1396     * @return Collection of UserDataVO
1397     * @ejb.interface-method
1398     * @ejb.transaction type="Supports"
1399     */

1400    public Collection JavaDoc findAllUsersWithLimit(Admin admin) throws FinderException JavaDoc {
1401        debug(">findAllUsersWithLimit()");
1402        Collection JavaDoc returnval = null;
1403        try {
1404            returnval = query(admin, null, true, null, null, false, 0);
1405        } catch (IllegalQueryException e) {
1406        }
1407        debug("<findAllUsersWithLimit()");
1408        return returnval;
1409    }
1410
1411    /**
1412     * Finds all users with a specified status and returns the first MAXIMUM_QUERY_ROWCOUNT.
1413     *
1414     * @param status the new status, from 'UserData'.
1415     * @ejb.interface-method
1416     * @ejb.transaction type="Supports"
1417     */

1418    public Collection JavaDoc findAllUsersByStatusWithLimit(Admin admin, int status, boolean onlybatchusers) throws FinderException JavaDoc {
1419        debug(">findAllUsersByStatusWithLimit()");
1420
1421        Query query = new Query(Query.TYPE_USERQUERY);
1422        query.add(UserMatch.MATCH_WITH_STATUS, BasicMatch.MATCH_TYPE_EQUALS, Integer.toString(status));
1423        Collection JavaDoc returnval = null;
1424
1425        try {
1426            returnval = query(admin, query, false, null, null, onlybatchusers, 0);
1427        } catch (IllegalQueryException e) {
1428        }
1429
1430        debug("<findAllUsersByStatusWithLimit()");
1431        return returnval;
1432    }
1433
1434
1435    /**
1436     * Method to execute a customized query on the ra user data. The parameter query should be a legal Query object.
1437     *
1438     * @param query a number of statments compiled by query class to a SQL 'WHERE'-clause statment.
1439     * @param caauthorizationstring is a string placed in the where clause of SQL query indication which CA:s the administrator is authorized to view.
1440     * @param endentityprofilestring is a string placed in the where clause of SQL query indication which endentityprofiles the administrator is authorized to view.
1441     * @param numberofrows the number of rows to fetch, use 0 for default UserAdminConstants.MAXIMUM_QUERY_ROWCOUNT
1442     * @return a collection of UserDataVO. Maximum size of Collection is defined i IUserAdminSessionRemote.MAXIMUM_QUERY_ROWCOUNT
1443     * @throws IllegalQueryException when query parameters internal rules isn't fullfilled.
1444     * @ejb.interface-method
1445     * @ejb.transaction type="Supports"
1446     * @see se.anatom.ejbca.util.query.Query
1447     */

1448    public Collection JavaDoc query(Admin admin, Query query, String JavaDoc caauthorizationstring, String JavaDoc endentityprofilestring, int numberofrows) throws IllegalQueryException {
1449        return query(admin, query, true, caauthorizationstring, endentityprofilestring, false, numberofrows);
1450    }
1451
1452    /**
1453     * Help function used to retrieve user information. A query parameter of null indicates all users.
1454     * If caauthorizationstring or endentityprofilestring are null then the method will retrieve the information
1455     * itself.
1456     *
1457     * @param numberofrows the number of rows to fetch, use 0 for default UserAdminConstants.MAXIMUM_QUERY_ROWCOUNT
1458     */

1459    private Collection JavaDoc query(Admin admin, Query query, boolean withlimit, String JavaDoc caauthorizationstr, String JavaDoc endentityprofilestr, boolean onlybatchusers, int numberofrows) throws IllegalQueryException {
1460        debug(">query(): withlimit="+withlimit);
1461        boolean authorizedtoanyprofile = true;
1462        Connection JavaDoc con = null;
1463        PreparedStatement JavaDoc ps = null;
1464        ResultSet JavaDoc rs = null;
1465        String JavaDoc caauthorizationstring = StringTools.strip(caauthorizationstr);
1466        String JavaDoc endentityprofilestring = StringTools.strip(endentityprofilestr);
1467        ArrayList JavaDoc returnval = new ArrayList JavaDoc();
1468        GlobalConfiguration globalconfiguration = getGlobalConfiguration(admin);
1469        RAAuthorization raauthorization = null;
1470        String JavaDoc caauthstring = caauthorizationstring;
1471        String JavaDoc endentityauth = endentityprofilestring;
1472        String JavaDoc sqlquery = "select " + USERDATA_COL + " from UserData where ";
1473        int fetchsize = UserAdminConstants.MAXIMUM_QUERY_ROWCOUNT;
1474        
1475        if(numberofrows != 0){
1476            fetchsize = numberofrows;
1477        }
1478
1479
1480        // Check if query is legal.
1481
if (query != null && !query.isLegalQuery())
1482            throw new IllegalQueryException();
1483
1484        if (query != null)
1485            sqlquery = sqlquery + query.getQueryString();
1486
1487        if (caauthorizationstring == null || endentityprofilestring == null) {
1488            raauthorization = new RAAuthorization(admin, raadminsession, authorizationsession);
1489            caauthstring = raauthorization.getCAAuthorizationString();
1490            if (globalconfiguration.getEnableEndEntityProfileLimitations())
1491                endentityauth = raauthorization.getEndEntityProfileAuthorizationString(true);
1492            else
1493                endentityauth = "";
1494        }
1495
1496        if (!caauthstring.trim().equals("") && query != null)
1497            sqlquery = sqlquery + " AND " + caauthstring;
1498        else
1499            sqlquery = sqlquery + caauthstring;
1500
1501
1502        if (globalconfiguration.getEnableEndEntityProfileLimitations()) {
1503            if (caauthstring.trim().equals("") && query == null)
1504                sqlquery = sqlquery + endentityauth;
1505            else
1506                sqlquery = sqlquery + " AND " + endentityauth;
1507
1508            if (endentityauth == null || endentityauth.trim().equals("")) {
1509                authorizedtoanyprofile = false;
1510            }
1511        }
1512
1513        try {
1514            if (authorizedtoanyprofile) {
1515                // Construct SQL query.
1516
con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
1517                log.debug("generated query: " + sqlquery);
1518                ps = con.prepareStatement(sqlquery);
1519
1520                // Execute query.
1521
rs = ps.executeQuery();
1522
1523                // Assemble result.
1524
while (rs.next() && (!withlimit || returnval.size() <= fetchsize)) {
1525                    // Read the variables in order, some databases (i.e. MS-SQL)
1526
// seems to not like out-of-order read of columns (i.e. nr 15 before nr 1)
1527
String JavaDoc user = rs.getString(1);
1528                    String JavaDoc dn = rs.getString(2);
1529                    String JavaDoc subaltname = rs.getString(3);
1530                    String JavaDoc email = rs.getString(4);
1531                    int status = rs.getInt(5);
1532                    int type = rs.getInt(6);
1533                    String JavaDoc pwd = rs.getString(7);
1534                    Date JavaDoc timecreated = new java.util.Date JavaDoc(rs.getLong(8));
1535                    Date JavaDoc timemodified = new java.util.Date JavaDoc(rs.getLong(9));
1536                    int eprofileid = rs.getInt(10);
1537                    int cprofileid = rs.getInt(11);
1538                    int tokentype = rs.getInt(12);
1539                    int tokenissuerid = rs.getInt(13);
1540                    int caid = rs.getInt(14);
1541                    String JavaDoc extendedInformation = rs.getString(15);
1542                    UserDataVO data = new UserDataVO(user, dn, caid, subaltname, email, status, type
1543                            , eprofileid, cprofileid, timecreated, timemodified, tokentype, tokenissuerid,
1544                            UserDataVO.getExtendedInformation(extendedInformation));
1545                    data.setPassword(pwd);
1546
1547                    if (!onlybatchusers || (data.getPassword() != null && data.getPassword().length() > 0))
1548                        returnval.add(data);
1549                }
1550            }
1551            debug("<query()");
1552            return returnval;
1553
1554        } catch (Exception JavaDoc e) {
1555            throw new EJBException JavaDoc(e);
1556        } finally {
1557            JDBCUtil.close(con, ps, rs);
1558        }
1559
1560    } // query
1561

1562
1563    /**
1564     * Methods that checks if a user exists in the database having the given endentityprofileid. This function is mainly for avoiding
1565     * desyncronisation when a end entity profile is deleted.
1566     *
1567     * @param endentityprofileid the id of end entity profile to look for.
1568     * @return true if endentityprofileid exists in userdatabase.
1569     * @ejb.interface-method
1570     * @ejb.transaction type="Supports"
1571     */

1572    public boolean checkForEndEntityProfileId(Admin admin, int endentityprofileid) {
1573        debug(">checkForEndEntityProfileId()");
1574        Connection JavaDoc con = null;
1575        PreparedStatement JavaDoc ps = null;
1576        ResultSet JavaDoc rs = null;
1577        int count = 1; // return true as default.
1578

1579        Query query = new Query(Query.TYPE_USERQUERY);
1580        query.add(UserMatch.MATCH_WITH_ENDENTITYPROFILE, BasicMatch.MATCH_TYPE_EQUALS, Integer.toString(endentityprofileid));
1581
1582        try {
1583            // Construct SQL query.
1584
con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
1585            ps = con.prepareStatement("select COUNT(*) from UserData where " + query.getQueryString());
1586            // Execute query.
1587
rs = ps.executeQuery();
1588            // Assemble result.
1589
if (rs.next()) {
1590                count = rs.getInt(1);
1591            }
1592            debug("<checkForEndEntityProfileId()");
1593            return count > 0;
1594
1595        } catch (Exception JavaDoc e) {
1596            throw new EJBException JavaDoc(e);
1597        } finally {
1598            JDBCUtil.close(con, ps, rs);
1599        }
1600
1601
1602    }
1603
1604    /**
1605     * Methods that checks if a user exists in the database having the given certificateprofileid. This function is mainly for avoiding
1606     * desyncronisation when a certificateprofile is deleted.
1607     *
1608     * @param certificateprofileid the id of certificateprofile to look for.
1609     * @return true if certificateproileid exists in userdatabase.
1610     * @ejb.interface-method
1611     * @ejb.transaction type="Supports"
1612     */

1613    public boolean checkForCertificateProfileId(Admin admin, int certificateprofileid) {
1614        debug(">checkForCertificateProfileId()");
1615        Connection JavaDoc con = null;
1616        PreparedStatement JavaDoc ps = null;
1617        ResultSet JavaDoc rs = null;
1618        int count = 1; // return true as default.
1619

1620        Query query = new Query(Query.TYPE_USERQUERY);
1621        query.add(UserMatch.MATCH_WITH_CERTIFICATEPROFILE, BasicMatch.MATCH_TYPE_EQUALS, Integer.toString(certificateprofileid));
1622
1623        try {
1624            // Construct SQL query.
1625
con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
1626            ps = con.prepareStatement("select COUNT(*) from UserData where " + query.getQueryString());
1627            // Execute query.
1628
rs = ps.executeQuery();
1629            // Assemble result.
1630
if (rs.next()) {
1631                count = rs.getInt(1);
1632            }
1633            debug("<checkForCertificateProfileId()");
1634            return count > 0;
1635
1636        } catch (Exception JavaDoc e) {
1637            throw new EJBException JavaDoc(e);
1638        } finally {
1639            JDBCUtil.close(con, ps, rs);
1640        }
1641    } // checkForCertificateProfileId
1642

1643    /**
1644     * Methods that checks if a user exists in the database having the given caid. This function is mainly for avoiding
1645     * desyncronisation when a CAs is deleted.
1646     *
1647     * @param caid the id of CA to look for.
1648     * @return true if caid exists in userdatabase.
1649     * @ejb.interface-method
1650     * @ejb.transaction type="Supports"
1651     */

1652    public boolean checkForCAId(Admin admin, int caid) {
1653        debug(">checkForCAId()");
1654        Connection JavaDoc con = null;
1655        PreparedStatement JavaDoc ps = null;
1656        ResultSet JavaDoc rs = null;
1657        int count = 1; // return true as default.
1658

1659        Query query = new Query(Query.TYPE_USERQUERY);
1660        query.add(UserMatch.MATCH_WITH_CA, BasicMatch.MATCH_TYPE_EQUALS, Integer.toString(caid));
1661
1662        try {
1663            // Construct SQL query.
1664
con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
1665            ps = con.prepareStatement("select COUNT(*) from UserData where " + query.getQueryString());
1666            // Execute query.
1667
rs = ps.executeQuery();
1668            // Assemble result.
1669
if (rs.next()) {
1670                count = rs.getInt(1);
1671            }
1672            debug("<checkForCAId()");
1673            return count > 0;
1674
1675        } catch (Exception JavaDoc e) {
1676            throw new EJBException JavaDoc(e);
1677        } finally {
1678            JDBCUtil.close(con, ps, rs);
1679        }
1680    } // checkForCAId
1681

1682
1683    /**
1684     * Methods that checks if a user exists in the database having the given hard token profile id. This function is mainly for avoiding
1685     * desyncronisation when a hard token profile is deleted.
1686     *
1687     * @param profileid of hardtokenprofile to look for.
1688     * @return true if proileid exists in userdatabase.
1689     * @ejb.interface-method
1690     * @ejb.transaction type="Supports"
1691     */

1692    public boolean checkForHardTokenProfileId(Admin admin, int profileid) {
1693        debug(">checkForHardTokenProfileId()");
1694        Connection JavaDoc con = null;
1695        PreparedStatement JavaDoc ps = null;
1696        ResultSet JavaDoc rs = null;
1697        int count = 1; // return true as default.
1698

1699        Query query = new Query(Query.TYPE_USERQUERY);
1700        query.add(UserMatch.MATCH_WITH_TOKEN, BasicMatch.MATCH_TYPE_EQUALS, Integer.toString(profileid));
1701
1702        try {
1703            // Construct SQL query.
1704
con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
1705            ps = con.prepareStatement("select COUNT(*) from UserData where " + query.getQueryString());
1706            // Execute query.
1707
rs = ps.executeQuery();
1708            // Assemble result.
1709
if (rs.next()) {
1710                count = rs.getInt(1);
1711            }
1712            debug("<checkForHardTokenProfileId()");
1713            return count > 0;
1714
1715        } catch (Exception JavaDoc e) {
1716            throw new EJBException JavaDoc(e);
1717        } finally {
1718            JDBCUtil.close(con, ps, rs);
1719        }
1720    } // checkForHardTokenProfileId
1721

1722
1723    private void print(Admin admin, EndEntityProfile profile, UserDataVO userdata){
1724        try{
1725          if(profile.getUsePrinting()){
1726            String JavaDoc[] pINs = new String JavaDoc[1];
1727            pINs[0] = userdata.getPassword();
1728              PrinterManager.print(profile.getPrinterName(), profile.getPrinterSVGFileName(), profile.getPrinterSVGData(), profile.getPrintedCopies(), 0, userdata, pINs, new String JavaDoc[0], "", "", "");
1729          }
1730        }catch(PrinterException JavaDoc e){
1731            String JavaDoc msg = intres.getLocalizedMessage("ra.errorprint", userdata.getUsername(), e.getMessage());
1732            error(msg, e);
1733            try{
1734                logsession.log(admin, userdata.getCAId(), LogEntry.MODULE_RA, new java.util.Date JavaDoc(),userdata.getUsername(), null, LogEntry.EVENT_ERROR_NOTIFICATION, msg);
1735            }catch(Exception JavaDoc f){
1736                throw new EJBException JavaDoc(f);
1737            }
1738        }
1739    }
1740    
1741    private void sendNotification(Admin admin, EndEntityProfile profile, String JavaDoc username, String JavaDoc password, String JavaDoc dn, String JavaDoc email, int caid) {
1742        debug(">sendNotification: user="+username+", email="+email);
1743        try {
1744            if (email == null) {
1745                String JavaDoc msg = intres.getLocalizedMessage("ra.errornotificationnoemail", username);
1746                throw new Exception JavaDoc(msg);
1747            }
1748
1749            String JavaDoc mailJndi = getLocator().getString("java:comp/env/MailJNDIName");
1750            Session JavaDoc mailSession = getLocator().getMailSession(mailJndi);
1751            NotificationParamGen paramGen = new NotificationParamGen(username,password,dn);
1752            HashMap JavaDoc params = paramGen.getParams();
1753
1754            Message JavaDoc msg = new TemplateMimeMessage(params, mailSession);
1755            msg.setFrom(new InternetAddress JavaDoc(profile.getNotificationSender()));
1756            msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(email, false));
1757            msg.setSubject(profile.getNotificationSubject());
1758            msg.setContent(profile.getNotificationMessage(), "text/plain");
1759            msg.setHeader("X-Mailer", "JavaMailer");
1760            msg.setSentDate(new Date JavaDoc());
1761            Transport.send(msg);
1762
1763            logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(), username, null, LogEntry.EVENT_INFO_NOTIFICATION, intres.getLocalizedMessage("ra.sentnotification", username, email));
1764        } catch (Exception JavaDoc e) {
1765            String JavaDoc msg = intres.getLocalizedMessage("ra.errorsendnotification", username, email);
1766            error(msg, e);
1767            try{
1768                logsession.log(admin, caid, LogEntry.MODULE_RA, new java.util.Date JavaDoc(),username, null, LogEntry.EVENT_ERROR_NOTIFICATION, msg);
1769            }catch(Exception JavaDoc f){
1770                throw new EJBException JavaDoc(f);
1771            }
1772        }
1773        debug("<sendNotification: user="+username+", email="+email);
1774    } // sendNotification
1775

1776    /**
1777     * Method checking if username already exists in database.
1778     *
1779     * @return true if username already exists.
1780     * @ejb.interface-method
1781     * @ejb.transaction type="Supports"
1782     */

1783    public boolean existsUser(Admin admin, String JavaDoc username) {
1784        boolean returnval = true;
1785
1786        try {
1787            home.findByPrimaryKey(new UserDataPK(username));
1788        } catch (FinderException JavaDoc fe) {
1789            returnval = false;
1790        }
1791
1792        return returnval;
1793    }
1794
1795} // LocalUserAdminSessionBean
1796
Popular Tags