Skip to content
This repository was archived by the owner on Oct 6, 2023. It is now read-only.

Commit 4843cd1

Browse files
author
sowerstl
committed
Add User ID as PK for User entities; (DOECODE-787)
1 parent b855f3b commit 4843cd1

File tree

2 files changed

+57
-31
lines changed

2 files changed

+57
-31
lines changed

src/main/java/gov/osti/entity/User.java

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
import javax.persistence.ElementCollection;
1313
import javax.persistence.Entity;
14+
import javax.persistence.GeneratedValue;
15+
import javax.persistence.GenerationType;
1416
import javax.persistence.Id;
1517
import javax.persistence.NamedQueries;
1618
import javax.persistence.NamedQuery;
@@ -19,9 +21,10 @@
1921
import javax.persistence.Table;
2022
import javax.persistence.Temporal;
2123
import javax.persistence.TemporalType;
24+
import javax.persistence.UniqueConstraint;
2225

2326
@Entity
24-
@Table(name="users")
27+
@Table(name="users", uniqueConstraints=@UniqueConstraint(columnNames={"email","apiKey"}))
2528
@NamedQueries ({
2629
@NamedQuery (name = "User.findAllUsers", query = "SELECT u FROM User u ORDER BY u.lastName"),
2730
@NamedQuery (name = "User.findUser", query = "SELECT u FROM User u WHERE u.email=lower(:email)")
@@ -48,6 +51,8 @@ public User(String email, String password, String apiKey, String confirmationCod
4851

4952
// email address is primary key for Users
5053
@Id
54+
@GeneratedValue(strategy = GenerationType.AUTO)
55+
private Long userId = null;
5156
private String email = null;
5257
private String password = null;
5358
private String apiKey = null;
@@ -120,6 +125,14 @@ public void setConfirmationCode(String confirmationCode) {
120125
this.confirmationCode = confirmationCode;
121126
}
122127

128+
public Long getUserId() {
129+
return userId;
130+
}
131+
132+
public void setUserId(Long userId) {
133+
this.userId = userId;
134+
}
135+
123136
public String getEmail() {
124137
return email;
125138
}

src/main/java/gov/osti/services/UserServices.java

Lines changed: 43 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import com.fasterxml.jackson.core.JsonProcessingException;
3030
import com.fasterxml.jackson.databind.ObjectMapper;
3131
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
32+
import com.fasterxml.jackson.databind.node.ObjectNode;
3233

3334
import gov.osti.entity.Site;
3435

@@ -161,7 +162,7 @@ public Response hasRole(@PathParam("role") String role) {
161162
}
162163

163164
/**
164-
* Endpoint that returns user email
165+
* Endpoint that returns user id and email
165166
*
166167
* @return an OK Response if session is logged in, otherwise a FORBIDDEN or
167168
* UNAUTHENTICATED response as appropriate
@@ -178,7 +179,7 @@ public Response load() {
178179
// return an OK if authenticated, otherwise authentication services will handle status
179180
return Response
180181
.status(Response.Status.OK)
181-
.entity(mapper.createObjectNode().put("email", user.getEmail()).toString())
182+
.entity(mapper.createObjectNode().put("userId", user.getUserId()).put("email", user.getEmail()).toString())
182183
.build();
183184
}
184185

@@ -318,6 +319,7 @@ public Response login(String object) {
318319
.createObjectNode()
319320
.put("xsrfToken", xsrfToken)
320321
.put("site", user.getSiteId())
322+
.put("userid", user.getUserId())
321323
.put("email", user.getEmail())
322324
.put("first_name", user.getFirstName())
323325
.put("last_name", user.getLastName())
@@ -441,7 +443,7 @@ public Response register(String object) {
441443
.build();
442444

443445
try {
444-
User user = em.find(User.class, request.getEmail());
446+
User user = findUserByEmail(em, request.getEmail());
445447

446448
// if there's already a user on file, cannot re-register if VERIFIED
447449
if ( user != null && user.isVerified() ) {
@@ -572,7 +574,7 @@ public Response forgotPassword(String object) {
572574

573575
// attempt to process the request
574576
try {
575-
User user = em.find(User.class, request.getEmail());
577+
User user = findUserByEmail(em, request.getEmail());
576578

577579
// account has to exist AND be verified
578580
if (null==user || !user.isVerified())
@@ -816,27 +818,21 @@ public Response getUsers(
816818
@RequiresRoles("OSTI")
817819
@Path("/{email}")
818820
public Response getUser(@PathParam("email") String email) {
819-
EntityManager em = DoeServletContextListener.createEntityManager();
820-
821821
try {
822822
if (StringUtils.isBlank(email))
823823
return ErrorResponse
824824
.badRequest("Missing required parameter.")
825825
.build();
826826

827-
TypedQuery<User> q = em.createNamedQuery("User.findUser", User.class)
828-
.setParameter("email", email);
827+
// should just be one user
828+
User u = findUserByEmail(email);
829829

830830
// if no users, send back a 404 response
831-
List<User> users = q.getResultList();
832-
if (users.isEmpty())
831+
if (u == null)
833832
return ErrorResponse
834833
.notFound("No users found.")
835834
.build();
836835

837-
// should just be one
838-
User u = users.get(0);
839-
840836
return Response
841837
.ok()
842838
.entity(mapper.writeValueAsString(u))
@@ -846,8 +842,6 @@ public Response getUser(@PathParam("email") String email) {
846842
return ErrorResponse
847843
.internalServerError("JSON processing error on User.")
848844
.build();
849-
} finally {
850-
em.close();
851845
}
852846
}
853847

@@ -969,19 +963,14 @@ public Response editUser(@PathParam("email") String email, String json) {
969963
.build();
970964

971965
try {
972-
TypedQuery<User> query = em.createNamedQuery("User.findUser", User.class)
973-
.setParameter("email", email);
974-
975-
List<User> results = query.getResultList();
966+
// obtain the BEFORE User
967+
User source = findUserByEmail(em, email);
976968

977-
if (results.isEmpty())
969+
if (source == null)
978970
return ErrorResponse
979971
.notFound("User is not on file.")
980972
.build();
981973

982-
// obtain the BEFORE User
983-
User source = results.get(0);
984-
985974
// ensure the EMAILS match, if supplied
986975
if ( !StringUtils.equalsIgnoreCase(email, source.getEmail()) )
987976
return ErrorResponse
@@ -1083,7 +1072,7 @@ public Response changePassword(String object) {
10831072
.build();
10841073

10851074
try {
1086-
User u = em.find(User.class, user.getEmail());
1075+
User u = em.find(User.class, user.getUserId());
10871076

10881077
if (null==u) {
10891078
return ErrorResponse
@@ -1456,7 +1445,7 @@ public Response confirmUser(@QueryParam("confirmation") String jwt) {
14561445
String confirmationCode = claims.getId();
14571446
String email = claims.getSubject();
14581447

1459-
currentUser = em.find(User.class, email);
1448+
currentUser = findUserByEmail(em, email);
14601449

14611450
if (currentUser == null) {
14621451
//no user matched, return with error
@@ -1627,12 +1616,36 @@ protected static User findUserByEmail(String email) {
16271616
EntityManager em = DoeServletContextListener.createEntityManager();
16281617

16291618
try {
1630-
return em.find(User.class, email);
1619+
return findUserByEmail(em, email);
1620+
} finally {
1621+
em.close();
1622+
}
1623+
}
1624+
1625+
/**
1626+
* Locate a User record by EMAIL address.
1627+
*
1628+
* @param em the ENTITY MANAGER to use if ATTACHED object is needed
1629+
* @param email the EMAIL to look for
1630+
* @return a User object if possible or null if not found or errors
1631+
*/
1632+
private static User findUserByEmail(EntityManager em, String email) {
1633+
try {
1634+
TypedQuery<User> q = em.createNamedQuery("User.findUser", User.class)
1635+
.setParameter("email", email);
1636+
1637+
// if no users, send back a 404 response
1638+
List<User> users = q.getResultList();
1639+
if (users.isEmpty())
1640+
throw new Exception("No users found.");
1641+
1642+
// should just be one
1643+
User u = users.get(0);
1644+
1645+
return u;
16311646
} catch ( Exception e ) {
16321647
log.warn("Error locating user : " + email, e);
16331648
return null;
1634-
} finally {
1635-
em.close();
16361649
}
16371650
}
16381651

@@ -1650,7 +1663,7 @@ private static void processUserLogin(String email, boolean failure) {
16501663

16511664
try {
16521665
// find the User
1653-
User user = em.find(User.class, email);
1666+
User user = findUserByEmail(em, email);
16541667

16551668
// this shouldn't happen
16561669
if (null==user)
@@ -1698,7 +1711,7 @@ private static void resetUserToken(String email) {
16981711
EntityManager em = DoeServletContextListener.createEntityManager();
16991712

17001713
try {
1701-
User user = em.find(User.class, email);
1714+
User user = findUserByEmail(em, email);
17021715

17031716
if (null==user)
17041717
throw new NotFoundException("Unable to locate user " + email);

0 commit comments

Comments
 (0)