]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
b274c21bc2c645cad3b14515219d0b2125fc0ddc
[tmp/jakarta-migration.git] /
1 /**
2  *  This document is a part of the source code and related artifacts
3  *  for CollectionSpace, an open source collections management system
4  *  for museums and related institutions:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2010 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
18  *  Unless required by applicable law or agreed to in writing, software
19  *  distributed under the License is distributed on an "AS IS" BASIS,
20  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  *  See the License for the specific language governing permissions and
22  *  limitations under the License.
23  */
24 /*
25  * To change this template, choose Tools | Templates
26  * and open the template in the editor.
27  */
28 package org.collectionspace.services.account.storage.csidp;
29
30 import java.util.Date;
31 import javax.persistence.Query;
32
33 import org.collectionspace.services.authentication.User;
34 import org.collectionspace.services.common.context.ServiceContext;
35 import org.collectionspace.services.common.document.BadRequestException;
36 import org.collectionspace.services.common.document.DocumentNotFoundException;
37 import org.collectionspace.services.common.document.JaxbUtils;
38 import org.collectionspace.services.common.document.TransactionException;
39 import org.collectionspace.services.common.security.SecurityUtils;
40 import org.collectionspace.services.common.storage.jpa.JPATransactionContext;
41
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * UserStorageClient manages persistence for CS IdP
47  * Note: this class is always used by the AccountStorageClient which provides
48  * access to entity manager
49  * @author
50  */
51 public class UserStorageClient {
52
53     private final Logger logger = LoggerFactory.getLogger(UserStorageClient.class);
54
55     /**
56      * create user with given userId and password
57      * @param userId
58      * @param password
59      * @return user
60      */
61     public User create(String userId, byte[] password) throws Exception {
62         User user = new User();
63         user.setUsername(userId);
64         user.setPasswd(getEncPassword(userId, password));
65         user.setCreatedAtItem(new Date());
66         return user;
67     }
68
69     /**
70      * getUser get user for given userId
71      * @param em EntityManager
72      * @param userId
73      */
74     public User get(JPATransactionContext jpaTransactionContext, String userId) throws DocumentNotFoundException {
75         User userFound = (User) jpaTransactionContext.find(User.class, userId);
76         if (userFound == null) {
77             String msg = "Could not find user with userId=" + userId;
78             logger.error(msg);
79             throw new DocumentNotFoundException(msg);
80         }
81         
82         return userFound;
83     }
84     
85     @SuppressWarnings("rawtypes")
86         public User get(ServiceContext ctx, String userId) throws DocumentNotFoundException, TransactionException {
87         User userFound = null;
88         
89         JPATransactionContext jpaConnectionContext = (JPATransactionContext)ctx.openConnection();
90         try {
91                 userFound = (User) jpaConnectionContext.find(User.class, userId);
92                 if (userFound == null) {
93                     String msg = "could not find user with userId=" + userId;
94                     logger.error(msg);
95                     throw new DocumentNotFoundException(msg);
96                 }
97         } finally {
98                 ctx.closeConnection();
99         }
100         
101         return userFound;
102     }    
103
104     /**
105      * updateUser for given userId
106      * @param entity manager
107      * @param userId
108      * @param password
109      */
110     public void update(JPATransactionContext jpaTransactionContext, String userId, byte[] password)
111             throws DocumentNotFoundException, Exception {
112         User userFound = get(jpaTransactionContext, userId);
113         if (userFound != null) {
114             userFound.setPasswd(getEncPassword(userId, password));
115             userFound.setUpdatedAtItem(new Date());
116             if (logger.isDebugEnabled()) {
117                 logger.debug("updated user=" + JaxbUtils.toString(userFound, User.class));
118             }
119             jpaTransactionContext.persist(userFound);
120         }
121     }
122
123     /**
124      * delete deletes user with given userId
125      * @param em entity manager
126      * @param userId
127      * @throws Exception if user for given userId not found
128      */
129     public void delete(JPATransactionContext jpaTransactionContext, String userId)
130             throws DocumentNotFoundException, Exception {
131         //if userid gives any indication about the id provider, it should
132         //be used to avoid the following approach
133         StringBuilder usrDelStr = new StringBuilder("DELETE FROM ");
134         usrDelStr.append(User.class.getCanonicalName());
135         usrDelStr.append(" WHERE username = :username");
136         //TODO: add tenant id
137         Query usrDel = jpaTransactionContext.createQuery(usrDelStr.toString());
138         usrDel.setParameter("username", userId);
139         int usrDelCount = usrDel.executeUpdate();
140         if (usrDelCount != 1) {
141             String msg = "could not find user with username=" + userId;
142             logger.error(msg);
143             throw new DocumentNotFoundException(msg);
144         }
145     }
146
147     private String getEncPassword(String userId, byte[] password) throws BadRequestException {
148         //jaxb unmarshaller already unmarshal xs:base64Binary, no need to b64 decode
149         //byte[] bpass = Base64.decodeBase64(accountReceived.getPassword());
150         try {
151             SecurityUtils.validatePassword(new String(password));
152         } catch (Exception e) {
153             throw new BadRequestException(e.getMessage());
154         }
155         String secEncPasswd = SecurityUtils.createPasswordHash(
156                 userId, new String(password));
157         return secEncPasswd;
158     }
159 }