Init app
This commit is contained in:
39
api/src/main/java/com/rossa/api/ApiApplication.java
Normal file
39
api/src/main/java/com/rossa/api/ApiApplication.java
Normal file
@@ -0,0 +1,39 @@
|
||||
package com.rossa.api;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@SpringBootApplication
|
||||
// @SpringBootApplication(scanBasePackages = "com.rossa.api.controller")
|
||||
public class ApiApplication extends SpringBootServletInitializer {
|
||||
|
||||
// @Override
|
||||
// protected SpringApplicationBuilder configure(SpringApplicationBuilder
|
||||
// builder) {
|
||||
// return builder.sources(ApiApplication.class);
|
||||
// }
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ApiApplication.class, args);
|
||||
}
|
||||
|
||||
// @Bean
|
||||
// WebMvcConfigurer corsConfigurer() {
|
||||
// return new WebMvcConfigurer() {
|
||||
// @Override
|
||||
// public void addCorsMappings(CorsRegistry registry) {
|
||||
// registry.addMapping("/**").allowedOrigins("http://localhost:4200",
|
||||
// "http://192.168.178.21:8180/").maxAge(3000);
|
||||
// // registry.addMapping("/**")
|
||||
// // .allowedHeaders("*")
|
||||
// // .allowedOrigins("*")
|
||||
// // .maxAge(3000);
|
||||
// }
|
||||
// };
|
||||
// }
|
||||
}
|
||||
13
api/src/main/java/com/rossa/api/ServletInitializer.java
Normal file
13
api/src/main/java/com/rossa/api/ServletInitializer.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package com.rossa.api;
|
||||
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
|
||||
public class ServletInitializer extends SpringBootServletInitializer {
|
||||
|
||||
@Override
|
||||
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
|
||||
return application.sources(ApiApplication.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.rossa.api.config;
|
||||
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
|
||||
@Override
|
||||
public void handle(HttpServletRequest req,
|
||||
HttpServletResponse resp,
|
||||
AccessDeniedException ex) throws IOException, ServletException {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (auth != null) {
|
||||
System.out.println("User '" + auth.getName()
|
||||
+ "' attempted to access the protected URL: "
|
||||
+ req.getRequestURI());
|
||||
resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Forbidden");
|
||||
} else {
|
||||
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.rossa.api.config;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
|
||||
private static final long serialVersionUID = -772511716561421072L;
|
||||
|
||||
@Override
|
||||
public void commence(HttpServletRequest arg0, HttpServletResponse arg1, AuthenticationException arg2)
|
||||
throws IOException, ServletException {
|
||||
arg1.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
|
||||
}
|
||||
}
|
||||
143
api/src/main/java/com/rossa/api/config/JwtRequestFilter.java
Normal file
143
api/src/main/java/com/rossa/api/config/JwtRequestFilter.java
Normal file
@@ -0,0 +1,143 @@
|
||||
package com.rossa.api.config;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.rossa.api.models.AuthUserInfo;
|
||||
import com.rossa.api.security.UserAuthenticationService;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import io.jsonwebtoken.ExpiredJwtException;
|
||||
|
||||
@Component
|
||||
public class JwtRequestFilter extends OncePerRequestFilter {
|
||||
private final String _authorizationKey = "authorization";
|
||||
private final String _bearerTokenPrefix = "bearer ";
|
||||
|
||||
@Autowired
|
||||
private UserAuthenticationService userAuthService;
|
||||
|
||||
@Autowired
|
||||
private JwtTokenUtils<AuthUserInfo> jwtTokenUtils;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
System.out.println("--------------------------------");
|
||||
System.out.println(request.getRequestURL().toString());
|
||||
|
||||
AuthUserInfo tokenUserInfo = null;
|
||||
String jwtToken = getJwtTokenFromHeader(request);
|
||||
|
||||
System.out.println("Token: " + jwtToken);
|
||||
|
||||
if (StringUtils.hasText(jwtToken)) {
|
||||
tokenUserInfo = extractJwtUserInfoFromToken(jwtToken);
|
||||
if (tokenUserInfo != null) {
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
if (StringUtils.hasText(tokenUserInfo.getUserId())) {
|
||||
AuthUserInfo userDetails = this.userAuthService.getUserById(tokenUserInfo.getUserId());
|
||||
if (userDetails != null) {
|
||||
if (jwtTokenUtils.validateToken(jwtToken, userDetails)) {
|
||||
List<GrantedAuthority> allAuths = convertUserRolesToGrantedAuthorities(
|
||||
userDetails.getUserRoles());
|
||||
if (allAuths != null && allAuths.size() > 0) {
|
||||
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
|
||||
userDetails, null, allAuths);
|
||||
usernamePasswordAuthenticationToken
|
||||
.setDetails(
|
||||
new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(usernamePasswordAuthenticationToken);
|
||||
} else {
|
||||
System.out.println("User has no roles associated with.");
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
} else {
|
||||
System.out.println("User credential cannot be validated.");
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
} else {
|
||||
System.out.println("No valid user credential available.");
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
} else {
|
||||
System.out.println("Invalid user info detected. Authentication failed.");
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
} else {
|
||||
System.out.println("Unable to get JWT Token");
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
} else {
|
||||
System.out.println("JWT Token does not begin with Bearer String");
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
|
||||
System.out.println("Try normal filtering");
|
||||
chain.doFilter(request, response);
|
||||
System.out.println("--------------------------------");
|
||||
}
|
||||
|
||||
private String getJwtTokenFromHeader(HttpServletRequest request) {
|
||||
String retVal = "";
|
||||
if (request != null) {
|
||||
|
||||
final String requestTokenHeader = request.getHeader(_authorizationKey);
|
||||
System.out.println("Found Auth Key: [" + requestTokenHeader + "]");
|
||||
if (StringUtils.hasText(requestTokenHeader) && requestTokenHeader.startsWith(_bearerTokenPrefix)) {
|
||||
retVal = requestTokenHeader.substring(_bearerTokenPrefix.length());
|
||||
}
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
private AuthUserInfo extractJwtUserInfoFromToken(String tokenStrVal) {
|
||||
AuthUserInfo retVal = null;
|
||||
if (StringUtils.hasText(tokenStrVal)) {
|
||||
try {
|
||||
retVal = jwtTokenUtils.getUserInfoFromToken(tokenStrVal);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
System.out.println("Unable to get JWT Token via token string decryption.");
|
||||
retVal = null;
|
||||
} catch (ExpiredJwtException ex) {
|
||||
System.out.println("JWT Token has expired");
|
||||
retVal = null;
|
||||
}
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
private List<GrantedAuthority> convertUserRolesToGrantedAuthorities(List<String> allUserRoles) {
|
||||
List<GrantedAuthority> retVal = new ArrayList<GrantedAuthority>();
|
||||
if (allUserRoles != null && allUserRoles.size() > 0) {
|
||||
for (String role : allUserRoles) {
|
||||
if (StringUtils.hasText(role)) {
|
||||
retVal.add(new SimpleGrantedAuthority(role));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
}
|
||||
190
api/src/main/java/com/rossa/api/config/JwtTokenUtils.java
Normal file
190
api/src/main/java/com/rossa/api/config/JwtTokenUtils.java
Normal file
@@ -0,0 +1,190 @@
|
||||
package com.rossa.api.config;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import com.rossa.api.models.AuthUserInfo;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.thymeleaf.util.StringUtils;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
|
||||
@Component
|
||||
public class JwtTokenUtils<T extends Object> implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = -2550185165626007488L;
|
||||
|
||||
public static final long JWT_TOKEN_VALIDITY = 15 * 60; // 15 minutes
|
||||
|
||||
@Value("${jwt.secret}")
|
||||
private String secret;
|
||||
|
||||
public AuthUserInfo getUserInfoFromToken(String token) {
|
||||
AuthUserInfo retVal = null;
|
||||
String userInfoStr = getUserInfoStringFromToken(token);
|
||||
if (!StringUtils.isEmpty(userInfoStr)) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
try {
|
||||
retVal = mapper.readValue(userInfoStr, AuthUserInfo.class);
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Exception occurred. " + ex.getMessage());
|
||||
ex.printStackTrace();
|
||||
retVal = null;
|
||||
}
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
public String getUserInfoStringFromToken(String token) {
|
||||
String retVal = null;
|
||||
if (!StringUtils.isEmpty(token)) {
|
||||
retVal = getClaimFromToken(token, Claims::getSubject);
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
public Date getExpirationDateFromToken(String token) {
|
||||
Date retVal = null;
|
||||
if (!StringUtils.isEmpty(token)) {
|
||||
retVal = getClaimFromToken(token, Claims::getExpiration);
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
public <K extends Object> K getClaimFromToken(String token,
|
||||
Function<Claims, K> claimsResolver) {
|
||||
if (!StringUtils.isEmpty(token)) {
|
||||
Claims claims = getAllClaimsFromToken(token);
|
||||
return claimsResolver.apply(claims);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Claims getAllClaimsFromToken(String token) {
|
||||
if (!StringUtils.isEmpty(token)) {
|
||||
if (!StringUtils.isEmpty(secret)) {
|
||||
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
|
||||
} else {
|
||||
System.out.println("Secret key is null or empty, unable to decode claims from token.");
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Boolean isTokenExpired(String token) {
|
||||
if (!StringUtils.isEmpty(token)) {
|
||||
Date expiration = getExpirationDateFromToken(token);
|
||||
if (expiration == null) {
|
||||
System.out.println("Invalid expiration data. Invalid token detected.");
|
||||
return false;
|
||||
}
|
||||
|
||||
return expiration.before(new Date());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public String generateToken(T userInfo, Map<String, Object> claims, Date startTime, Date expirationTime) {
|
||||
String userInfoStr = "";
|
||||
String retVal = null;
|
||||
|
||||
if (claims == null) {
|
||||
System.out.println("Claims object is null or empty, cannot createsecurity token.");
|
||||
return retVal;
|
||||
}
|
||||
|
||||
if (userInfo == null) {
|
||||
System.out.println("userInfo object is null or empty, cannot createsecurity token.");
|
||||
return retVal;
|
||||
}
|
||||
|
||||
try {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
userInfoStr = mapper.writeValueAsString(userInfo);
|
||||
|
||||
retVal = doGenerateToken(claims, userInfoStr, startTime, expirationTime);
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Exception occurred. " + ex.getMessage());
|
||||
ex.printStackTrace();
|
||||
retVal = null;
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
public String generateToken(T userDetails, Date startTime, Date expirationTime) {
|
||||
Map<String, Object> emptyClaims = new HashMap<String, Object>();
|
||||
return generateToken(userDetails, emptyClaims, startTime, expirationTime);
|
||||
}
|
||||
|
||||
private String doGenerateToken(Map<String, Object> claims, String subject, Date startTime, Date expirationTime) {
|
||||
String retVal = null;
|
||||
|
||||
if (StringUtils.isEmpty(secret)) {
|
||||
System.out.println("Invalid secret key for token encryption.");
|
||||
return retVal;
|
||||
}
|
||||
|
||||
if (claims == null) {
|
||||
System.out.println("Invalid token claims object.");
|
||||
return retVal;
|
||||
}
|
||||
|
||||
if (StringUtils.isEmpty(subject)) {
|
||||
System.out.println("Invalid subject value for the security token.");
|
||||
return retVal;
|
||||
}
|
||||
|
||||
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(startTime)
|
||||
.setExpiration(expirationTime)
|
||||
.signWith(SignatureAlgorithm.HS512, secret).compact();
|
||||
}
|
||||
|
||||
public Boolean validateToken(String token, AuthUserInfo userDetails) {
|
||||
if (!StringUtils.isEmpty(token)) {
|
||||
AuthUserInfo userInfo = getUserInfoFromToken(token);
|
||||
|
||||
if (userInfo != null) {
|
||||
if (userDetails != null) {
|
||||
String actualUserId = userInfo.getUserId();
|
||||
if (!StringUtils.isEmpty(actualUserId) && actualUserId.equalsIgnoreCase(userDetails.getUserId())) {
|
||||
if (userDetails.isUserActive()) {
|
||||
return !isTokenExpired(token);
|
||||
} else {
|
||||
System.out.println(String.format("User with id [%s] is not active. Invalid token.",
|
||||
userInfo.getUserId()));
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
System.out.println("User in the token has a different user id than expected. Invalid token.");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
System.out.println("Expected user details object is invalid. Unable to verify token validity.");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
System.out.println("Decrypted user details object is invalid. Invalid token.");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
System.out.println("Invalid token string detected. Invalid token.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.rossa.api.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
|
||||
public class WebAppSecurityConfig {
|
||||
@Autowired
|
||||
private AccessDeniedHandler accessDeniedHandler;
|
||||
|
||||
@Autowired
|
||||
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||
|
||||
@Autowired
|
||||
private JwtRequestFilter jwtRequestFilter;
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
System.out.println("Security filter chain initialization...");
|
||||
http.cors().and()
|
||||
.csrf().disable()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/assets/**", "/public/**", "/authenticate", "/app/**").permitAll()
|
||||
.anyRequest().authenticated().and()
|
||||
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
|
||||
.accessDeniedHandler(accessDeniedHandler).and().sessionManagement()
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
|
||||
|
||||
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public WebMvcConfigurer corsConfigurer() {
|
||||
String[] allowDomains = new String[2];
|
||||
allowDomains[0] = "http://localhost:4200";
|
||||
allowDomains[1] = "http://192.168.178.21:8180/";
|
||||
|
||||
System.out.println("CORS configuration....");
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**").allowedOrigins(allowDomains);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
39
api/src/main/java/com/rossa/api/config/data.sql
Normal file
39
api/src/main/java/com/rossa/api/config/data.sql
Normal file
@@ -0,0 +1,39 @@
|
||||
INSERT INTO meters (name) VALUES ('1LOG');
|
||||
INSERT INTO meters (name) VALUES ('1HEM');
|
||||
INSERT INTO meters (name) VALUES ('WASSER');
|
||||
INSERT INTO meters (name) VALUES ('ABWASSER');
|
||||
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-12-31 00:00:00', 11546.00, 1);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-09-30 00:00:00', 10504.00, 1);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-08-30 00:00:00', 10193.00, 1);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-07-01 00:00:00', 9679.00, 1);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2021-12-31 00:00:00', 7787.00, 1);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2021-09-25 00:00:00', 7322.00, 1);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-12-31 00:00:00', 12398.00, 2);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-05-31 00:00:00', 10799.00, 2);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2021-12-31 00:00:00', 8758.00, 2);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2021-09-01 00:00:00', 7355.00, 2);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2021-06-01 00:00:00', 7163.00, 2);
|
||||
|
||||
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2022-01-01 00:00:00', 288.00, 3);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2022-12-31 00:00:00', 464.00, 3);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2021-01-01 00:00:00', 153.00, 3);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2021-12-31 00:00:00', 288.00, 3);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2020-03-03 00:00:00', 153.00, 3);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2020-12-31 00:00:00', 288.00, 3);
|
||||
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2022-01-01 00:00:00', 116.00, 4);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2022-12-31 00:00:00', 189.00, 4);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2021-01-01 00:00:00', 81.00, 4);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2021-12-31 00:00:00', 116.00, 4);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2020-03-06 00:00:00', 0.00, 4);
|
||||
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2020-12-31 00:00:00', 81.00, 4);
|
||||
|
||||
|
||||
/***************
|
||||
|
||||
|
||||
|
||||
|
||||
***************/
|
||||
15
api/src/main/java/com/rossa/api/config/schema.sql
Normal file
15
api/src/main/java/com/rossa/api/config/schema.sql
Normal file
@@ -0,0 +1,15 @@
|
||||
CREATE TABLE meters (
|
||||
id INT NOT NULL AUTO_INCREMENT,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
CREATE TABLE meter_data (
|
||||
id INT NOT NULL AUTO_INCREMENT,
|
||||
type ENUM('ENERGY', 'WATER') NOT NULL,
|
||||
date DATETIME NOT NULL,
|
||||
amount FLOAT NOT NULL,
|
||||
meter_id INT NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY (meter_id) REFERENCES meter(id)
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.rossa.api.controllers;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
@Controller
|
||||
public class AppContoller {
|
||||
@RequestMapping(value = "/public/index", method = RequestMethod.GET)
|
||||
public ModelAndView index() {
|
||||
ModelAndView retVal = new ModelAndView();
|
||||
retVal.setViewName("indexPage");
|
||||
return retVal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.rossa.api.controllers;
|
||||
|
||||
import com.rossa.api.models.AuthUserInfo;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
public class ControllerBase {
|
||||
protected AuthUserInfo getCurrentUser() {
|
||||
AuthUserInfo retVal = null;
|
||||
Object principal = SecurityContextHolder
|
||||
.getContext()
|
||||
.getAuthentication()
|
||||
.getPrincipal();
|
||||
if (principal != null && principal instanceof AuthUserInfo) {
|
||||
retVal = (AuthUserInfo) principal;
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.rossa.api.controllers;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class HelloController {
|
||||
|
||||
@GetMapping("/hello")
|
||||
public String index() {
|
||||
return "Greetings from Spring Boot!";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.rossa.api.controllers;
|
||||
|
||||
import com.rossa.api.models.AuthUserInfo;
|
||||
import com.rossa.api.models.LoginRequest;
|
||||
import com.rossa.api.models.OpResponse;
|
||||
import com.rossa.api.security.UserAuthenticationService;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class LoginController extends ControllerBase {
|
||||
private UserAuthenticationService _authService;
|
||||
|
||||
public LoginController(UserAuthenticationService authService) {
|
||||
_authService = authService;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<AuthUserInfo> login(@RequestBody LoginRequest loginReq) {
|
||||
System.out.println("User Name: " + loginReq.getUserName());
|
||||
System.out.println("User Pass: " + loginReq.getUserPass());
|
||||
|
||||
if (StringUtils.hasText(loginReq.getUserName()) && StringUtils.hasText(loginReq.getUserPass())) {
|
||||
AuthUserInfo userFound = _authService.authenticateUser(loginReq.getUserName(), loginReq.getUserPass());
|
||||
if (userFound != null) {
|
||||
return ResponseEntity.ok(userFound);
|
||||
} else {
|
||||
return ResponseEntity.status(403).body((AuthUserInfo) null);
|
||||
}
|
||||
} else {
|
||||
return ResponseEntity.status(403).body((AuthUserInfo) null);
|
||||
}
|
||||
}
|
||||
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@RequestMapping(value = "/signOut", method = RequestMethod.POST)
|
||||
public ResponseEntity<OpResponse> signOut() {
|
||||
ResponseEntity<OpResponse> retVal = null;
|
||||
OpResponse resp = new OpResponse();
|
||||
|
||||
AuthUserInfo currUser = getCurrentUser();
|
||||
if (currUser != null) {
|
||||
String userId = currUser.getUserId();
|
||||
|
||||
boolean signoutSuccess = _authService.userSignOut(userId);
|
||||
if (signoutSuccess) {
|
||||
resp.setSuccessful(true);
|
||||
resp.setStatus("Log out successful");
|
||||
resp.setDetailMessage("You have successfully log out from this site.");
|
||||
retVal = new ResponseEntity<OpResponse>(resp, HttpStatus.OK);
|
||||
} else {
|
||||
resp.setSuccessful(false);
|
||||
resp.setStatus("Operation Failed");
|
||||
resp.setDetailMessage("Unable to sin out user. Unknown error.");
|
||||
retVal = new ResponseEntity<OpResponse>(resp, HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
} else {
|
||||
resp.setSuccessful(false);
|
||||
resp.setStatus("Operation Failed");
|
||||
resp.setDetailMessage("You cannot log out if you are not log in first.");
|
||||
retVal = new ResponseEntity<OpResponse>(resp, HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
System.out.println("sign out called!");
|
||||
return retVal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.rossa.api.controllers;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
import com.rossa.api.exception.ResourceNotFoundException;
|
||||
import com.rossa.api.models.Meter;
|
||||
import com.rossa.api.repository.MeterRepository;
|
||||
|
||||
@RestController
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public class MeterController {
|
||||
@Autowired
|
||||
private MeterRepository meterRepository;
|
||||
|
||||
@RequestMapping(value = "/meters", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public List<Meter> getAllEmployees() {
|
||||
return meterRepository.findAll();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/meters/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<Meter> getEmployeeById(@PathVariable(value = "id") long meterId)
|
||||
throws ResourceNotFoundException {
|
||||
Meter meter = meterRepository.findById(meterId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("Meter not found for this id :: " + meterId));
|
||||
return ResponseEntity.ok().body(meter);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/meters", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public Meter createMeter(@Valid @RequestBody Meter meter) {
|
||||
return meterRepository.save(meter);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.rossa.api.controllers;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
import com.rossa.api.exception.ResourceNotFoundException;
|
||||
import com.rossa.api.models.MeterData;
|
||||
import com.rossa.api.repository.MeterDataRepository;
|
||||
|
||||
@RestController
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
// @CrossOrigin(origins = "http://localhost:4200, http://192.168.178.21/")
|
||||
public class MeterDataController {
|
||||
@Autowired
|
||||
private MeterDataRepository meterDataRepository;
|
||||
|
||||
@RequestMapping(value = "/meter-data", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public List<com.rossa.api.models.MeterData> getAllMeterData() {
|
||||
return meterDataRepository.findAll();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/meter-data/meter/{meterId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public List<MeterData> getAllMeterDataByMeterId(@PathVariable(value = "meterId") long meterId) {
|
||||
return meterDataRepository.findByMeterId(meterId);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/meter-data/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<MeterData> getMeterDataById(@PathVariable(value = "id") long meterDataId)
|
||||
throws ResourceNotFoundException {
|
||||
MeterData meterData = meterDataRepository.findById(meterDataId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("Meter not found for this id :: " + meterDataId));
|
||||
return ResponseEntity.ok().body(meterData);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/meter-data", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public MeterData createMeterData(@Valid @RequestBody MeterData meterData) {
|
||||
return meterDataRepository.save(meterData);
|
||||
}
|
||||
|
||||
// @PutMapping("/meter-data/{id}")
|
||||
// public ResponseEntity < MeterData > updateMeterData(@PathVariable(value =
|
||||
// "id") Long meterDataId,
|
||||
// @Valid @RequestBody MeterData meterDataDetails) throws
|
||||
// ResourceNotFoundException {
|
||||
// MeterData meterData = meterDataRepository.findById(meterDataId)
|
||||
// .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this
|
||||
// id :: " + meterDataId));
|
||||
|
||||
// meterData.setAmount(meterDataDetails.getAmount());
|
||||
// meterData.setDate(meterDataDetails.getDate());
|
||||
// meterData.setMeter(meterDataDetails.getMeter());
|
||||
// meterData.setType(meterDataDetails.getType());
|
||||
// final MeterData updatedMeterData = meterDataRepository.save(meterData);
|
||||
// return ResponseEntity.ok(updatedMeterData);
|
||||
// }
|
||||
|
||||
@RequestMapping(value = "/meter-data/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<MeterData> updateMeterData(@PathVariable(value = "id") Long meterDataId,
|
||||
@Valid @RequestBody MeterData meterDataDetails) throws ResourceNotFoundException {
|
||||
MeterData meterData = meterDataRepository.findById(meterDataId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + meterDataId));
|
||||
|
||||
if (meterDataDetails.getType() != null) {
|
||||
meterData.setType(meterDataDetails.getType());
|
||||
}
|
||||
|
||||
if (meterDataDetails.getDate() != null) {
|
||||
meterData.setDate(meterDataDetails.getDate());
|
||||
}
|
||||
|
||||
if (meterDataDetails.getAmount() != null) {
|
||||
meterData.setAmount(meterDataDetails.getAmount());
|
||||
}
|
||||
|
||||
if (meterDataDetails.getMeter() != null) {
|
||||
meterData.setMeter(meterDataDetails.getMeter());
|
||||
}
|
||||
|
||||
final MeterData updatedMeterData = meterDataRepository.save(meterData);
|
||||
return ResponseEntity.ok(updatedMeterData);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/meter-data/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public Map<String, Boolean> deleteMeterData(@PathVariable(value = "id") Long meterDataId)
|
||||
throws ResourceNotFoundException {
|
||||
MeterData meterData = meterDataRepository.findById(meterDataId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + meterDataId));
|
||||
|
||||
meterDataRepository.delete(meterData);
|
||||
Map<String, Boolean> response = new HashMap<>();
|
||||
response.put("deleted", Boolean.TRUE);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.rossa.api.controllers;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.rossa.api.models.TitleModel;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class SecureApiController {
|
||||
public SecureApiController() {
|
||||
}
|
||||
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@RequestMapping(value = "/secure/allGameTitles", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<List<TitleModel>> allGameTitles() {
|
||||
List<TitleModel> resp = new ArrayList<TitleModel>();
|
||||
|
||||
TitleModel titleToAdd = new TitleModel();
|
||||
titleToAdd.setGameTitle("Cyberpunk 2077");
|
||||
titleToAdd.setPublisher("Warnder Bros");
|
||||
titleToAdd.setDevStudioName("CD Projekt Red");
|
||||
titleToAdd.setPublishingYear((short) 2019);
|
||||
titleToAdd.setRetailPrice(69.95f);
|
||||
|
||||
resp.add(titleToAdd);
|
||||
|
||||
titleToAdd = new TitleModel();
|
||||
titleToAdd.setGameTitle("Final Fantasy XV");
|
||||
titleToAdd.setPublisher("Square Enix");
|
||||
titleToAdd.setDevStudioName("Square Enix");
|
||||
titleToAdd.setPublishingYear((short) 2016);
|
||||
titleToAdd.setRetailPrice(59.95f);
|
||||
|
||||
resp.add(titleToAdd);
|
||||
|
||||
titleToAdd = new TitleModel();
|
||||
titleToAdd.setGameTitle("Fallout 4");
|
||||
titleToAdd.setPublisher("Bethesda Softworks");
|
||||
titleToAdd.setDevStudioName("Bethesda Game Studios");
|
||||
titleToAdd.setPublishingYear((short) 2015);
|
||||
titleToAdd.setRetailPrice(59.95f);
|
||||
|
||||
resp.add(titleToAdd);
|
||||
|
||||
titleToAdd = new TitleModel();
|
||||
titleToAdd.setGameTitle("Dragon Quest XI");
|
||||
titleToAdd.setPublisher("Square Enix");
|
||||
titleToAdd.setDevStudioName("Square Enix");
|
||||
titleToAdd.setPublishingYear((short) 2017);
|
||||
titleToAdd.setRetailPrice(59.95f);
|
||||
|
||||
resp.add(titleToAdd);
|
||||
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.rossa.api.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.NOT_FOUND)
|
||||
public class ResourceNotFoundException extends Exception{
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public ResourceNotFoundException(String message){
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
36
api/src/main/java/com/rossa/api/models/AuthToken.java
Normal file
36
api/src/main/java/com/rossa/api/models/AuthToken.java
Normal file
@@ -0,0 +1,36 @@
|
||||
package com.rossa.api.models;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class AuthToken
|
||||
extends AuthUserInfo {
|
||||
private Date sessionStartTime;
|
||||
|
||||
private Date sessionEndTime;
|
||||
|
||||
private String tokenValue;
|
||||
|
||||
public Date getSessionStartTime() {
|
||||
return sessionStartTime;
|
||||
}
|
||||
|
||||
public void setSessionStartTime(Date sessionStartTime) {
|
||||
this.sessionStartTime = sessionStartTime;
|
||||
}
|
||||
|
||||
public Date getSessionEndTime() {
|
||||
return sessionEndTime;
|
||||
}
|
||||
|
||||
public void setSessionEndTime(Date sessionEndTime) {
|
||||
this.sessionEndTime = sessionEndTime;
|
||||
}
|
||||
|
||||
public String getTokenValue() {
|
||||
return tokenValue;
|
||||
}
|
||||
|
||||
public void setTokenValue(String tokenValue) {
|
||||
this.tokenValue = tokenValue;
|
||||
}
|
||||
}
|
||||
75
api/src/main/java/com/rossa/api/models/AuthUserInfo.java
Normal file
75
api/src/main/java/com/rossa/api/models/AuthUserInfo.java
Normal file
@@ -0,0 +1,75 @@
|
||||
package com.rossa.api.models;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class AuthUserInfo {
|
||||
private String userId;
|
||||
|
||||
private String userName;
|
||||
|
||||
private String userPassword;
|
||||
|
||||
private String userNickName;
|
||||
|
||||
private boolean userActive;
|
||||
|
||||
private String userEmail;
|
||||
|
||||
private List<String> userRoles;
|
||||
|
||||
public String getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(String userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
public String getUserPassword() {
|
||||
return userPassword;
|
||||
}
|
||||
|
||||
public void setUserPassword(String userPassword) {
|
||||
this.userPassword = userPassword;
|
||||
}
|
||||
|
||||
public String getUserNickName() {
|
||||
return userNickName;
|
||||
}
|
||||
|
||||
public void setUserNickName(String userNickName) {
|
||||
this.userNickName = userNickName;
|
||||
}
|
||||
|
||||
public boolean isUserActive() {
|
||||
return userActive;
|
||||
}
|
||||
|
||||
public void setUserActive(boolean userActive) {
|
||||
this.userActive = userActive;
|
||||
}
|
||||
|
||||
public String getUserEmail() {
|
||||
return userEmail;
|
||||
}
|
||||
|
||||
public void setUserEmail(String userEmail) {
|
||||
this.userEmail = userEmail;
|
||||
}
|
||||
|
||||
public List<String> getUserRoles() {
|
||||
return userRoles;
|
||||
}
|
||||
|
||||
public void setUserRoles(List<String> userRoles) {
|
||||
this.userRoles = userRoles;
|
||||
}
|
||||
}
|
||||
23
api/src/main/java/com/rossa/api/models/LoginRequest.java
Normal file
23
api/src/main/java/com/rossa/api/models/LoginRequest.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package com.rossa.api.models;
|
||||
|
||||
public class LoginRequest {
|
||||
private String userName;
|
||||
|
||||
private String userPass;
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
public String getUserPass() {
|
||||
return userPass;
|
||||
}
|
||||
|
||||
public void setUserPass(String userPass) {
|
||||
this.userPass = userPass;
|
||||
}
|
||||
}
|
||||
40
api/src/main/java/com/rossa/api/models/Meter.java
Normal file
40
api/src/main/java/com/rossa/api/models/Meter.java
Normal file
@@ -0,0 +1,40 @@
|
||||
package com.rossa.api.models;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "meters")
|
||||
public class Meter {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
|
||||
@Column(name = "name", nullable = false)
|
||||
private String name;
|
||||
|
||||
public Meter() {
|
||||
}
|
||||
|
||||
// getters and setters
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
87
api/src/main/java/com/rossa/api/models/MeterData.java
Normal file
87
api/src/main/java/com/rossa/api/models/MeterData.java
Normal file
@@ -0,0 +1,87 @@
|
||||
package com.rossa.api.models;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.EnumType;
|
||||
import javax.persistence.Enumerated;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.Table;
|
||||
import javax.persistence.Temporal;
|
||||
import javax.persistence.TemporalType;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
@Entity
|
||||
@Table(name = "meterData")
|
||||
public class MeterData {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "type", nullable = false)
|
||||
private UsageType type;
|
||||
|
||||
@Column(name = "date", nullable = false)
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private Date date;
|
||||
|
||||
@Column(name = "amount", nullable = false)
|
||||
private Float amount;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "meterId", nullable = false)
|
||||
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
|
||||
private Meter meter;
|
||||
|
||||
public MeterData() {
|
||||
}
|
||||
|
||||
// getters and setters
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public UsageType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(UsageType type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public Float getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(Float amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public Meter getMeter() {
|
||||
return meter;
|
||||
}
|
||||
|
||||
public void setMeter(Meter meter) {
|
||||
this.meter = meter;
|
||||
}
|
||||
}
|
||||
33
api/src/main/java/com/rossa/api/models/OpResponse.java
Normal file
33
api/src/main/java/com/rossa/api/models/OpResponse.java
Normal file
@@ -0,0 +1,33 @@
|
||||
package com.rossa.api.models;
|
||||
|
||||
public class OpResponse {
|
||||
private boolean successful;
|
||||
|
||||
private String status;
|
||||
|
||||
private String detailMessage;
|
||||
|
||||
public boolean isSuccessful() {
|
||||
return successful;
|
||||
}
|
||||
|
||||
public void setSuccessful(boolean successful) {
|
||||
this.successful = successful;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getDetailMessage() {
|
||||
return detailMessage;
|
||||
}
|
||||
|
||||
public void setDetailMessage(String detailMessage) {
|
||||
this.detailMessage = detailMessage;
|
||||
}
|
||||
}
|
||||
53
api/src/main/java/com/rossa/api/models/TitleModel.java
Normal file
53
api/src/main/java/com/rossa/api/models/TitleModel.java
Normal file
@@ -0,0 +1,53 @@
|
||||
package com.rossa.api.models;
|
||||
|
||||
public class TitleModel {
|
||||
private String gameTitle;
|
||||
|
||||
private String publisher;
|
||||
|
||||
private String devStudioName;
|
||||
|
||||
private short publishingYear;
|
||||
|
||||
private float retailPrice;
|
||||
|
||||
public String getGameTitle() {
|
||||
return gameTitle;
|
||||
}
|
||||
|
||||
public void setGameTitle(String titleValue) {
|
||||
this.gameTitle = titleValue;
|
||||
}
|
||||
|
||||
public String getPublisher() {
|
||||
return publisher;
|
||||
}
|
||||
|
||||
public void setPublisher(String publisher) {
|
||||
this.publisher = publisher;
|
||||
}
|
||||
|
||||
public String getDevStudioName() {
|
||||
return devStudioName;
|
||||
}
|
||||
|
||||
public void setDevStudioName(String devStudioName) {
|
||||
this.devStudioName = devStudioName;
|
||||
}
|
||||
|
||||
public short getPublishingYear() {
|
||||
return publishingYear;
|
||||
}
|
||||
|
||||
public void setPublishingYear(short publishingYear) {
|
||||
this.publishingYear = publishingYear;
|
||||
}
|
||||
|
||||
public float getRetailPrice() {
|
||||
return retailPrice;
|
||||
}
|
||||
|
||||
public void setRetailPrice(float retailPrice) {
|
||||
this.retailPrice = retailPrice;
|
||||
}
|
||||
}
|
||||
25
api/src/main/java/com/rossa/api/models/UsageType.java
Normal file
25
api/src/main/java/com/rossa/api/models/UsageType.java
Normal file
@@ -0,0 +1,25 @@
|
||||
package com.rossa.api.models;
|
||||
|
||||
public enum UsageType {
|
||||
ENERGY("ENERGY"),
|
||||
WATER("WATER");
|
||||
|
||||
private final String value;
|
||||
|
||||
UsageType(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public static UsageType fromValue(String value) {
|
||||
for (UsageType type : values()) {
|
||||
if (type.value.equals(value)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Invalid UsageType value: " + value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.rossa.api.repository;
|
||||
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import com.rossa.api.models.MeterData;
|
||||
|
||||
public interface MeterDataRepository extends JpaRepository<MeterData, Long> {
|
||||
|
||||
List<MeterData> findByMeterId(long meterId);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.rossa.api.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.rossa.api.models.Meter;
|
||||
|
||||
public interface MeterRepository extends JpaRepository<Meter, Long> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.rossa.api.repository;
|
||||
|
||||
import com.rossa.api.models.AuthUserInfo;
|
||||
|
||||
public interface UserRepository {
|
||||
AuthUserInfo getUser(String userName, boolean userActive);
|
||||
|
||||
AuthUserInfo getUserById(String userId);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.rossa.api.repository;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.rossa.api.models.AuthUserInfo;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Service
|
||||
public class UserRepositoryImpl implements UserRepository {
|
||||
private static List<AuthUserInfo> mockUsersList;
|
||||
|
||||
static {
|
||||
mockUsersList = new ArrayList<AuthUserInfo>();
|
||||
|
||||
AuthUserInfo userToAdd = new AuthUserInfo();
|
||||
userToAdd.setUserActive(true);
|
||||
userToAdd.setUserId("00000001");
|
||||
userToAdd.setUserEmail("testuser1@teststore.org");
|
||||
userToAdd.setUserName("testuser1");
|
||||
userToAdd.setUserNickName("Test User1");
|
||||
userToAdd.setUserPassword("123test321");
|
||||
|
||||
List<String> adminRoles = new ArrayList<String>();
|
||||
adminRoles.add("ROLE_SITE_ADMIN");
|
||||
adminRoles.add("ROLE_SITE_SUPERUSER");
|
||||
adminRoles.add("ROLE_SITE_USER");
|
||||
|
||||
userToAdd.setUserRoles(adminRoles);
|
||||
mockUsersList.add(userToAdd);
|
||||
|
||||
userToAdd = new AuthUserInfo();
|
||||
userToAdd.setUserActive(true);
|
||||
userToAdd.setUserId("00000001");
|
||||
userToAdd.setUserEmail("testuser1@teststore.org");
|
||||
userToAdd.setUserName("testuser1");
|
||||
userToAdd.setUserNickName("Test User1");
|
||||
userToAdd.setUserPassword("123test321");
|
||||
|
||||
List<String> userRoles = new ArrayList<String>();
|
||||
userRoles.add("ROLE_SITE_USER");
|
||||
|
||||
userToAdd.setUserRoles(userRoles);
|
||||
mockUsersList.add(userToAdd);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthUserInfo getUser(String userName, boolean userActive) {
|
||||
AuthUserInfo retVal = null;
|
||||
if (mockUsersList != null) {
|
||||
Optional<AuthUserInfo> foundUser = mockUsersList.stream().filter(x -> {
|
||||
String uname = x.getUserName();
|
||||
return StringUtils.hasText(uname) && uname.equals(userName) && x.isUserActive() == userActive;
|
||||
}).findFirst();
|
||||
|
||||
if (foundUser.isPresent()) {
|
||||
retVal = foundUser.get();
|
||||
}
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthUserInfo getUserById(String userId) {
|
||||
AuthUserInfo retVal = null;
|
||||
if (mockUsersList != null) {
|
||||
Optional<AuthUserInfo> foundUser = mockUsersList.stream().filter(x -> {
|
||||
String uid = x.getUserId();
|
||||
return StringUtils.hasText(uid) && uid.equals(userId);
|
||||
}).findFirst();
|
||||
|
||||
if (foundUser.isPresent()) {
|
||||
retVal = foundUser.get();
|
||||
}
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.rossa.api.security;
|
||||
|
||||
import com.rossa.api.models.AuthToken;
|
||||
import com.rossa.api.models.AuthUserInfo;
|
||||
|
||||
public interface UserAuthenticationService {
|
||||
AuthToken authenticateUser(String userName, String password);
|
||||
|
||||
AuthUserInfo getUserById(String userId);
|
||||
|
||||
boolean userSignOut(String userId);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.rossa.api.security;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.rossa.api.config.JwtTokenUtils;
|
||||
import com.rossa.api.models.AuthToken;
|
||||
import com.rossa.api.models.AuthUserInfo;
|
||||
import com.rossa.api.repository.UserRepository;
|
||||
|
||||
@Service
|
||||
public class UserAuthenticationServiceImpl
|
||||
implements UserAuthenticationService {
|
||||
public static final long JWT_TOKEN_VALIDITY = 15 * 60; // 15 minutes
|
||||
|
||||
private UserRepository userRepo;
|
||||
private JwtTokenUtils<AuthUserInfo> jwtTknUtils;
|
||||
|
||||
public UserAuthenticationServiceImpl(UserRepository userRepo,
|
||||
JwtTokenUtils<AuthUserInfo> jwtTknUtils) {
|
||||
this.userRepo = userRepo;
|
||||
this.jwtTknUtils = jwtTknUtils;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthToken authenticateUser(String userName, String password) {
|
||||
AuthToken retVal = null;
|
||||
if (!StringUtils.hasText(userName)) {
|
||||
throw new IllegalArgumentException("User name cannot be null or empty.");
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(password)) {
|
||||
throw new IllegalArgumentException("User password cannot be null or empty.");
|
||||
}
|
||||
|
||||
AuthUserInfo foundUser = userRepo.getUser(userName, true);
|
||||
if (foundUser != null) {
|
||||
String userPass = foundUser.getUserPassword();
|
||||
if (StringUtils.hasText(userPass) && userPass.equals(password)) {
|
||||
long currTimeMillisec = System.currentTimeMillis();
|
||||
Date dateNow = new Date(currTimeMillisec);
|
||||
Date dateExpires = new Date(currTimeMillisec + JWT_TOKEN_VALIDITY * 1000);
|
||||
|
||||
retVal = new AuthToken();
|
||||
retVal.setUserId(foundUser.getUserId());
|
||||
retVal.setUserName(foundUser.getUserName());
|
||||
retVal.setUserNickName(foundUser.getUserNickName());
|
||||
retVal.setUserEmail(foundUser.getUserEmail());
|
||||
retVal.setUserActive(foundUser.isUserActive());
|
||||
retVal.setUserPassword(null);
|
||||
retVal.setUserRoles(foundUser.getUserRoles());
|
||||
|
||||
String jwtTknVal = this.jwtTknUtils.generateToken(foundUser, dateNow, dateExpires);
|
||||
retVal.setSessionStartTime(dateNow);
|
||||
retVal.setSessionEndTime(dateExpires);
|
||||
retVal.setTokenValue(jwtTknVal);
|
||||
} else {
|
||||
System.out.println("Unable to validate user credential. Authentication failed.");
|
||||
retVal = null;
|
||||
}
|
||||
} else {
|
||||
System.out.println("User not found. Authentication failed.");
|
||||
retVal = null;
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthUserInfo getUserById(String userId) {
|
||||
if (!StringUtils.hasText(userId)) {
|
||||
throw new IllegalArgumentException("User id cannot be null or empty.");
|
||||
}
|
||||
|
||||
AuthUserInfo retVal = userRepo.getUserById(userId);
|
||||
return retVal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean userSignOut(String userId) {
|
||||
// dud method.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
34
api/src/main/resources/application.properties
Normal file
34
api/src/main/resources/application.properties
Normal file
@@ -0,0 +1,34 @@
|
||||
# # Database
|
||||
# db.driver= com.mysql.jdbc.Driver
|
||||
# db.url= jdbc:mysql://192.168.178.21:3306/rossa_tech_testing
|
||||
# db.username=db_pezi
|
||||
# db.password=Pe23Zi0484!_db
|
||||
|
||||
# # Hibernate
|
||||
# hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
|
||||
# hibernate.show_sql=true
|
||||
# hibernate.hbm2ddl.auto=update
|
||||
# entitymanager.packagesToScan=Model
|
||||
|
||||
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration
|
||||
jwt.secret=aquickfoxjumpsoverthelazydog
|
||||
|
||||
|
||||
# Database
|
||||
spring.datasource.url= jdbc:mysql://192.168.178.21:3306/rossa_tech_testing?useSSL=false
|
||||
spring.datasource.username= db_pezi
|
||||
spring.datasource.password= Pe23Zi0484!_db
|
||||
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
|
||||
spring.jackson.serialization.fail-on-empty-beans=false
|
||||
|
||||
#spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
|
||||
|
||||
# Hibernate ddl auto (create, create-drop, validate, update)
|
||||
#spring.jpa.hibernate.ddl-auto= update
|
||||
|
||||
|
||||
# spring.security.user.name=pezi
|
||||
# spring.security.user.password=Password123!
|
||||
security.basic.enabled=false
|
||||
26
api/src/main/resources/templates/indexPage.html
Normal file
26
api/src/main/resources/templates/indexPage.html
Normal file
@@ -0,0 +1,26 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
|
||||
<title>Login</title>
|
||||
<link rel="stylesheet" th:href="@{/assets/bootstrap/css/bootstrap.min.css}"/>
|
||||
<link rel="stylesheet" th:href="@{/assets/bootstrap/css/bootstrap-theme.min.css}"/>
|
||||
<link rel="stylesheet" th:href="@{/assets/css/index.css}"/>
|
||||
<link rel="icon" type="image/png" th:href="@{/assets/images/favicon.png}">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container" ng-app="sampleApp">
|
||||
<ui-view></ui-view>
|
||||
</div>
|
||||
|
||||
<script type="text/javascript" th:src="@{/assets/jquery/js/jquery.min.js}"></script>
|
||||
<script type="text/javascript" th:src="@{/assets/bootstrap/js/bootstrap.min.js}"></script>
|
||||
<script type="text/javascript" th:src="@{/assets/angularjs/1.7.5/angular.min.js}"></script>
|
||||
<script type="text/javascript" th:src="@{/assets/angularjs/1.7.5/angular-resource.min.js}"></script>
|
||||
<script type="text/javascript" th:src="@{/assets/angularjs/1.7.5/angular-route.min.js}"></script>
|
||||
<script type="text/javascript" th:src="@{/assets/angularjs/1.7.5/angular-ui-router.min.js}"></script>
|
||||
<script type="module" th:src="@{/assets/app/js/app.js}"></script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user