]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
7a69d118abf58e42903b91faff9d22e9095edc61
[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.math.BigInteger;
31 import java.util.Date;
32 import java.util.UUID;
33
34 import javax.persistence.EntityManager;
35 import javax.persistence.EntityManagerFactory;
36 import javax.persistence.Query;
37
38 import org.collectionspace.services.authentication.Token;
39 import org.collectionspace.services.common.document.BadRequestException;
40 import org.collectionspace.services.common.document.DocumentException;
41 import org.collectionspace.services.common.document.DocumentNotFoundException;
42 import org.collectionspace.services.common.document.JaxbUtils;
43 import org.collectionspace.services.common.document.TransactionException;
44 import org.collectionspace.services.common.security.SecurityUtils;
45 import org.collectionspace.services.common.storage.TransactionContext;
46 import org.collectionspace.services.common.storage.jpa.JPATransactionContext;
47 import org.collectionspace.services.common.storage.jpa.JpaStorageUtils;
48
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 public class TokenStorageClient {
53
54     static private final Logger logger = LoggerFactory.getLogger(TokenStorageClient.class);
55
56     /**
57      * create user with given userId and password
58      * @param userId
59      * @param password
60      * @return user
61      */
62     static public Token create(String accountCsid, String tenantId, BigInteger expireSeconds) {
63         EntityManagerFactory emf = JpaStorageUtils.getEntityManagerFactory();        
64             Token token = new Token();
65             
66         try {
67             EntityManager em = emf.createEntityManager();
68
69                 token.setId(UUID.randomUUID().toString());
70                 token.setAccountCsid(accountCsid);
71                 token.setTenantId(tenantId);
72                 token.setExpireSeconds(expireSeconds);
73                 token.setEnabled(true);
74                 token.setCreatedAtItem(new Date());
75             
76             em.getTransaction().begin();
77                 em.persist(token);
78             em.getTransaction().commit();
79
80         } finally {
81             if (emf != null) {
82                 JpaStorageUtils.releaseEntityManagerFactory(emf);
83             }
84         }
85         
86         return token;
87         }
88
89     /**
90      * Update a token for given an id
91      * @param id
92      * @param enabledFlag
93      * @throws TransactionException 
94      */
95     static public void update(TransactionContext transactionContext, String id, boolean enabledFlag) throws DocumentNotFoundException, TransactionException {
96         Token tokenFound = null;
97         
98         tokenFound = get((JPATransactionContext)transactionContext, id);
99         if (tokenFound != null) {
100             tokenFound.setEnabled(enabledFlag);
101             tokenFound.setUpdatedAtItem(new Date());
102             if (logger.isDebugEnabled()) {
103                 logger.debug("Updated token=" + JaxbUtils.toString(tokenFound, Token.class));
104             }
105         } else {
106                 String msg = String.format("Could not find token with id='%s'", id);
107                 throw new DocumentNotFoundException(msg);
108         }
109     }
110
111     /**
112      * Get token for given ID
113      * @param em EntityManager
114      * @param id
115      */    
116     public static Token get(JPATransactionContext jpaTransactionContext, String id) throws DocumentNotFoundException, TransactionException {
117         Token tokenFound = null;
118         
119         tokenFound = (Token) jpaTransactionContext.find(Token.class, id);        
120         if (tokenFound == null) {
121             String msg = "Could not find token with ID=" + id;
122             logger.error(msg);
123             throw new DocumentNotFoundException(msg);
124         }
125
126         return tokenFound;
127     }
128     
129     static public Token get(String id) throws DocumentNotFoundException {
130         Token tokenFound = null;
131         EntityManagerFactory emf = JpaStorageUtils.getEntityManagerFactory();
132
133         try {
134             EntityManager em = emf.createEntityManager();
135             tokenFound = (Token) em.find(Token.class, id);        
136             if (tokenFound == null) {
137                 String msg = "Could not find token with ID=" + id;
138                 logger.error(msg);
139                 throw new DocumentNotFoundException(msg);
140             }
141         } finally {
142             if (emf != null) {
143                 JpaStorageUtils.releaseEntityManagerFactory(emf);
144             }
145         }
146         
147         return tokenFound;
148     }    
149
150         /**
151      * Deletes the token with given id
152      * @param id
153      * @throws Exception if user for given userId not found
154      */
155     static public void delete(String id) throws DocumentNotFoundException {
156         EntityManagerFactory emf = JpaStorageUtils.getEntityManagerFactory();
157
158         try {
159             EntityManager em = emf.createEntityManager();
160             
161             StringBuilder tokenDelStr = new StringBuilder("DELETE FROM ");
162                 tokenDelStr.append(Token.class.getCanonicalName());
163                 tokenDelStr.append(" WHERE id = :id");
164         
165                 Query tokenDel = em.createQuery(tokenDelStr.toString());
166                 tokenDel.setParameter("id", id);
167                 int tokenDelCount = tokenDel.executeUpdate();
168                 if (tokenDelCount != 1) {
169                     String msg = "Could not find token with id=" + id;
170                     logger.error(msg);
171                     throw new DocumentNotFoundException(msg);
172                 }
173         } finally {
174             if (emf != null) {
175                 JpaStorageUtils.releaseEntityManagerFactory(emf);
176             }
177         }               
178     }
179
180     private String getEncPassword(String userId, byte[] password) throws BadRequestException {
181         //jaxb unmarshaller already unmarshal xs:base64Binary, no need to b64 decode
182         //byte[] bpass = Base64.decodeBase64(accountReceived.getPassword());
183         try {
184             SecurityUtils.validatePassword(new String(password));
185         } catch (Exception e) {
186             throw new BadRequestException(e.getMessage());
187         }
188         String secEncPasswd = SecurityUtils.createPasswordHash(
189                 userId, new String(password), null);
190         return secEncPasswd;
191     }
192 }