KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > ui > web > admin > rainterface > RAInterfaceBean


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.ui.web.admin.rainterface;
15
16 import java.math.BigInteger JavaDoc;
17 import java.rmi.RemoteException JavaDoc;
18 import java.security.cert.X509Certificate JavaDoc;
19 import java.util.ArrayList JavaDoc;
20 import java.util.Collection JavaDoc;
21 import java.util.Date JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.TreeMap JavaDoc;
24
25 import javax.ejb.CreateException JavaDoc;
26 import javax.ejb.FinderException JavaDoc;
27 import javax.naming.NamingException JavaDoc;
28 import javax.servlet.http.HttpServletRequest JavaDoc;
29
30 import org.apache.log4j.Logger;
31 import org.ejbca.core.ejb.ServiceLocator;
32 import org.ejbca.core.ejb.authorization.IAuthorizationSessionLocal;
33 import org.ejbca.core.ejb.authorization.IAuthorizationSessionLocalHome;
34 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocal;
35 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocalHome;
36 import org.ejbca.core.ejb.hardtoken.IHardTokenSessionLocal;
37 import org.ejbca.core.ejb.hardtoken.IHardTokenSessionLocalHome;
38 import org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionLocal;
39 import org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionLocalHome;
40 import org.ejbca.core.ejb.ra.IUserAdminSessionLocal;
41 import org.ejbca.core.ejb.ra.IUserAdminSessionLocalHome;
42 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionLocal;
43 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionLocalHome;
44 import org.ejbca.core.ejb.ra.userdatasource.IUserDataSourceSessionLocal;
45 import org.ejbca.core.ejb.ra.userdatasource.IUserDataSourceSessionLocalHome;
46 import org.ejbca.core.model.SecConst;
47 import org.ejbca.core.model.authorization.AuthorizationDeniedException;
48 import org.ejbca.core.model.authorization.AvailableAccessRules;
49 import org.ejbca.core.model.ca.certificateprofiles.CertificateProfile;
50 import org.ejbca.core.model.ca.crl.RevokedCertInfo;
51 import org.ejbca.core.model.log.Admin;
52 import org.ejbca.core.model.ra.UserDataConstants;
53 import org.ejbca.core.model.ra.UserDataVO;
54 import org.ejbca.core.model.ra.raadmin.EndEntityProfile;
55 import org.ejbca.ui.web.admin.configuration.EjbcaWebBean;
56 import org.ejbca.ui.web.admin.configuration.InformationMemory;
57 import org.ejbca.util.CertTools;
58 import org.ejbca.util.StringTools;
59 import org.ejbca.util.query.Query;
60
61
62
63 /**
64  * A java bean handling the interface between EJBCA ra module and JSP pages.
65  *
66  * @author Philip Vendil
67  * @version $Id: RAInterfaceBean.java,v 1.14 2006/09/27 09:28:27 herrvendil Exp $
68  */

69 public class RAInterfaceBean implements java.io.Serializable JavaDoc {
70     
71     private static Logger log = Logger.getLogger(RAInterfaceBean.class);
72     
73     // Public constants.
74
public static final int MAXIMUM_QUERY_ROWCOUNT = SecConst.MAXIMUM_QUERY_ROWCOUNT;
75     
76     public static final String JavaDoc[] tokentexts = SecConst.TOKENTEXTS;
77     public static final int[] tokenids = SecConst.TOKENIDS;
78     
79     /** Creates new RaInterfaceBean */
80     public RAInterfaceBean() {
81         users = new UsersView();
82         addedusermemory = new AddedUserMemory();
83     }
84     // Public methods.
85
public void initialize(HttpServletRequest JavaDoc request, EjbcaWebBean ejbcawebbean) throws Exception JavaDoc{
86       log.debug(">initialize()");
87
88       if(!initialized){
89         if(request.getAttribute( "javax.servlet.request.X509Certificate" ) != null)
90           administrator = new Admin(((X509Certificate JavaDoc[]) request.getAttribute( "javax.servlet.request.X509Certificate" ))[0]);
91         else
92           administrator = new Admin(Admin.TYPE_PUBLIC_WEB_USER, request.getRemoteAddr());
93         // Get the UserAdminSession instance.
94
this.informationmemory = ejbcawebbean.getInformationMemory();
95         
96         ServiceLocator locator = ServiceLocator.getInstance();
97         adminsessionhome = (IUserAdminSessionLocalHome) locator.getLocalHome(IUserAdminSessionLocalHome.COMP_NAME);
98         adminsession = adminsessionhome.create();
99
100         raadminsessionhome = (IRaAdminSessionLocalHome) locator.getLocalHome(IRaAdminSessionLocalHome.COMP_NAME);
101         raadminsession = raadminsessionhome.create();
102         
103
104         certificatesessionhome = (ICertificateStoreSessionLocalHome) locator.getLocalHome(ICertificateStoreSessionLocalHome.COMP_NAME);
105         certificatesession = certificatesessionhome.create();
106
107         IAuthorizationSessionLocalHome authorizationsessionhome = (IAuthorizationSessionLocalHome) locator.getLocalHome(IAuthorizationSessionLocalHome.COMP_NAME);
108         authorizationsession = authorizationsessionhome.create();
109
110         this.profiles = new EndEntityProfileDataHandler(administrator,raadminsession,authorizationsession,informationmemory);
111         
112         IHardTokenSessionLocalHome hardtokensessionhome = (IHardTokenSessionLocalHome) locator.getLocalHome(IHardTokenSessionLocalHome.COMP_NAME);
113         hardtokensession = hardtokensessionhome.create();
114
115         IKeyRecoverySessionLocalHome keyrecoverysessionhome = (IKeyRecoverySessionLocalHome) locator.getLocalHome(IKeyRecoverySessionLocalHome.COMP_NAME);
116         keyrecoverysession = keyrecoverysessionhome.create();
117         
118         IUserDataSourceSessionLocalHome userdatasourcesessionhome = (IUserDataSourceSessionLocalHome) locator.getLocalHome(IUserDataSourceSessionLocalHome.COMP_NAME);
119         userdatasourcesession = userdatasourcesessionhome.create();
120
121         initialized =true;
122       } else {
123           log.debug("=initialize(): already initialized");
124       }
125       log.debug("<initialize()");
126     }
127     
128     /* Adds a user to the database, the string array must be in format defined in class UserView. */
129     public void addUser(UserView userdata) throws Exception JavaDoc{
130         log.debug(">addUser()");
131         
132         if(userdata.getEndEntityProfileId() != 0){
133             UserDataVO uservo = new UserDataVO(userdata.getUsername(), userdata.getSubjectDN(), userdata.getCAId(), userdata.getSubjectAltName(),
134                     userdata.getEmail(), UserDataConstants.STATUS_NEW, userdata.getType(), userdata.getEndEntityProfileId(), userdata.getCertificateProfileId(),
135                     null,null, userdata.getTokenType(), userdata.getHardTokenIssuerId(), null);
136             uservo.setPassword(userdata.getPassword());
137             uservo.setExtendedinformation(userdata.getExtendedInformation());
138             adminsession.addUser(administrator, uservo, userdata.getClearTextPassword());
139             addedusermemory.addUser(userdata);
140         } else {
141             log.debug("=addUser(): profile id not set, user not created");
142         }
143         log.debug("<addUser()");
144     }
145     
146     /* Removes a number of users from the database.
147      *
148      * @param usernames an array of usernames to delete.
149      * @return false if administrator wasn't authorized to delete all of given users.
150      * */

151     public boolean deleteUsers(String JavaDoc[] usernames) throws Exception JavaDoc{
152       log.debug(">deleteUsers()");
153       boolean success = true;
154       for(int i=0; i < usernames.length; i++){
155          try{
156            adminsession.deleteUser(administrator, usernames[i]);
157          }catch(AuthorizationDeniedException e){
158            success = false;
159          }
160       }
161       log.debug("<deleteUsers(): " + success);
162       return success;
163     }
164
165     /* Changes the status of a number of users from the database.
166      *
167      * @param usernames an array of usernames to change.
168      * @param status gives the status to apply to users, should be one of UserDataRemote.STATUS constants.
169      * @return false if administrator wasn't authorized to change all of the given users.
170      * */

171     public boolean setUserStatuses(String JavaDoc[] usernames, String JavaDoc status) throws Exception JavaDoc{
172       log.debug(">setUserStatuses()");
173       boolean success = true;
174       int intstatus = 0;
175       try{
176         intstatus = Integer.parseInt(status);
177       }catch(Exception JavaDoc e){}
178       for(int i=0; i < usernames.length; i++){
179         try{
180           adminsession.setUserStatus(administrator, usernames[i],intstatus);
181         }catch(AuthorizationDeniedException e){
182            success = false;
183         }
184       }
185       log.debug("<setUserStatuses(): " + success);
186       return success;
187     }
188
189     /** Revokes the given users.
190      *
191      * @param users an array of usernames to revoke.
192      * @param reason reason(s) of revokation.
193      * @return false if administrator wasn't authorized to revoke all of the given users.
194      */

195     public boolean revokeUsers(String JavaDoc[] usernames, int reason) throws Exception JavaDoc{
196       log.debug(">revokeUsers()");
197       boolean success = true;
198       for(int i=0; i < usernames.length; i++){
199         try{
200           adminsession.revokeUser(administrator, usernames[i], reason);
201         }catch( AuthorizationDeniedException e){
202           success =false;
203         }
204       }
205       log.debug("<revokeUsers(): " + success);
206       return success;
207     }
208
209     /** Revokes the certificate with certificate serno.
210      *
211      * @param serno serial number of certificate to revoke.
212      * @param issuerdn the issuerdn of certificate to revoke.
213      * @param reason reason(s) of revokation.
214      * @return false if administrator wasn't authorized to revoke the given certificate.
215      */

216     public boolean revokeCert(BigInteger JavaDoc serno, String JavaDoc issuerdn, String JavaDoc username, int reason) throws Exception JavaDoc{
217       log.debug(">revokeCert()");
218       boolean success = true;
219       try{
220         adminsession.revokeCert(administrator, serno, issuerdn, username, reason);
221       }catch( AuthorizationDeniedException e){
222         success =false;
223       }
224       log.debug("<revokeCert(): " + success);
225       return success;
226     }
227
228     /**
229      * Reactivates the certificate with certificate serno.
230      *
231      * @param serno serial number of certificate to reactivate.
232      * @param issuerdn the issuerdn of certificate to reactivate.
233      * @param username the username joined to the certificate.
234      * @return false if administrator wasn't authorized to unrevoke the given certificate.
235      */

236     public boolean unrevokeCert(BigInteger JavaDoc serno, String JavaDoc issuerdn, String JavaDoc username) throws Exception JavaDoc {
237       log.debug(">unrevokeCert()");
238       boolean success = true;
239       try{
240          
241          RevokedCertInfo revinfo = certificatesession.isRevoked(administrator, issuerdn, serno);
242          
243          if ( revinfo != null && revinfo.getReason() == RevokedCertInfo.REVOKATION_REASON_CERTIFICATEHOLD ){
244              
245              //-- Find the UserView for the username, we must change his status
246
UserView userView = findUser(username);
247              
248              CertificateProfile certificateProfile = certificatesession.getCertificateProfile(administrator, userView.getCertificateProfileId());
249              Collection JavaDoc publisherList = certificateProfile.getPublisherList();
250             
251              //-- Try to change the certificate status
252
certificatesession.setRevokeStatus(administrator, issuerdn, serno, publisherList, RevokedCertInfo.NOT_REVOKED);
253             
254              if ( !certificatesession.checkIfAllRevoked(administrator, userView.getUsername()) ) {
255                  UserDataVO vo = adminsession.findUser(administrator, userView.getUsername());
256                  // Don't change status if it is already the same
257
if (vo.getStatus() != UserDataConstants.STATUS_GENERATED) {
258                      adminsession.setUserStatus(administrator, userView.getUsername(), UserDataConstants.STATUS_GENERATED);
259                  }
260              }
261                 
262          }
263    
264       }catch( AuthorizationDeniedException e){
265         success = false;
266       }
267
268       log.debug("<unrevokeCert(): " + success);
269       return success;
270     }
271     
272     /* Changes the userdata */
273     public void changeUserData(UserView userdata) throws Exception JavaDoc {
274         log.debug(">changeUserData()");
275
276         addedusermemory.changeUser(userdata);
277         if(userdata.getPassword() != null && userdata.getPassword().trim().equals(""))
278           userdata.setPassword(null);
279         UserDataVO uservo = new UserDataVO(userdata.getUsername(), userdata.getSubjectDN(), userdata.getCAId(), userdata.getSubjectAltName(),
280                 userdata.getEmail(), userdata.getStatus(), userdata.getType(), userdata.getEndEntityProfileId(), userdata.getCertificateProfileId(),
281                 null,null, userdata.getTokenType(), userdata.getHardTokenIssuerId(), null);
282         uservo.setPassword(userdata.getPassword());
283         uservo.setExtendedinformation(userdata.getExtendedInformation());
284         adminsession.changeUser(administrator, uservo, userdata.getClearTextPassword());
285
286         log.debug("<changeUserData()");
287     }
288
289     /* Method to filter out a user by it's username */
290     public UserView[] filterByUsername(String JavaDoc username) throws Exception JavaDoc{
291        log.debug(">filterByUserName()");
292        UserDataVO[] userarray = new UserDataVO[1];
293        UserDataVO user = null;
294        try{
295          user = adminsession.findUser(administrator, username);
296        }catch(AuthorizationDeniedException e){
297        }
298
299        if(user != null){
300          userarray[0]=user;
301          users.setUsers(userarray, informationmemory.getCAIdToNameMap());
302        }else{
303          users.setUsers((UserDataVO[]) null, informationmemory.getCAIdToNameMap());
304        }
305        log.debug("<filterByUserName()");
306        return users.getUsers(0,1);
307     }
308
309     /* Method used to check if user exists */
310     public boolean userExist(String JavaDoc username) throws Exception JavaDoc{
311        return adminsession.existsUser(administrator, username);
312     }
313     
314     /* Method to retrieve a user from the database without inserting it into users data, used by 'viewuser.jsp' and page*/
315     public UserView findUser(String JavaDoc username) throws Exception JavaDoc{
316        log.debug(">findUser(" + username + ")");
317        UserDataVO user = adminsession.findUser(administrator, username);
318         UserView userview = null;
319         if (user != null) {
320             userview = new UserView(user, informationmemory.getCAIdToNameMap());
321         }
322         log.debug("<findUser(" + username + "): " + userview);
323         return userview;
324     }
325     /* Method to retrieve a user from the database without inserting it into users data, used by 'edituser.jsp' and page*/
326     public UserView findUserForEdit(String JavaDoc username) throws Exception JavaDoc{
327        UserView userview = null;
328
329        UserDataVO user = adminsession.findUser(administrator, username);
330        
331        if(this.informationmemory.getGlobalConfiguration().getEnableEndEntityProfileLimitations())
332          if(!endEntityAuthorization(administrator, user.getEndEntityProfileId(),AvailableAccessRules.EDIT_RIGHTS, false))
333            throw new AuthorizationDeniedException("Not authorized to edit user.");
334
335        if(user != null)
336         userview = new UserView(user, informationmemory.getCAIdToNameMap());
337        return userview;
338     }
339
340     /* Method to find all users in database */
341     public UserView[] findAllUsers(int index,int size) throws Exception JavaDoc{
342        users.setUsers(adminsession.findAllUsersWithLimit(administrator), informationmemory.getCAIdToNameMap());
343        return users.getUsers(index,size);
344
345     }
346
347     /* Method to find all users in database */
348     public UserView[] filterByTokenSN(String JavaDoc tokensn, int index,int size) throws Exception JavaDoc{
349       UserView[] returnval = null;
350       UserDataVO user = null;
351       ArrayList JavaDoc userlist = new ArrayList JavaDoc();
352       
353       Collection JavaDoc usernames = hardtokensession.findHardTokenByTokenSerialNumber(administrator, tokensn);
354      
355       Iterator JavaDoc iter = usernames.iterator();
356       while(iter.hasNext()){
357          try{
358            user = adminsession.findUser(administrator, (String JavaDoc) iter.next());
359          }catch(AuthorizationDeniedException e){}
360         
361          if(user!=null)
362            userlist.add(user);
363       }
364      
365       users.setUsers(userlist, informationmemory.getCAIdToNameMap());
366
367       returnval= users.getUsers(index,size);
368
369       return returnval;
370     }
371
372     /* Method that checks if a certificate serialnumber is revoked and returns the user(s), else a null value. */
373     public UserView[] filterByCertificateSerialNumber(String JavaDoc serialnumber, int index, int size) throws RemoteException JavaDoc,
374                                                                                                    FinderException JavaDoc,
375                                                                                                    NamingException JavaDoc,
376                                                                                                    NumberFormatException JavaDoc,
377                                                                                                    CreateException JavaDoc{
378       serialnumber = StringTools.stripWhitespace(serialnumber);
379       Collection JavaDoc certs =certificatesession.findCertificatesBySerno(administrator, new BigInteger JavaDoc(serialnumber,16));
380       ArrayList JavaDoc userlist = new ArrayList JavaDoc();
381       UserView[] returnval = null;
382       if(certs != null){
383         Iterator JavaDoc iter = certs.iterator();
384         while(iter.hasNext()){
385            UserDataVO user = null;
386            try{
387              X509Certificate JavaDoc next = (X509Certificate JavaDoc) iter.next();
388              user = adminsession.findUserBySubjectAndIssuerDN(administrator, CertTools.getSubjectDN(next), next.getIssuerDN().toString());
389              if(user != null){
390                userlist.add(user);
391              }
392            }catch(AuthorizationDeniedException e){}
393         }
394         users.setUsers(userlist, informationmemory.getCAIdToNameMap());
395
396         returnval= users.getUsers(index,size);
397       }
398       return returnval;
399     }
400
401     /* Method that lists all users with certificate's that expires within given days. */
402     public UserView[] filterByExpiringCertificates(String JavaDoc days, int index, int size) throws RemoteException JavaDoc,
403                                                                                             FinderException JavaDoc,
404                                                                                             NumberFormatException JavaDoc,
405                                                                                             NamingException JavaDoc,
406                                                                                             CreateException JavaDoc{
407       ArrayList JavaDoc userlist = new ArrayList JavaDoc();
408       UserView[] returnval = null;
409
410       long d = Long.parseLong(days);
411       Date JavaDoc finddate = new Date JavaDoc();
412       long millis = (d * 86400000); // One day in milliseconds.
413
finddate.setTime(finddate.getTime() + millis);
414
415       Collection JavaDoc usernames =certificatesession.findCertificatesByExpireTimeWithLimit(administrator, finddate);
416       if(!usernames.isEmpty()){
417         Iterator JavaDoc i = usernames.iterator();
418         while(i.hasNext() && userlist.size() <= MAXIMUM_QUERY_ROWCOUNT +1 ){
419            UserDataVO user = null;
420            try{
421              user = adminsession.findUser(administrator, (String JavaDoc) i.next());
422              if(user != null)
423                userlist.add(user);
424            }catch(AuthorizationDeniedException e){}
425         }
426         users.setUsers(userlist, informationmemory.getCAIdToNameMap());
427
428         returnval= users.getUsers(index,size);
429       }
430       return returnval;
431     }
432
433     public UserView[] filterByQuery(Query query, int index, int size) throws Exception JavaDoc {
434       Collection JavaDoc userlist = adminsession.query(administrator, query, informationmemory.getUserDataQueryCAAuthoorizationString(), informationmemory.getUserDataQueryEndEntityProfileAuthorizationString(),0);
435       users.setUsers(userlist, informationmemory.getCAIdToNameMap());
436
437       return users.getUsers(index,size);
438     }
439
440     public int getResultSize(){
441      return users.size();
442     }
443
444     public boolean isAuthorizedToViewUserHistory(String JavaDoc username) throws Exception JavaDoc {
445       UserDataVO user = adminsession.findUser(administrator, username);
446       return endEntityAuthorization(administrator, user.getEndEntityProfileId(),AvailableAccessRules.HISTORY_RIGHTS, false);
447     }
448     
449     public boolean isAuthorizedToEditUser(String JavaDoc username) throws Exception JavaDoc {
450         UserDataVO user = adminsession.findUser(administrator, username);
451         return endEntityAuthorization(administrator, user.getEndEntityProfileId(),AvailableAccessRules.EDIT_RIGHTS, false);
452       }
453
454     /* Method to resort filtered user data. */
455     public void sortUserData(int sortby, int sortorder){
456       users.sortBy(sortby,sortorder);
457     }
458
459     /* Method to return the users between index and size, if userdata is smaller than size, a smaller array is returned. */
460     public UserView[] getUsers(int index, int size){
461       return users.getUsers(index, size);
462     }
463
464     /* Method that clears the userview memory. */
465     public void clearUsers(){
466       users.clear();
467     }
468
469     public boolean nextButton(int index, int size){
470       return index + size < users.size();
471     }
472     public boolean previousButton(int index){
473       return index > 0 ;
474     }
475
476     // Method dealing with added user memory.
477
/** A method to get the last added users in adduser.jsp.
478      *
479      * @see org.ejbca.ui.web.admin.rainterface.AddedUserMemory
480      */

481     public UserView[] getAddedUsers(int size){
482       return addedusermemory.getUsers(size);
483     }
484
485     // Methods dealing with profiles.
486

487
488     public TreeMap JavaDoc getAuthorizedEndEntityProfileNames() {
489       return informationmemory.getAuthorizedEndEntityProfileNames();
490     }
491
492     /** Returns the profile name from id proxied */
493     public String JavaDoc getEndEntityProfileName(int profileid) throws RemoteException JavaDoc{
494       return this.informationmemory.getEndEntityProfileNameProxy().getEndEntityProfileName(profileid);
495     }
496
497     public int getEndEntityProfileId(String JavaDoc profilename){
498       return profiles.getEndEntityProfileId(profilename);
499     }
500
501
502     public EndEntityProfile getEndEntityProfile(String JavaDoc name) throws Exception JavaDoc{
503       return profiles.getEndEntityProfile(name);
504     }
505
506     public EndEntityProfile getEndEntityProfile(int id) throws Exception JavaDoc{
507       return profiles.getEndEntityProfile(id);
508     }
509
510     public void addEndEntityProfile(String JavaDoc name) throws Exception JavaDoc{
511        EndEntityProfile profile = new EndEntityProfile();
512        Iterator JavaDoc iter = this.informationmemory.getAuthorizedCAIds().iterator();
513        String JavaDoc availablecas = "";
514        if(iter.hasNext())
515          availablecas = ((Integer JavaDoc) iter.next()).toString();
516        
517        while(iter.hasNext()){
518          availablecas = availablecas + EndEntityProfile.SPLITCHAR + ((Integer JavaDoc) iter.next()).toString();
519        }
520        
521        profile.setValue(EndEntityProfile.AVAILCAS, 0,availablecas);
522        profile.setRequired(EndEntityProfile.AVAILCAS, 0,true);
523         
524        profiles.addEndEntityProfile(name, profile);
525     }
526
527    
528     public void changeEndEntityProfile(String JavaDoc name, EndEntityProfile profile) throws Exception JavaDoc {
529        profiles.changeEndEntityProfile(name, profile);
530     }
531
532     /* Returns false if profile is used by any user or in authorization rules. */
533     public boolean removeEndEntityProfile(String JavaDoc name)throws Exception JavaDoc{
534         boolean profileused = false;
535         int profileid = raadminsession.getEndEntityProfileId(administrator, name);
536         // Check if any users or authorization rule use the profile.
537

538         profileused = adminsession.checkForEndEntityProfileId(administrator, profileid)
539                       || authorizationsession.existsEndEntityProfileInRules(administrator, profileid);
540
541         if(!profileused){
542           profiles.removeEndEntityProfile(name);
543         }
544
545         return !profileused;
546     }
547
548     public void renameEndEntityProfile(String JavaDoc oldname, String JavaDoc newname) throws Exception JavaDoc{
549        profiles.renameEndEntityProfile(oldname, newname);
550     }
551
552     public void cloneEndEntityProfile(String JavaDoc originalname, String JavaDoc newname) throws Exception JavaDoc{
553       profiles.cloneEndEntityProfile(originalname, newname);
554     }
555
556     public void loadCertificates(String JavaDoc username) throws Exception JavaDoc{
557         Collection JavaDoc certs = certificatesession.findCertificatesByUsername(administrator, username);
558         loadCertificateView(certs, username);
559     }
560     
561
562
563     public void loadTokenCertificates(String JavaDoc tokensn, String JavaDoc username) throws RemoteException JavaDoc, NamingException JavaDoc, CreateException JavaDoc, AuthorizationDeniedException, FinderException JavaDoc{
564         Collection JavaDoc certs = hardtokensession.findCertificatesInHardToken(administrator, tokensn);
565         loadCertificateView(certs, username);
566     }
567     
568     /** Helper method loading CertificateView and RevokedInfoView arrays given a collection of certificates.
569      *
570      * @param certs certificates to process
571      * @param username user the certs belong to
572      */

573     private void loadCertificateView(Collection JavaDoc certs, String JavaDoc username) {
574         if(!certs.isEmpty()){
575             Iterator JavaDoc j = certs.iterator();
576             certificates = new CertificateView[certs.size()];
577             for(int i=0; i< certificates.length; i++){
578                 RevokedInfoView revokedinfo = null;
579                 X509Certificate JavaDoc cert = (X509Certificate JavaDoc) j.next();
580                 RevokedCertInfo revinfo = certificatesession.isRevoked(administrator, CertTools.getIssuerDN(cert), cert.getSerialNumber());
581                 if(revinfo != null) {
582                     revokedinfo = new RevokedInfoView(revinfo);
583                 }
584                 certificates[i] = new CertificateView(cert, revokedinfo, username);
585             }
586         }
587         else{
588             certificates = null;
589         }
590     } // loadCertificateView
591

592     public boolean revokeTokenCertificates(String JavaDoc tokensn, String JavaDoc username, int reason) throws RemoteException JavaDoc, NamingException JavaDoc, CreateException JavaDoc, AuthorizationDeniedException, FinderException JavaDoc{
593        boolean success = true;
594
595        Collection JavaDoc certs = hardtokensession.findCertificatesInHardToken(administrator, tokensn);
596        Iterator JavaDoc i = certs.iterator();
597        try{
598          while(i.hasNext()){
599            X509Certificate JavaDoc cert = (X509Certificate JavaDoc) i.next();
600            adminsession.revokeCert(administrator, cert.getSerialNumber(), cert.getIssuerDN().toString(), username, reason);
601          }
602        }catch( AuthorizationDeniedException e){
603          success =false;
604        }
605
606        return success;
607     }
608
609     public boolean isAllTokenCertificatesRevoked(String JavaDoc tokensn, String JavaDoc username) throws RemoteException JavaDoc, NamingException JavaDoc, CreateException JavaDoc, AuthorizationDeniedException, FinderException JavaDoc{
610       Collection JavaDoc certs = hardtokensession.findCertificatesInHardToken(administrator, tokensn);
611
612       boolean allrevoked = true;
613
614       if(!certs.isEmpty()){
615         Iterator JavaDoc j = certs.iterator();
616         while(j.hasNext()){
617           X509Certificate JavaDoc cert = (X509Certificate JavaDoc) j.next();
618           RevokedCertInfo revinfo = certificatesession.isRevoked(administrator, CertTools.getIssuerDN(cert), cert.getSerialNumber());
619           if(revinfo == null || revinfo.getReason()== RevokedCertInfo.NOT_REVOKED)
620             allrevoked = false;
621         }
622       }
623
624       return allrevoked;
625     }
626     
627
628
629     public void loadCACertificates(CertificateView[] cacerts) {
630         certificates = cacerts;
631     }
632
633     public void loadCertificates(BigInteger JavaDoc serno, String JavaDoc issuerdn) throws RemoteException JavaDoc, NamingException JavaDoc, CreateException JavaDoc, AuthorizationDeniedException, FinderException JavaDoc{
634       try{
635           authorizationsession.isAuthorizedNoLog(administrator, AvailableAccessRules.CAPREFIX + issuerdn.hashCode());
636           X509Certificate JavaDoc cert = (X509Certificate JavaDoc) certificatesession.findCertificateByIssuerAndSerno(administrator, issuerdn, serno);
637           
638           if(cert != null){
639               RevokedInfoView revokedinfo = null;
640               String JavaDoc username = certificatesession.findUsernameByCertSerno(administrator,serno, cert.getIssuerDN().toString());
641               if(this.adminsession.findUser(administrator, username) != null){
642                   int endentityprofileid = this.adminsession.findUser(administrator, username).getEndEntityProfileId();
643                   this.endEntityAuthorization(administrator,endentityprofileid,AvailableAccessRules.VIEW_RIGHTS,true);
644               }
645               RevokedCertInfo revinfo = certificatesession.isRevoked(administrator, CertTools.getIssuerDN(cert), cert.getSerialNumber());
646               if(revinfo != null)
647                   revokedinfo = new RevokedInfoView(revinfo);
648               
649               certificates = new CertificateView[1];
650               certificates[0] = new CertificateView(cert, revokedinfo, username);
651               
652           }
653           else{
654               certificates = null;
655           }
656       }catch(AuthorizationDeniedException ade){
657           throw new AuthorizationDeniedException("Not authorized to view certificate, error: " + ade.getMessage());
658       }
659     }
660
661     public int getNumberOfCertificates(){
662       int returnval=0;
663       if(certificates != null){
664         returnval=certificates.length;
665       }
666       
667       return returnval;
668     }
669
670     public CertificateView getCertificate(int index){
671       CertificateView returnval = null;
672       if(certificates != null){
673         returnval = certificates[index];
674       }
675       
676       return returnval;
677     }
678
679     public boolean authorizedToEditUser(int profileid) throws RemoteException JavaDoc{
680       return endEntityAuthorization(administrator, profileid, AvailableAccessRules.EDIT_RIGHTS, false);
681     }
682
683     public boolean authorizedToViewHistory(int profileid) throws RemoteException JavaDoc{
684       return endEntityAuthorization(administrator, profileid, AvailableAccessRules.HISTORY_RIGHTS, false);
685     }
686
687     public boolean authorizedToViewHardToken(String JavaDoc username) throws Exception JavaDoc{
688       int profileid = adminsession.findUser(administrator, username).getEndEntityProfileId();
689       return endEntityAuthorization(administrator, profileid, AvailableAccessRules.HARDTOKEN_RIGHTS, false);
690     }
691
692     public boolean authorizedToViewHardToken(int profileid) throws Exception JavaDoc{
693       return endEntityAuthorization(administrator, profileid, AvailableAccessRules.HARDTOKEN_RIGHTS, false);
694     }
695
696     public boolean authorizedToRevokeCert(String JavaDoc username) throws FinderException JavaDoc, RemoteException JavaDoc, AuthorizationDeniedException{
697       boolean returnval=false;
698       UserDataVO data = adminsession.findUser(administrator, username);
699       if(data == null)
700         return false;
701               
702       int profileid = data.getEndEntityProfileId();
703
704       if(informationmemory.getGlobalConfiguration().getEnableEndEntityProfileLimitations())
705        returnval= endEntityAuthorization(administrator, profileid, AvailableAccessRules.REVOKE_RIGHTS, false);
706       else
707        returnval=true;
708
709       return returnval;
710     }
711
712
713     public boolean keyRecoveryPossible(X509Certificate JavaDoc cert, String JavaDoc username) throws Exception JavaDoc{
714       boolean returnval = true;
715       
716       try{
717         authorizationsession.isAuthorizedNoLog(administrator, AvailableAccessRules.REGULAR_KEYRECOVERY);
718       }catch(AuthorizationDeniedException ade){
719         returnval = false;
720       }
721       
722       if(informationmemory.getGlobalConfiguration().getEnableEndEntityProfileLimitations()){
723         UserDataVO data = adminsession.findUser(administrator, username);
724         if(data != null){
725           int profileid = data.getEndEntityProfileId();
726           returnval = endEntityAuthorization(administrator, profileid, AvailableAccessRules.KEYRECOVERY_RIGHTS, false);
727         }else
728           returnval = false;
729       }
730
731       return returnval && keyrecoverysession.existsKeys(administrator, cert) && !keyrecoverysession.isUserMarked(administrator,username);
732     }
733
734     public void markForRecovery(String JavaDoc username, X509Certificate JavaDoc cert) throws Exception JavaDoc{
735       boolean authorized = true;
736       int profileid = adminsession.findUser(administrator, username).getEndEntityProfileId();
737       if(informationmemory.getGlobalConfiguration().getEnableEndEntityProfileLimitations()){
738         authorized = endEntityAuthorization(administrator, profileid, AvailableAccessRules.KEYRECOVERY_RIGHTS, false);
739       }
740
741       if(authorized){
742         keyrecoverysession.markAsRecoverable(administrator, cert, profileid);
743       }
744     }
745
746     public String JavaDoc[] getCertificateProfileNames(){
747         String JavaDoc[] dummy = {""};
748         Collection JavaDoc certprofilenames = this.informationmemory.getAuthorizedEndEntityCertificateProfileNames().keySet();
749         if(certprofilenames == null)
750             return new String JavaDoc[0];
751         return (String JavaDoc[]) certprofilenames.toArray(dummy);
752     }
753
754     public int getCertificateProfileId(String JavaDoc certificateprofilename) throws RemoteException JavaDoc{
755       return certificatesession.getCertificateProfileId(administrator, certificateprofilename);
756     }
757     public String JavaDoc getCertificateProfileName(int certificateprofileid) throws RemoteException JavaDoc{
758       return this.informationmemory.getCertificateProfileNameProxy().getCertificateProfileName(certificateprofileid);
759     }
760
761     public boolean getEndEntityParameter(String JavaDoc parameter){
762        if(parameter == null)
763          return false;
764
765        return parameter.equals(EndEntityProfile.TRUE);
766     }
767
768     /**
769      * Help function used to check end entity profile authorization.
770      */

771     public boolean endEntityAuthorization(Admin admin, int profileid, String JavaDoc rights, boolean log) throws RemoteException JavaDoc {
772       boolean returnval = false;
773       
774       // TODO FIX
775
if(admin.getAdminInformation().isSpecialUser()){
776         return true;
777       }
778       try{
779         if(log)
780            returnval = authorizationsession.isAuthorized(admin, AvailableAccessRules.ENDENTITYPROFILEPREFIX+Integer.toString(profileid)+rights) &&
781            authorizationsession.isAuthorized(admin, AvailableAccessRules.REGULAR_RAFUNCTIONALITY + rights);
782         else
783            returnval = authorizationsession.isAuthorizedNoLog(admin, AvailableAccessRules.ENDENTITYPROFILEPREFIX+Integer.toString(profileid)+rights)&&
784            authorizationsession.isAuthorized(admin, AvailableAccessRules.REGULAR_RAFUNCTIONALITY + rights);
785       }catch(AuthorizationDeniedException e){}
786
787       return returnval;
788     }
789
790     /**
791      * Help functiosn used by edit end entity pages used to temporary save a profile
792      * so things can be canceled later
793      */

794     public EndEntityProfile getTemporaryEndEntityProfile(){
795         return this.temporateendentityprofile;
796     }
797     
798     public void setTemporaryEndEntityProfile(EndEntityProfile profile){
799         this.temporateendentityprofile = profile;
800     }
801     
802     IUserDataSourceSessionLocal getUserDataSourceSession(){
803         return userdatasourcesession;
804     }
805     
806     public String JavaDoc[] listPrinters(){
807         if(printerNames == null){
808             printerNames = org.ejbca.util.PrinterManager.listPrinters();
809         }
810         
811         return printerNames;
812     }
813
814     //
815
// Private fields.
816
//
817
private EndEntityProfileDataHandler profiles;
818
819     private IUserAdminSessionLocal adminsession;
820     private IUserAdminSessionLocalHome adminsessionhome;
821     private ICertificateStoreSessionLocal certificatesession;
822     private ICertificateStoreSessionLocalHome certificatesessionhome;
823     private IRaAdminSessionLocalHome raadminsessionhome;
824     private IRaAdminSessionLocal raadminsession;
825     private IAuthorizationSessionLocal authorizationsession;
826     private IHardTokenSessionLocal hardtokensession;
827     private IKeyRecoverySessionLocal keyrecoverysession;
828     private IUserDataSourceSessionLocal userdatasourcesession;
829
830     private UsersView users;
831     private CertificateView[] certificates;
832     private AddedUserMemory addedusermemory;
833     private Admin administrator;
834     private InformationMemory informationmemory;
835     private boolean initialized=false;
836     
837     private String JavaDoc[] printerNames = null;
838     
839     private EndEntityProfile temporateendentityprofile = null;
840 }
841
Popular Tags