Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,15 +1,50 @@
package local.skylerwebdev.javaschooldeploy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableWebMvc
@EnableSwagger2
@EnableJpaAuditing
@SpringBootApplication
public class JavaschooldeployApplication
{
private static final Logger logger = LoggerFactory.getLogger(JavaschooldeployApplication.class);
private static boolean stop = false;

@Autowired
private static Environment env;

private static void checkEnvironmentVariable(String envvar)
{
if (System.getenv(envvar) == null)
{
logger.error("Environment Variable " + envvar + " missing");
stop = true;
}
}

public static void main(String[] args)
{
SpringApplication.run(JavaschooldeployApplication.class, args);
checkEnvironmentVariable("OAUTHCLIENTID");
checkEnvironmentVariable("OAUTHCLIENTSECRET");

if (!stop)
{
ApplicationContext ctx = SpringApplication.run(JavaschooldeployApplication.class, args);

DispatcherServlet dispatcherServlet = (DispatcherServlet) ctx.getBean("dispatcherServlet");
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
}
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package local.skylerwebdev.javaschooldeploy;

import local.skylerwebdev.javaschooldeploy.models.Role;
import local.skylerwebdev.javaschooldeploy.models.User;
import local.skylerwebdev.javaschooldeploy.models.UserRoles;
import local.skylerwebdev.javaschooldeploy.services.RoleService;
import local.skylerwebdev.javaschooldeploy.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

@Transactional
@Component
public class SeedData implements CommandLineRunner
{
@Autowired
RoleService roleService;

@Autowired
UserService userService;


@Override
public void run(String[] args) throws Exception
{
Role r1 = new Role("admin");
Role r2 = new Role("user");
Role r3 = new Role("data");

roleService.save(r1);
roleService.save(r2);
roleService.save(r3);

// admin, data, user
ArrayList<UserRoles> admins = new ArrayList<>();
admins.add(new UserRoles(new User(), r1));
admins.add(new UserRoles(new User(), r2));
admins.add(new UserRoles(new User(), r3));
User u1 = new User("admin", "password", admins);
userService.save(u1);

// data, user
ArrayList<UserRoles> datas = new ArrayList<>();
datas.add(new UserRoles(new User(), r3));
datas.add(new UserRoles(new User(), r2));
User u2 = new User("cinnamon", "1234567", datas);
userService.save(u2);

// user
ArrayList<UserRoles> users = new ArrayList<>();
users.add(new UserRoles(new User(), r2));
User u3 = new User("barnbarn", "ILuvM4th!", users);
userService.save(u3);

users = new ArrayList<>();
users.add(new UserRoles(new User(), r2));
User u4 = new User("Bob", "password", users);
userService.save(u4);

users = new ArrayList<>();
users.add(new UserRoles(new User(), r2));
User u5 = new User("Jane", "password", users);
userService.save(u5);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1 * 60 * 60;
static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6 * 60 * 60;

@Autowired
private TokenStore tokenStore;
Expand All @@ -43,13 +42,19 @@ public void configure(ClientDetailsServiceConfigurer configurer) throws Exceptio
{
// .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT)

configurer.inMemory().withClient(CLIENT_ID).secret(encoder.encode(CLIENT_SECRET)).authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, IMPLICIT).scopes(SCOPE_READ, SCOPE_WRITE, TRUST).accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS).refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
configurer.inMemory()
.withClient(CLIENT_ID)
.secret(encoder.encode(CLIENT_SECRET))
.authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, IMPLICIT)
.scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception
{
endpoints.tokenStore(tokenStore).authenticationManager(authenticationManager);
endpoints.tokenStore(tokenStore)
.authenticationManager(authenticationManager);
endpoints.pathMapping("/oauth/token", "/login");
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
package local.skylerwebdev.javaschooldeploy.config;

import local.skylerwebdev.javaschooldeploy.JavaschooldeployApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
Expand All @@ -13,6 +19,21 @@
@Configuration
public class DataSourceConfig
{
private static final Logger logger = LoggerFactory.getLogger(JavaschooldeployApplication.class);
private static boolean stop = false;

@Autowired
private ApplicationContext appContext;

private static void checkEnvironmentVariable(String envvar)
{
if (System.getenv(envvar) == null)
{
logger.error("Environment Variable " + envvar + " missing");
stop = true;
}
}

@Autowired
private Environment env;

Expand All @@ -28,6 +49,18 @@ public DataSource dataSource()

if (dbValue.equalsIgnoreCase("POSTGRESQL"))
{
checkEnvironmentVariable("MYDBHOST");
checkEnvironmentVariable("MYDBNAME");
checkEnvironmentVariable("MYDBUSER");
checkEnvironmentVariable("MYDBPASSWORD");

if (stop)
{
logger.info("Manually shutting down system");
int exitCode = SpringApplication.exit(appContext, (ExitCodeGenerator) () -> 1);
System.exit(exitCode);
}

myUrlString = "jdbc:postgresql://" + System.getenv("MYDBHOST") + ":5432/" + System.getenv("MYDBNAME");
myDriverClass = "org.postgresql.Driver";
myDBUser = System.getenv("MYDBUSER");
Expand All @@ -41,8 +74,13 @@ public DataSource dataSource()
myDBPassword = "";
}

System.out.println(myUrlString);
return DataSourceBuilder.create().username(myDBUser).password(myDBPassword).url(myUrlString).driverClassName(myDriverClass).build();
logger.info("Database URL is " + myUrlString);
return DataSourceBuilder.create()
.username(myDBUser)
.password(myDBPassword)
.url(myUrlString)
.driverClassName(myDriverClass)
.build();
}

@Bean(name = "jdbcCustom")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
// @Configuration
// taken from https://techdev.io/en/developer-blog/querying-the-embedded-h2-database-of-a-spring-boot-application
// necessary for using the database tool built into intellij
public class H2ServerConfig
public class H2ServerConfiguration
{

// TCP port for remote connections, default 9092
Expand All @@ -30,7 +30,8 @@ public class H2ServerConfig
@ConditionalOnExpression("${h2.tcp.enabled:true}")
public Server h2TcpServer() throws SQLException
{
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", h2TcpPort).start();
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", h2TcpPort)
.start();
}

/**
Expand All @@ -42,6 +43,7 @@ public Server h2TcpServer() throws SQLException
@ConditionalOnExpression("${h2.web.enabled:true}")
public Server h2WebServer() throws SQLException
{
return Server.createWebServer("-web", "-webAllowOthers", "-webPort", h2WebPort).start();
return Server.createWebServer("-web", "-webAllowOthers", "-webPort", h2WebPort)
.start();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter
@Override
public void configure(ResourceServerSecurityConfigurer resources)
{
resources.resourceId(RESOURCE_ID).stateless(false);
resources.resourceId(RESOURCE_ID)
.stateless(false);
}

@Override
Expand All @@ -28,20 +29,25 @@ public void configure(HttpSecurity http) throws Exception
.antMatchers("/",
"/h2-console/**",
"/swagger-resources/**",
"/swagger-resources/configuration/ui",
"/swagger-resources/configuration/security",
"/swagger-resource/**",
"/swagger-ui.html",
"/v2/api-docs", "/webjars/**",
"/createnewuser",
"/otherapis/**").permitAll()
.antMatchers("/users/**", "/oauth/revoke-token").authenticated()
.antMatchers("/roles/**").hasAnyRole("ADMIN", "USER", "DATA")
.antMatchers("/actuator/**").hasAnyRole("ADMIN")
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
"/v2/api-docs",
"/webjars/**",
"/createnewuser").permitAll()
.antMatchers("/users/***", "/oauth/revoke-token").authenticated()
// .antMatchers("/books", "/authors").hasAnyRole("ADMIN", "USER", "DATA") - application data
// .antMatchers("/data/**").hasAnyRole("ADMIN", "DATA")
// .antMatchers("/users/***").hasAnyRole("USER")
.antMatchers("/roles/**", "/actuator/**").hasAnyRole("ADMIN")
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());

// http.requiresChannel().anyRequest().requiresSecure();
http.csrf().disable();
http.headers().frameOptions().disable();
http.csrf()
.disable();
http.headers()
.frameOptions()
.disable();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ public AuthenticationManager authenticationManagerBean() throws Exception
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Max-Age", "3600");

if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod()))
if (HttpMethod.OPTIONS.name()
.equalsIgnoreCase(((HttpServletRequest) req).getMethod()))
{
response.setStatus(HttpServletResponse.SC_OK);
} else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,32 @@
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

// http://localhost:2019/swagger-ui.html
@Configuration
@EnableSwagger2
public class Swagger2Config
{
@Bean
public Docket api()
{
return new Docket(DocumentationType.SWAGGER_2).select()
// .apis(RequestHandlerSelectors.any())
.apis(RequestHandlerSelectors.basePackage("com.lambdaschool.starthere")).paths(PathSelectors.any()).build().useDefaultResponseMessages(false) // Allows only my exception responses
.apis(RequestHandlerSelectors.basePackage("local.skylerwebdev.javaschooldeploy"))
.paths(PathSelectors.any())
.build()
.useDefaultResponseMessages(false) // Allows only my exception responses
.ignoredParameterTypes(Pageable.class) // allows only my paging parameter list
.apiInfo(apiEndPointsInfo());
}

private ApiInfo apiEndPointsInfo()
{
return new ApiInfoBuilder().title("Java Spring Back End Starting Project").description("A starting application for developing Java Spring Back End Projects").contact(new Contact("John Mitchell", "http://www.lambdaschool.com", "john@lambdaschool.com")).license("MIT").licenseUrl("https://github.com/LambdaSchool/java-starthere/blob/master/LICENSE").version("1.0.0").build();
return new ApiInfoBuilder().title("Java Project for Schools Deployment")
.description("A starting application for developing Java Spring Back End Projects")
.contact(new Contact("Skyler Dowdy", "https://github.com/skyler2440", "skylerwebdev@gmail.com"))
.version("1.0.0")
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ public class WebConfig implements WebMvcConfigurer
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");

registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Loading