Commit 0a51ba52 authored by nivetha's avatar nivetha
Browse files

Get user token API modification & token validation

Showing with 92 additions and 69 deletions
+92 -69
...@@ -9,6 +9,8 @@ import java.util.Arrays; ...@@ -9,6 +9,8 @@ import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.function.Function; import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
...@@ -16,6 +18,7 @@ import org.springframework.stereotype.Component; ...@@ -16,6 +18,7 @@ import org.springframework.stereotype.Component;
import com.tarento.retail.model.User; import com.tarento.retail.model.User;
import com.tarento.retail.util.AppConfiguration; import com.tarento.retail.util.AppConfiguration;
import com.tarento.retail.util.Constants;
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
...@@ -23,64 +26,62 @@ import io.jsonwebtoken.SignatureAlgorithm; ...@@ -23,64 +26,62 @@ import io.jsonwebtoken.SignatureAlgorithm;
@Component @Component
public class JwtTokenUtil implements Serializable { public class JwtTokenUtil implements Serializable {
public static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);
/** /**
* *
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public static final String CLAIMS_KEY = "scopes"; public static final String CLAIMS_KEY = "scopes";
@Autowired @Autowired
AppConfiguration appConfig; AppConfiguration appConfig;
public String getUsernameFromToken(String token) { public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject); return getClaimFromToken(token, Claims::getSubject);
} }
public Date getExpirationDateFromToken(String token) { public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration); return getClaimFromToken(token, Claims::getExpiration);
} }
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) { public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token); final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims); return claimsResolver.apply(claims);
} }
private Claims getAllClaimsFromToken(String token) { private Claims getAllClaimsFromToken(String token) {
return Jwts.parser() return Jwts.parser().setSigningKey(SIGNING_KEY).parseClaimsJws(token).getBody();
.setSigningKey(SIGNING_KEY) }
.parseClaimsJws(token)
.getBody(); public Boolean isTokenExpired(String token) {
} try {
final Date expiration = getExpirationDateFromToken(token);
private Boolean isTokenExpired(String token) { return expiration.before(new Date());
final Date expiration = getExpirationDateFromToken(token); } catch (Exception e) {
return expiration.before(new Date()); LOGGER.error(String.format(Constants.EXCEPTION_METHOD, "isTokenExpired", e.getMessage()));
} return Boolean.TRUE;
}
public String generateToken(User user) { }
return doGenerateToken(user.getUsername());
} public String generateToken(User user) {
return doGenerateToken(user.getUsername());
private String doGenerateToken(String subject) { }
Claims claims = Jwts.claims().setSubject(subject); private String doGenerateToken(String subject) {
claims.put(CLAIMS_KEY, Arrays.asList(new SimpleGrantedAuthority(JWT_GRANTED_AUTHORITY)));
Claims claims = Jwts.claims().setSubject(subject);
return Jwts.builder() claims.put(CLAIMS_KEY, Arrays.asList(new SimpleGrantedAuthority(JWT_GRANTED_AUTHORITY)));
.setClaims(claims)
.setIssuer(JWT_ISSUER) return Jwts.builder().setClaims(claims).setIssuer(JWT_ISSUER).setIssuedAt(new Date(System.currentTimeMillis()))
.setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + appConfig.getJwtValidity() * 60 * 1000))
.setExpiration(new Date(System.currentTimeMillis() + appConfig.getJwtValidity() * 60 * 1000)) .signWith(SignatureAlgorithm.HS256, SIGNING_KEY).compact();
.signWith(SignatureAlgorithm.HS256, SIGNING_KEY) }
.compact();
} public Boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
public Boolean validateToken(String token, UserDetails userDetails) { return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
final String username = getUsernameFromToken(token); }
return (
username.equals(userDetails.getUsername())
&& !isTokenExpired(token));
}
} }
...@@ -394,17 +394,16 @@ public class UserController { ...@@ -394,17 +394,16 @@ public class UserController {
return ResponseGenerator.failureResponse("Failed"); return ResponseGenerator.failureResponse("Failed");
} }
@RequestMapping(value = "getDeviceTokenForUserIds", method = RequestMethod.GET) @RequestMapping(value = PathRoutes.UserRoutes.GET_USER_DEVICE_TOKEN, method = RequestMethod.GET)
public List<UserDeviceToken> getUsersForAStore( public String getUsersDeviceToken(@RequestParam(value = "userIds", required = false) List<Long> userIdList)
@RequestParam(value = "userIds", required = false) List<Long> userIdList) throws JsonProcessingException { throws JsonProcessingException {
if (userIdList != null) { if (userIdList != null) {
List<UserDeviceToken> tokenList = userService.getDeviceTokenForUsers(userIdList); List<UserDeviceToken> tokenList = userService.getDeviceTokenForUsers(userIdList);
if (tokenList != null) { if (tokenList != null) {
return tokenList; return ResponseGenerator.successResponse(tokenList);
} }
return null;
} }
return null; return ResponseGenerator.failureResponse();
} }
@RequestMapping(value = PathRoutes.UserRoutes.CREATE_UPDATE_COUNTRY, method = RequestMethod.POST) @RequestMapping(value = PathRoutes.UserRoutes.CREATE_UPDATE_COUNTRY, method = RequestMethod.POST)
......
...@@ -22,6 +22,7 @@ import org.springframework.jdbc.support.GeneratedKeyHolder; ...@@ -22,6 +22,7 @@ import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder; import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.tarento.retail.config.JwtTokenUtil;
import com.tarento.retail.dao.RoleDao; import com.tarento.retail.dao.RoleDao;
import com.tarento.retail.dao.UserDao; import com.tarento.retail.dao.UserDao;
import com.tarento.retail.dto.CountryDto; import com.tarento.retail.dto.CountryDto;
...@@ -64,6 +65,9 @@ public class UserDaoImpl implements UserDao { ...@@ -64,6 +65,9 @@ public class UserDaoImpl implements UserDao {
@Autowired @Autowired
RoleDao roleDao; RoleDao roleDao;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Override @Override
public List<Action> findAllActionsByRoleID(Integer roleID) { public List<Action> findAllActionsByRoleID(Integer roleID) {
List<Action> actions = new ArrayList<Action>(); List<Action> actions = new ArrayList<Action>();
...@@ -643,8 +647,14 @@ public class UserDaoImpl implements UserDao { ...@@ -643,8 +647,14 @@ public class UserDaoImpl implements UserDao {
public List<UserDeviceToken> getDeviceTokenForUserList(List<Long> userIdList) { public List<UserDeviceToken> getDeviceTokenForUserList(List<Long> userIdList) {
List<UserDeviceToken> tokenList = new ArrayList<>(); List<UserDeviceToken> tokenList = new ArrayList<>();
try { try {
tokenList = jdbcTemplate.query(UserQueries.FETCH_USER_DEVICE_TOKEN + getIdQuery(userIdList) List<UserDeviceToken> response = jdbcTemplate.query(
+ UserQueries.USER_DEVICE_ROLE_CONDITION, new SqlDataMapper().new UserDeviceMapper()); UserQueries.FETCH_USER_DEVICE_TOKEN + getIdQuery(userIdList),
new SqlDataMapper().new UserDeviceMapper());
for (UserDeviceToken tokens : response) {
if (!jwtTokenUtil.isTokenExpired(tokens.getAuthToken())) {
tokenList.add(tokens);
}
}
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("Encountered an Exception while fetching User Device Token Map: " + e); LOGGER.error("Encountered an Exception while fetching User Device Token Map: " + e);
} }
......
...@@ -7,31 +7,42 @@ package com.tarento.retail.model; ...@@ -7,31 +7,42 @@ package com.tarento.retail.model;
*/ */
public class UserDeviceToken { public class UserDeviceToken {
private Long userId; private Long userId;
private String deviceToken; private String deviceToken;
private String deviceId; private String deviceId;
private String authToken;
public Long getUserId() { public Long getUserId() {
return userId; return userId;
} }
public void setUserId(Long userId) { public void setUserId(Long userId) {
this.userId = userId; this.userId = userId;
} }
public String getDeviceToken() { public String getDeviceToken() {
return deviceToken; return deviceToken;
} }
public void setDeviceToken(String deviceToken) { public void setDeviceToken(String deviceToken) {
this.deviceToken = deviceToken; this.deviceToken = deviceToken;
} }
public String getDeviceId() { public String getDeviceId() {
return deviceId; return deviceId;
} }
public void setDeviceId(String deviceId) { public void setDeviceId(String deviceId) {
this.deviceId = deviceId; this.deviceId = deviceId;
} }
public String getAuthToken() {
return authToken;
}
public void setAuthToken(String authToken) {
this.authToken = authToken;
}
} }
...@@ -96,6 +96,7 @@ public class SqlDataMapper { ...@@ -96,6 +96,7 @@ public class SqlDataMapper {
UserDeviceToken token = new UserDeviceToken(); UserDeviceToken token = new UserDeviceToken();
token.setDeviceToken(rs.getString("device_token")); token.setDeviceToken(rs.getString("device_token"));
token.setUserId(rs.getLong("user_id")); token.setUserId(rs.getLong("user_id"));
token.setAuthToken(rs.getString("auth_token"));
return token; return token;
} }
} }
...@@ -311,10 +312,10 @@ public class SqlDataMapper { ...@@ -311,10 +312,10 @@ public class SqlDataMapper {
return action; return action;
} }
} }
public class UserRoleCountMapper implements RowMapper<KeyValue> { public class UserRoleCountMapper implements RowMapper<KeyValue> {
public KeyValue mapRow(ResultSet rs, int rowNum) throws SQLException { public KeyValue mapRow(ResultSet rs, int rowNum) throws SQLException {
KeyValue keyValue = new KeyValue(); KeyValue keyValue = new KeyValue();
keyValue.setKey(rs.getString("roleName")); keyValue.setKey(rs.getString("roleName"));
keyValue.setValue(rs.getObject("numberOfUsers")); keyValue.setValue(rs.getObject("numberOfUsers"));
return keyValue; return keyValue;
......
...@@ -39,6 +39,7 @@ public interface PathRoutes { ...@@ -39,6 +39,7 @@ public interface PathRoutes {
final String MAP_USER_MASTER_ROLE_COUNTRY_ORG = "mapUserMasterRoleCountryOrg"; final String MAP_USER_MASTER_ROLE_COUNTRY_ORG = "mapUserMasterRoleCountryOrg";
final String REQUEST_OTP = "/requestOTP"; final String REQUEST_OTP = "/requestOTP";
final String NUMBER_OF_USERS_ROLES_GET = "/getNumberOfUsersAndRoles"; final String NUMBER_OF_USERS_ROLES_GET = "/getNumberOfUsersAndRoles";
final String GET_USER_DEVICE_TOKEN = "getDeviceTokenForUserIds";
} }
public interface AuthenticationRoutes { public interface AuthenticationRoutes {
......
...@@ -147,7 +147,7 @@ public interface Sql { ...@@ -147,7 +147,7 @@ public interface Sql {
final String CHECK_USER_DEVICE_TOKEN = "SELECT COUNT(*) FROM user_device WHERE user_id = ? AND device_token = ? "; final String CHECK_USER_DEVICE_TOKEN = "SELECT COUNT(*) FROM user_device WHERE user_id = ? AND device_token = ? ";
final String INSERT_USER_DEVICE_TOKEN = "INSERT INTO user_device (user_id, device_token, device_id, created_date, user_auth_id) VALUES (?,?,?,?,?) "; final String INSERT_USER_DEVICE_TOKEN = "INSERT INTO user_device (user_id, device_token, device_id, created_date, user_auth_id) VALUES (?,?,?,?,?) ";
final String UPDATE_USER_DEVICE_TOKEN = "UPDATE user_device SET device_token = ?, created_date = ? WHERE user_id = ? "; final String UPDATE_USER_DEVICE_TOKEN = "UPDATE user_device SET device_token = ?, created_date = ? WHERE user_id = ? ";
final String FETCH_USER_DEVICE_TOKEN = " SELECT device.id, device.user_id, device.device_token FROM user_device device WHERE device.user_id IN "; final String FETCH_USER_DEVICE_TOKEN = " SELECT device.id, device.user_id, device.device_token, auth_token FROM user_device device, user_authentication WHERE device.user_auth_id = user_authentication.id AND device.user_id IN ";
final String USER_DEVICE_ROLE_CONDITION = " and exists (select 1 from user_role where user_id = device.user_id and role_id IN (1,2)) " final String USER_DEVICE_ROLE_CONDITION = " and exists (select 1 from user_role where user_id = device.user_id and role_id IN (1,2)) "
+ "and not exists (select 1 from user_role where user_id = device.user_id and role_id NOT IN (1,2)) "; + "and not exists (select 1 from user_role where user_id = device.user_id and role_id NOT IN (1,2)) ";
final String FETCH_AUTH_TOKEN_REF = "SELECT id FROM user_authentication WHERE auth_token = ? "; final String FETCH_AUTH_TOKEN_REF = "SELECT id FROM user_authentication WHERE auth_token = ? ";
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment