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