# The guestbook starter from https://exe.dev/deploy/spring-boot. # Run it in a project generated by start.spring.io (web, thymeleaf, security, # data-jpa, flyway, postgresql, actuator); it writes the app's own files: # application.properties settings that aren't secrets # V1__messages.sql the first Flyway migration # Message, MessageRepository, GuestbookController the guestbook, with JPA # ExeDevSecurity sign-in from exe.dev's X-ExeDev-Email header # index.html, admin.html Thymeleaf templates set -eu mkdir -p src/main/java/com/example/app src/main/resources/templates src/main/resources/db/migration cat > src/main/resources/application.properties <<'EOF' spring.application.name=app # Flyway owns the schema; Hibernate only checks that the entities match it. spring.jpa.hibernate.ddl-auto=validate spring.jpa.open-in-view=false # exe.dev emails of people who may open /admin, comma-separated. app.admins=${APP_ADMINS:} EOF cat > src/main/resources/db/migration/V1__messages.sql <<'EOF' CREATE TABLE message ( id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, author TEXT NOT NULL, body TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); EOF cat > src/main/java/com/example/app/Message.java <<'EOF' package com.example.app; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import java.time.Instant; @Entity public class Message { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String author; private String body; private Instant createdAt = Instant.now(); protected Message() {} public Message(String author, String body) { this.author = author; this.body = body; } public Long getId() { return id; } public String getAuthor() { return author; } public String getBody() { return body; } public Instant getCreatedAt() { return createdAt; } } EOF cat > src/main/java/com/example/app/MessageRepository.java <<'EOF' package com.example.app; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; public interface MessageRepository extends JpaRepository { List findTop50ByOrderByIdDesc(); } EOF cat > src/main/java/com/example/app/GuestbookController.java <<'EOF' package com.example.app; import java.security.Principal; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.server.ResponseStatusException; import static org.springframework.http.HttpStatus.BAD_REQUEST; @Controller public class GuestbookController { private final MessageRepository messages; public GuestbookController(MessageRepository messages) { this.messages = messages; } @GetMapping("/") public String index(Model model) { model.addAttribute("messages", messages.findTop50ByOrderByIdDesc()); return "index"; } @PostMapping("/sign") public String sign(@RequestParam String body, Principal user) { body = body.strip(); if (body.isEmpty() || body.length() > 280) { throw new ResponseStatusException(BAD_REQUEST, "Say something, in 280 characters or fewer."); } // Signed in with exe.dev (see ExeDevSecurity): the email's local part. String author = user == null ? "a visitor" : user.getName().split("@")[0]; messages.save(new Message(author, body)); return "redirect:/"; } @GetMapping("/admin") public String admin(Model model) { model.addAttribute("count", messages.count()); return "admin"; } } EOF cat > src/main/java/com/example/app/ExeDevSecurity.java <<'EOF' package com.example.app; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Locale; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.ProviderManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider; import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter; /** * Signs visitors in with their exe.dev account. * * exe.dev's HTTPS proxy adds X-ExeDev-Email to every request from a visitor * signed in to exe.dev, and removes any X-ExeDev-* header the visitor sent * (https://exe.dev/docs/login-with-exe). Trusting the header is safe only * because the proxy is the only way to reach port 8000 from outside the VM. */ @Configuration public class ExeDevSecurity { /** Turns an X-ExeDev-Email into a user: ROLE_USER, plus ROLE_ADMIN for APP_ADMINS. */ @Bean UserDetailsService exeDevUsers(@Value("${app.admins}") List admins) { return email -> User.withUsername(email.strip().toLowerCase(Locale.ROOT)) .password("") .roles(admins.stream().anyMatch(email.strip()::equalsIgnoreCase) ? new String[] {"USER", "ADMIN"} : new String[] {"USER"}) .build(); } @Bean SecurityFilterChain securityFilterChain(HttpSecurity http, UserDetailsService exeDevUsers) throws Exception { var provider = new PreAuthenticatedAuthenticationProvider(); provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(exeDevUsers)); var exeDevLogin = new RequestHeaderAuthenticationFilter(); exeDevLogin.setPrincipalRequestHeader("X-ExeDev-Email"); exeDevLogin.setExceptionIfHeaderMissing(false); // no header: anonymous exeDevLogin.setAuthenticationManager(new ProviderManager(provider)); http.addFilter(exeDevLogin) // Read the header on every request; don't remember logins in a session. .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth .requestMatchers("/admin/**", "/admin").hasRole("ADMIN") .anyRequest().permitAll()) // Visitors who aren't signed in go to exe.dev's login page, then come back. .exceptionHandling(e -> e.authenticationEntryPoint((request, response, ex) -> response.sendRedirect("/__exe.dev/login?redirect=" + URLEncoder.encode(request.getRequestURI(), StandardCharsets.UTF_8)))); return http.build(); } } EOF cat > src/main/resources/templates/index.html <<'EOF' Guestbook

Guestbook

Signed in as you.

Not signed in. Sign in with exe.dev

  • someone: hello
  • No messages yet. Be the first.
EOF cat > src/main/resources/templates/admin.html <<'EOF' Admin

Admin

The guestbook has 0 messages.

EOF