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