]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
a0b86daa6f9ced381165e631f76151f909baea66
[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 java.util.UUID;
32
33 import javax.persistence.Query;
34
35 import org.collectionspace.services.authentication.User;
36 import org.collectionspace.services.common.context.ServiceContext;
37 import org.collectionspace.services.common.document.BadRequestException;
38 import org.collectionspace.services.common.document.DocumentNotFoundException;
39 import org.collectionspace.services.common.document.JaxbUtils;
40 import org.collectionspace.services.common.document.TransactionException;
41 import org.collectionspace.services.common.security.SecurityUtils;
42 import org.collectionspace.services.common.storage.jpa.JPATransactionContext;
43
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * UserStorageClient manages persistence for CS IdP
49  * Note: this class is always used by the AccountStorageClient which provides
50  * access to entity manager
51  * @author
52  */
53 public class UserStorageClient {
54
55     private final Logger logger = LoggerFactory.getLogger(UserStorageClient.class);
56
57     /**
58      * create user with given userId and password
59      * @param userId
60      * @param password
61      * @return user
62      */
63     public User create(String userId, byte[] password) throws Exception {
64         User user = new User();
65         user.setUsername(userId);
66         String salt = UUID.randomUUID().toString();
67         user.setPasswd(getEncPassword(userId, password, salt));
68         user.setSalt(salt);
69         user.setCreatedAtItem(new Date());
70         return user;
71     }
72
73     /**
74      * getUser get user for given userId
75      * @param em EntityManager
76      * @param userId
77      */
78     public User get(JPATransactionContext jpaTransactionContext, String userId) throws DocumentNotFoundException {
79         User userFound = (User) jpaTransactionContext.find(User.class, userId);
80         if (userFound == null) {
81             String msg = "Could not find user with userId=" + userId;
82             logger.error(msg);
83             throw new DocumentNotFoundException(msg);
84         }
85         
86         return userFound;
87     }
88     
89     @SuppressWarnings("rawtypes")
90         public User get(ServiceContext ctx, String userId) throws DocumentNotFoundException, TransactionException {
91         User userFound = null;
92         
93         JPATransactionContext jpaConnectionContext = (JPATransactionContext)ctx.openConnection();
94         try {
95                 userFound = (User) jpaConnectionContext.find(User.class, userId);
96                 if (userFound == null) {
97                     String msg = "could not find user with userId=" + userId;
98                     logger.error(msg);
99                     throw new DocumentNotFoundException(msg);
100                 }
101         } finally {
102                 ctx.closeConnection();
103         }
104         
105         return userFound;
106     }    
107
108     /**
109      * updateUser for given userId
110      * @param entity manager
111      * @param userId
112      * @param password
113      */
114     public void update(JPATransactionContext jpaTransactionContext, String userId, byte[] password)
115             throws DocumentNotFoundException, Exception {
116         User userFound = get(jpaTransactionContext, userId);
117         if (userFound != null) {
118             userFound.setPasswd(getEncPassword(userId, password, userFound.getSalt()));
119             userFound.setUpdatedAtItem(new Date());
120             if (logger.isDebugEnabled()) {
121                 logger.debug("updated user=" + JaxbUtils.toString(userFound, User.class));
122             }
123             jpaTransactionContext.persist(userFound);
124         }
125     }
126
127     /**
128      * delete deletes user with given userId
129      * @param em entity manager
130      * @param userId
131      * @throws Exception if user for given userId not found
132      */
133     public void delete(JPATransactionContext jpaTransactionContext, String userId)
134             throws DocumentNotFoundException, Exception {
135         //if userid gives any indication about the id provider, it should
136         //be used to avoid the following approach
137         StringBuilder usrDelStr = new StringBuilder("DELETE FROM ");
138         usrDelStr.append(User.class.getCanonicalName());
139         usrDelStr.append(" WHERE username = :username");
140         //TODO: add tenant id
141         Query usrDel = jpaTransactionContext.createQuery(usrDelStr.toString());
142         usrDel.setParameter("username", userId);
143         int usrDelCount = usrDel.executeUpdate();
144         if (usrDelCount != 1) {
145             String msg = "could not find user with username=" + userId;
146             logger.error(msg);
147             throw new DocumentNotFoundException(msg);
148         }
149     }
150
151     private String getEncPassword(String userId, byte[] password, String salt) throws BadRequestException {
152         //jaxb unmarshaller already unmarshal xs:base64Binary, no need to b64 decode
153         //byte[] bpass = Base64.decodeBase64(accountReceived.getPassword());
154         try {
155             SecurityUtils.validatePassword(new String(password));
156         } catch (Exception e) {
157             throw new BadRequestException(e.getMessage());
158         }
159         String secEncPasswd = SecurityUtils.createPasswordHash(
160                 userId, new String(password), salt);
161         return secEncPasswd;
162     }
163 }