6 Commits

18 changed files with 387 additions and 140 deletions

View File

@@ -30,7 +30,7 @@
<properties> <properties>
<java.version>21</java.version> <java.version>21</java.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>
@@ -55,7 +55,7 @@
<scope>runtime</scope> <scope>runtime</scope>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.mysql</groupId> <groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId> <artifactId>mysql-connector-j</artifactId>
@@ -77,6 +77,10 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
@@ -123,5 +127,4 @@
</plugins> </plugins>
</build> </build>
</project> </project>

View File

@@ -1,37 +1,37 @@
package com.example.demo.config; package com.example.demo.config;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
// データベースに保存されている平文パスワードと、BCryptでハッシュ化されたパスワードの両方を照合できるようにするクラス // データベースに保存されている平文パスワードと、BCryptでハッシュ化されたパスワードの両方を照合できるようにするクラス
public class CompatiblePasswordEncoder implements PasswordEncoder { public class CompatiblePasswordEncoder implements PasswordEncoder {
// パスワードを安全にハッシュ化するためのクラスを生成 // パスワードを安全にハッシュ化するためのクラスを生成
private final BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(); private final BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder();
// パスワードのハッシュ化 // パスワードのハッシュ化
@Override @Override
public String encode(CharSequence rawPassword) { public String encode(CharSequence rawPassword) {
return bcrypt.encode(rawPassword); return bcrypt.encode(rawPassword);
} }
@Override @Override
public boolean matches( public boolean matches(
CharSequence rawPassword, CharSequence rawPassword,
String encodedPassword) { String encodedPassword) {
// 保存済みパスワードが存在するか確認 // 保存済みパスワードが存在するか確認
if (encodedPassword == null) { if (encodedPassword == null) {
return false; return false;
} }
// 既存の平文パスワードに対応 // 既存の平文パスワードに対応
if (!encodedPassword.startsWith("$2a$") if (!encodedPassword.startsWith("$2a$")
&& !encodedPassword.startsWith("$2b$") && !encodedPassword.startsWith("$2b$")
&& !encodedPassword.startsWith("$2y$")) { && !encodedPassword.startsWith("$2y$")) {
return rawPassword.toString().equals(encodedPassword); return rawPassword.toString().equals(encodedPassword);
} }
// BCrypt形式のパスワードに対応 // BCrypt形式のパスワードに対応
return bcrypt.matches(rawPassword, encodedPassword); return bcrypt.matches(rawPassword, encodedPassword);
} }

View File

@@ -1,5 +1,5 @@
package com.example.demo.config; package com.example.demo.config;
import java.io.IOException; import java.io.IOException;
import jakarta.servlet.ServletException; import jakarta.servlet.ServletException;
@@ -11,49 +11,49 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.example.demo.service.LoginAttemptService; import com.example.demo.service.LoginAttemptService;
// ログイン失敗時の処理 // ログイン失敗時の処理
@Component @Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
private LoginAttemptService loginAttemptService; private LoginAttemptService loginAttemptService;
public CustomAuthenticationFailureHandler(LoginAttemptService loginAttemptService) { public CustomAuthenticationFailureHandler(LoginAttemptService loginAttemptService) {
this.loginAttemptService = loginAttemptService; this.loginAttemptService = loginAttemptService;
} }
@Override @Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException { AuthenticationException exception) throws IOException, ServletException {
// 画面から入力されたメールアドレスを取得 // 画面から入力されたメールアドレスを取得
String mailAddress = request.getParameter("mailAddress"); String mailAddress = request.getParameter("mailAddress");
if (mailAddress != null && !mailAddress.isBlank()) { if (mailAddress != null && !mailAddress.isBlank()) {
String mail = mailAddress.trim(); String mail = mailAddress.trim();
if (loginAttemptService.isBlocked(mail)) { if (loginAttemptService.isBlocked(mail)) {
getRedirectStrategy().sendRedirect( getRedirectStrategy().sendRedirect(
request, response, "/login?error=locked"); request, response, "/login?error=locked");
return; return;
} }
// 失敗回数を1増やす // 失敗回数を1増やす
loginAttemptService.loginFailed(mail); loginAttemptService.loginFailed(mail);
// すでにロック中なら失敗回数を増やさない // すでにロック中なら失敗回数を増やさない
if (loginAttemptService.isBlocked(mail)) { if (loginAttemptService.isBlocked(mail)) {
getRedirectStrategy().sendRedirect( getRedirectStrategy().sendRedirect(
request, response, "/login?error=locked"); request, response, "/login?error=locked");
return; return;
} }
// あと何回失敗されるとロックされるか取得 // あと何回失敗されるとロックされるか取得
int remaining = loginAttemptService.getRemainingAttempts(mail); int remaining = loginAttemptService.getRemainingAttempts(mail);
getRedirectStrategy().sendRedirect( getRedirectStrategy().sendRedirect(
request, response, "/login?error=failed&remaining=" + remaining); request, response, "/login?error=failed&remaining=" + remaining);
} }
} }
} }

View File

@@ -1,5 +1,5 @@
package com.example.demo.config; package com.example.demo.config;
import java.io.IOException; import java.io.IOException;
import jakarta.servlet.ServletException; import jakarta.servlet.ServletException;
@@ -12,37 +12,37 @@ import org.springframework.stereotype.Component;
import com.example.demo.common.Const; import com.example.demo.common.Const;
import com.example.demo.service.LoginAttemptService; import com.example.demo.service.LoginAttemptService;
@Component @Component
public class CustomAuthenticationSuccessHandler public class CustomAuthenticationSuccessHandler
extends SimpleUrlAuthenticationSuccessHandler { extends SimpleUrlAuthenticationSuccessHandler {
private final LoginAttemptService loginAttemptService; private final LoginAttemptService loginAttemptService;
public CustomAuthenticationSuccessHandler( public CustomAuthenticationSuccessHandler(
LoginAttemptService loginAttemptService) { LoginAttemptService loginAttemptService) {
this.loginAttemptService = loginAttemptService; this.loginAttemptService = loginAttemptService;
setDefaultTargetUrl("/menu"); setDefaultTargetUrl("/menu");
setAlwaysUseDefaultTargetUrl(true); setAlwaysUseDefaultTargetUrl(true);
} }
@Override @Override
public void onAuthenticationSuccess( public void onAuthenticationSuccess(
HttpServletRequest request, HttpServletRequest request,
HttpServletResponse response, HttpServletResponse response,
Authentication authentication) Authentication authentication)
throws IOException, ServletException { throws IOException, ServletException {
if (authentication.getPrincipal() instanceof CustomUserDetails userDetails) { if (authentication.getPrincipal() instanceof CustomUserDetails userDetails) {
String mail = userDetails.getUsername(); String mail = userDetails.getUsername();
loginAttemptService.loginSucceeded(mail); loginAttemptService.loginSucceeded(mail);
request.getSession(true).setAttribute( request.getSession(true).setAttribute(
Const.SESSION_LOGIN_USER, Const.SESSION_LOGIN_USER,
userDetails.getLoginUser()); userDetails.getLoginUser());
} }
super.onAuthenticationSuccess(request, response, authentication); super.onAuthenticationSuccess(request, response, authentication);
} }
} }

View File

@@ -1,5 +1,5 @@
package com.example.demo.config; package com.example.demo.config;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@@ -9,36 +9,36 @@ import org.springframework.security.core.userdetails.UserDetails;
import com.example.demo.common.LoginUser; import com.example.demo.common.LoginUser;
import com.example.demo.service.LoginAttemptService; import com.example.demo.service.LoginAttemptService;
// システムの社員情報をSpring Securityが扱えるクラスに変更 // システムの社員情報をSpring Securityが扱えるクラスに変更
public class CustomUserDetails implements UserDetails { public class CustomUserDetails implements UserDetails {
private final LoginUser loginUser; private final LoginUser loginUser;
private final String password; // DBから取得した暗号化パスワードを保持 private final String password; // DBから取得した暗号化パスワードを保持
private final LoginAttemptService loginAttemptService; private final LoginAttemptService loginAttemptService;
public CustomUserDetails(LoginUser loginUser, String password, LoginAttemptService loginAttemptService) { public CustomUserDetails(LoginUser loginUser, String password, LoginAttemptService loginAttemptService) {
this.loginUser = loginUser; this.loginUser = loginUser;
this.password = password; this.password = password;
this.loginAttemptService = loginAttemptService; this.loginAttemptService = loginAttemptService;
} }
@Override @Override
public String getPassword() { public String getPassword() {
return this.password; return this.password;
} }
@Override @Override
public String getUsername() { public String getUsername() {
return loginUser.getMailAddress(); return loginUser.getMailAddress();
} }
// アカウントのロック状態の確認 // アカウントのロック状態の確認
@Override @Override
public boolean isAccountNonLocked() { public boolean isAccountNonLocked() {
return !loginAttemptService.isBlocked(getUsername()); return !loginAttemptService.isBlocked(getUsername());
} }
// 管理者判定メソッド // 管理者判定メソッド
@Override @Override
@@ -46,29 +46,29 @@ public class CustomUserDetails implements UserDetails {
String role = loginUser.isAdmin() String role = loginUser.isAdmin()
? "ROLE_ADMIN" ? "ROLE_ADMIN"
: "ROLE_USER"; : "ROLE_USER";
return Collections.singletonList( // 要素が一つだけの変更できないリストを作るメソッド return Collections.singletonList( // 要素が一つだけの変更できないリストを作るメソッド
new SimpleGrantedAuthority(role)); new SimpleGrantedAuthority(role));
} }
@Override @Override
public boolean isAccountNonExpired() { public boolean isAccountNonExpired() {
return true; return true;
} }
@Override @Override
public boolean isCredentialsNonExpired() { public boolean isCredentialsNonExpired() {
return true; return true;
} }
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return true; return true;
} }
// ログイン成功後にコントローラー等でLoginUserを取り出すためのゲッター // ログイン成功後にコントローラー等でLoginUserを取り出すためのゲッター
public LoginUser getLoginUser() { public LoginUser getLoginUser() {
return loginUser; return loginUser;
} }
} }

View File

@@ -34,4 +34,5 @@ public class LoginCheckInterceptor implements HandlerInterceptor {
} }
return true; return true;
} }
} }

View File

@@ -1,5 +1,5 @@
package com.example.demo.config; package com.example.demo.config;
import org.springframework.boot.security.autoconfigure.web.servlet.PathRequest; import org.springframework.boot.security.autoconfigure.web.servlet.PathRequest;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@@ -7,25 +7,25 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
public class SecurityConfig { public class SecurityConfig {
private final CustomAuthenticationFailureHandler failureHandler; private final CustomAuthenticationFailureHandler failureHandler;
private final CustomAuthenticationSuccessHandler successHandler; private final CustomAuthenticationSuccessHandler successHandler;
public SecurityConfig( public SecurityConfig(
CustomAuthenticationFailureHandler failureHandler, CustomAuthenticationFailureHandler failureHandler,
CustomAuthenticationSuccessHandler successHandler) { CustomAuthenticationSuccessHandler successHandler) {
this.failureHandler = failureHandler; this.failureHandler = failureHandler;
this.successHandler = successHandler; this.successHandler = successHandler;
} }
@Bean @Bean
public SecurityFilterChain securityFilterChain( public SecurityFilterChain securityFilterChain(
HttpSecurity http) throws Exception { HttpSecurity http) throws Exception {
http http
.authorizeHttpRequests(authorize -> authorize .authorizeHttpRequests(authorize -> authorize
.requestMatchers( .requestMatchers(
@@ -47,10 +47,10 @@ public class SecurityConfig {
.logoutUrl("/logout") .logoutUrl("/logout")
.logoutSuccessUrl("/login?logout") .logoutSuccessUrl("/login?logout")
.permitAll()); .permitAll());
return http.build(); return http.build();
} }
@Bean @Bean
public PasswordEncoder passwordEncoder() { public PasswordEncoder passwordEncoder() {
return new CompatiblePasswordEncoder(); return new CompatiblePasswordEncoder();

View File

@@ -1,39 +1,90 @@
package com.example.demo.controller; package com.example.demo.controller;
import java.util.List;
import java.util.stream.IntStream;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import com.example.demo.entity.BookCollection;
import com.example.demo.service.BookService; import com.example.demo.service.BookService;
/** BOOK-01:書籍検索(bookList.html) */ /** BOOK-01:書籍検索(bookList.html) */
@Controller @Controller
public class BookController { public class BookController {
private final BookService bookService; private final BookService bookService;
public BookController(BookService bookService) { public BookController(BookService bookService) {
this.bookService = bookService; this.bookService = bookService;
} }
/** メニューの「書籍一覧」=条件なし(全件)、検索ボタン=条件付きで同じURLを使う */ /** メニューの「書籍一覧」=条件なし(全件)、検索ボタン=条件付きで同じURLを使う */
@GetMapping("/books") @GetMapping("/books")
public String list(@RequestParam(defaultValue = "") String nmBook, public String list(@RequestParam(defaultValue = "") String nmBook,
@RequestParam(defaultValue = "") String publisher, @RequestParam(defaultValue = "") String publisher,
@RequestParam(defaultValue = "") String note, @RequestParam(defaultValue = "") String note,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
Model model) { Model model) {
model.addAttribute("books", bookService.searchLendable(nmBook, publisher, note));
Page<BookCollection> bookPage =
bookService.searchLendable(nmBook, publisher, note, page, size);
List<Integer> pageNumbers =
IntStream.range(0, bookPage.getTotalPages()).boxed().toList();
model.addAttribute("books", bookPage);
model.addAttribute("bookPage", bookPage);
model.addAttribute("pageNumbers", pageNumbers);
// 検索条件を保持 // 検索条件を保持
model.addAttribute("nmBook", nmBook); model.addAttribute("nmBook", nmBook);
model.addAttribute("publisher", publisher); model.addAttribute("publisher", publisher);
model.addAttribute("note", note); model.addAttribute("note", note);
return "bookList"; return "bookList";
} }
} }
//package com.example.demo.controller;
//
//
//
//
//
//
//import org.springframework.stereotype.Controller;
//import org.springframework.ui.Model;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//
//import com.example.demo.service.BookService;
//
//
///** BOOK-01:書籍検索(bookList.html) */
//@Controller
//public class BookController {
// private final BookService bookService;
//
// public BookController(BookService bookService) {
// this.bookService = bookService;
// }
//
// /** メニューの「書籍一覧」=条件なし(全件)、検索ボタン=条件付きで同じURLを使う */
// @GetMapping("/books")
// public String list(@RequestParam(defaultValue = "") String nmBook,
// @RequestParam(defaultValue = "") String publisher,
// @RequestParam(defaultValue = "") String note,
// Model model) {
// model.addAttribute("books", bookService.searchLendable(nmBook, publisher, note));
// // 検索条件を保持
// model.addAttribute("nmBook", nmBook);
// model.addAttribute("publisher", publisher);
// model.addAttribute("note", note);
// return "bookList";
// }
//
//}

View File

@@ -1,6 +1,5 @@
package com.example.demo.controller; package com.example.demo.controller;
import jakarta.servlet.http.HttpSession; import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
@@ -9,15 +8,15 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import com.example.demo.common.Const; import com.example.demo.common.Const;
@Controller @Controller
public class LoginController { public class LoginController {
@GetMapping("/") @GetMapping("/")
public String root() { public String root() {
return "redirect:/login"; return "redirect:/login";
} }
@GetMapping("/login") @GetMapping("/login")
public String loginForm( public String loginForm(
HttpSession session, HttpSession session,
@@ -25,21 +24,21 @@ public class LoginController {
@RequestParam(name = "logout", required = false) String logout, @RequestParam(name = "logout", required = false) String logout,
@RequestParam(name = "remaining", required = false) Integer remaining, @RequestParam(name = "remaining", required = false) Integer remaining,
Model model) { Model model) {
// すでにログインしている場合はメニュー画面へ // すでにログインしている場合はメニュー画面へ
if (session.getAttribute(Const.SESSION_LOGIN_USER) != null) { if (session.getAttribute(Const.SESSION_LOGIN_USER) != null) {
return "redirect:/menu"; return "redirect:/menu";
} }
// ログイン失敗時のメッセージ // ログイン失敗時のメッセージ
if ("locked".equals(error)) { if ("locked".equals(error)) {
model.addAttribute( model.addAttribute(
"errorMessage", "errorMessage",
"ログインに5回連続で失敗したため、10分間アカウントをロックしました。" "ログインに5回連続で失敗したため、10分間アカウントをロックしました。"
); );
} else if ("failed".equals(error) && remaining != null) { } else if ("failed".equals(error) && remaining != null) {
if (remaining == 1) { if (remaining == 1) {
model.addAttribute( model.addAttribute(
"errorMessage", "errorMessage",
@@ -53,17 +52,17 @@ public class LoginController {
+ "回間違えると、10分間ログインできなくなります。" + "回間違えると、10分間ログインできなくなります。"
); );
} }
} else if (error != null) { } else if (error != null) {
model.addAttribute( model.addAttribute(
"errorMessage", "errorMessage",
"メールアドレスまたはパスワードが間違っています。" "メールアドレスまたはパスワードが間違っています。"
); );
} else if (logout != null) { } else if (logout != null) {
model.addAttribute("message", "ログアウトしました。"); model.addAttribute("message", "ログアウトしました。");
} }
return "login"; return "login";
} }
} }

View File

@@ -105,4 +105,5 @@ public class Employee {
public void setDateUpdate(LocalDateTime v) { public void setDateUpdate(LocalDateTime v) {
this.dateUpdate = v; this.dateUpdate = v;
} }
} }

View File

@@ -1,17 +1,18 @@
package com.example.demo.repository; package com.example.demo.repository;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import com.example.demo.entity.BookCollection; import com.example.demo.entity.BookCollection;
public interface BookCollectionRepository extends JpaRepository<BookCollection, Integer> { public interface BookCollectionRepository extends JpaRepository<BookCollection, Integer> {
/** /**
* 貸出可の蔵書を部分一致(AND)で検索する。 * 貸出可の蔵書を部分一致(AND)で検索する。
* 空文字の条件は「指定なし」。LIKE の特殊文字は呼び出し側で '!' を使ってエスケープ済み。 * 空文字の条件は「指定なし」。LIKE の特殊文字は呼び出し側で '!' を使ってエスケープ済み。
@@ -22,11 +23,13 @@ public interface BookCollectionRepository extends JpaRepository<BookCollection,
+ "and (:publisher = '' or b.publisher like concat('%', :publisher, '%') escape '!') " + "and (:publisher = '' or b.publisher like concat('%', :publisher, '%') escape '!') "
+ "and (:note = '' or b.note like concat('%', :note, '%') escape '!') " + "and (:note = '' or b.note like concat('%', :note, '%') escape '!') "
+ "order by b.idBook") + "order by b.idBook")
List<BookCollection> search(@Param("lending") String lending, Page<BookCollection> search(
@Param("nm") String nm, @Param("lending") String lending,
@Param("publisher") String publisher, @Param("nm") String nm,
@Param("note") String note); @Param("publisher") String publisher,
@Param("note") String note,
Pageable pageable);
/** /**
* 貸出フラグを from → to に更新する(現在値が from のときだけ更新)。 * 貸出フラグを from → to に更新する(現在値が from のときだけ更新)。
* 戻り値が0なら、既に他の操作で状態が変わっている(状態不整合)。 * 戻り値が0なら、既に他の操作で状態が変わっている(状態不整合)。
@@ -37,3 +40,42 @@ public interface BookCollectionRepository extends JpaRepository<BookCollection,
int updateLending(@Param("id") Integer id, @Param("from") String from, @Param("to") String to, int updateLending(@Param("id") Integer id, @Param("from") String from, @Param("to") String to,
@Param("uid") Integer uid, @Param("now") LocalDateTime now); @Param("uid") Integer uid, @Param("now") LocalDateTime now);
} }
//package com.example.demo.repository;
//
//import java.time.LocalDateTime;
//import java.util.List;
//
//import org.springframework.data.jpa.repository.JpaRepository;
//import org.springframework.data.jpa.repository.Modifying;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.query.Param;
//
//import com.example.demo.entity.BookCollection;
//
//public interface BookCollectionRepository extends JpaRepository<BookCollection, Integer> {
//
// /**
// * 貸出可の蔵書を部分一致(AND)で検索する。
// * 空文字の条件は「指定なし」。LIKE の特殊文字は呼び出し側で '!' を使ってエスケープ済み。
// */
// @Query("select b from BookCollection b "
// + "where b.flgLending = :lending "
// + "and (:nm = '' or b.nmBook like concat('%', :nm, '%') escape '!') "
// + "and (:publisher = '' or b.publisher like concat('%', :publisher, '%') escape '!') "
// + "and (:note = '' or b.note like concat('%', :note, '%') escape '!') "
// + "order by b.idBook")
// List<BookCollection> search(@Param("lending") String lending,
// @Param("nm") String nm,
// @Param("publisher") String publisher,
// @Param("note") String note);
//
// /**
// * 貸出フラグを from → to に更新する(現在値が from のときだけ更新)。
// * 戻り値が0なら、既に他の操作で状態が変わっている(状態不整合)。
// */
// @Modifying(clearAutomatically = true, flushAutomatically = true)
// @Query("update BookCollection b set b.flgLending = :to, b.idUpdate = :uid, b.dateUpdate = :now "
// + "where b.idBook = :id and b.flgLending = :from")
// int updateLending(@Param("id") Integer id, @Param("from") String from, @Param("to") String to,
// @Param("uid") Integer uid, @Param("now") LocalDateTime now);
//}

View File

@@ -10,4 +10,5 @@ public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
Optional<Employee> findByMailAddressAndFlgRetirement(String mailAddress, String flgRetirement); Optional<Employee> findByMailAddressAndFlgRetirement(String mailAddress, String flgRetirement);
Optional<Employee> findByMailAddress(String mailAddress); Optional<Employee> findByMailAddress(String mailAddress);
} }

View File

@@ -1,33 +1,67 @@
package com.example.demo.service; package com.example.demo.service;
import java.util.List; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import com.example.demo.common.Const; import com.example.demo.common.Const;
import com.example.demo.entity.BookCollection; import com.example.demo.entity.BookCollection;
import com.example.demo.repository.BookCollectionRepository; import com.example.demo.repository.BookCollectionRepository;
/** BOOK-01:書籍検索 */ /** BOOK-01:書籍検索 */
@Service @Service
public class BookService { public class BookService {
private final BookCollectionRepository bookRepository; private final BookCollectionRepository bookRepository;
public BookService(BookCollectionRepository bookRepository) { public BookService(BookCollectionRepository bookRepository) {
this.bookRepository = bookRepository; this.bookRepository = bookRepository;
} }
/** 貸出可の蔵書を検索する。全て未入力なら全件。 */ /** 貸出可の蔵書を検索する。全て未入力なら全件。 */
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<BookCollection> searchLendable(String nmBook, String publisher, String note) { public Page<BookCollection> searchLendable(String nmBook, String publisher, String note,int page, int size) {
return bookRepository.search(Const.LENDING_OK, normalize(nmBook), normalize(publisher), normalize(note)); return bookRepository.search(Const.LENDING_OK, normalize(nmBook), normalize(publisher), normalize(note),PageRequest.of(page, size));
} }
/** 前後の空白除去+LIKE特殊文字(! % _)のエスケープ(エスケープ文字は '!') */ /** 前後の空白除去+LIKE特殊文字(! % _)のエスケープ(エスケープ文字は '!') */
static String normalize(String s) { static String normalize(String s) {
if (s == null) return ""; if (s == null) return "";
return s.trim().replace("!", "!!").replace("%", "!%").replace("_", "!_"); return s.trim().replace("!", "!!").replace("%", "!%").replace("_", "!_");
} }
} }
//package com.example.demo.service;
//
//import java.util.List;
//
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import com.example.demo.common.Const;
//import com.example.demo.entity.BookCollection;
//import com.example.demo.repository.BookCollectionRepository;
//
///** BOOK-01:書籍検索 */
//@Service
//public class BookService {
// private final BookCollectionRepository bookRepository;
//
// public BookService(BookCollectionRepository bookRepository) {
// this.bookRepository = bookRepository;
// }
//
// /** 貸出可の蔵書を検索する。全て未入力なら全件。 */
// @Transactional(readOnly = true)
// public List<BookCollection> searchLendable(String nmBook, String publisher, String note) {
// return bookRepository.search(Const.LENDING_OK, normalize(nmBook), normalize(publisher), normalize(note));
// }
//
// /** 前後の空白除去+LIKE特殊文字(! % _)のエスケープ(エスケープ文字は '!') */
// static String normalize(String s) {
// if (s == null) return "";
// return s.trim().replace("!", "!!").replace("%", "!%").replace("_", "!_");
// }
//}
//

View File

@@ -1,5 +1,5 @@
package com.example.demo.service; package com.example.demo.service;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
@@ -10,28 +10,28 @@ import com.example.demo.common.LoginUser;
import com.example.demo.config.CustomUserDetails; import com.example.demo.config.CustomUserDetails;
import com.example.demo.entity.Employee; import com.example.demo.entity.Employee;
import com.example.demo.repository.EmployeeRepository; import com.example.demo.repository.EmployeeRepository;
//Spring Securityから依頼を受けて、ログインする社員情報をDBから取得 //Spring Securityから依頼を受けて、ログインする社員情報をDBから取得
@Service @Service
public class CustomUserDetailsService implements UserDetailsService { public class CustomUserDetailsService implements UserDetailsService {
private final EmployeeRepository employeeRepository; private final EmployeeRepository employeeRepository;
private final LoginAttemptService loginAttemptService; private final LoginAttemptService loginAttemptService;
public CustomUserDetailsService( public CustomUserDetailsService(
EmployeeRepository employeeRepository, EmployeeRepository employeeRepository,
LoginAttemptService loginAttemptService) { LoginAttemptService loginAttemptService) {
this.employeeRepository = employeeRepository; this.employeeRepository = employeeRepository;
this.loginAttemptService = loginAttemptService; this.loginAttemptService = loginAttemptService;
} }
@Override @Override
public UserDetails loadUserByUsername(String maillAddress) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String maillAddress) throws UsernameNotFoundException {
Employee employee = employeeRepository.findByMailAddressAndFlgRetirement(maillAddress.trim(), Const.RETIRE_NO) Employee employee = employeeRepository.findByMailAddressAndFlgRetirement(maillAddress.trim(), Const.RETIRE_NO)
.orElseThrow(() -> new UsernameNotFoundException("認証に失敗しました。")); .orElseThrow(() -> new UsernameNotFoundException("認証に失敗しました。"));
// ↑社員情報が見つからない場合は例外処理 // ↑社員情報が見つからない場合は例外処理
// 取得したEmployeeをLoginUserに変換する // 取得したEmployeeをLoginUserに変換する
LoginUser loginUser = new LoginUser( LoginUser loginUser = new LoginUser(
employee.getIdEmployee(), employee.getIdEmployee(),
@@ -39,9 +39,9 @@ public class CustomUserDetailsService implements UserDetailsService {
employee.getKnEmployee(), employee.getKnEmployee(),
employee.getMailAddress(), employee.getMailAddress(),
employee.getFlgAdmin()); employee.getFlgAdmin());
// Spring Security用の形式に変換 // Spring Security用の形式に変換
return new CustomUserDetails(loginUser, employee.getPassword(), loginAttemptService); return new CustomUserDetails(loginUser, employee.getPassword(), loginAttemptService);
} }
} }

View File

@@ -18,6 +18,9 @@ import com.example.demo.entity.Employee;
import com.example.demo.form.EmployeeForm; import com.example.demo.form.EmployeeForm;
import com.example.demo.repository.EmployeeRepository; import com.example.demo.repository.EmployeeRepository;
/** EMP-01:社員登録、EMP-02:社員編集 */ /** EMP-01:社員登録、EMP-02:社員編集 */
@Service @Service
public class EmployeeService { public class EmployeeService {
@@ -33,6 +36,7 @@ public class EmployeeService {
PasswordEncoder passwordEncoder) { PasswordEncoder passwordEncoder) {
this.employeeRepository = employeeRepository; this.employeeRepository = employeeRepository;
this.passwordEncoder = passwordEncoder; this.passwordEncoder = passwordEncoder;
} }
// ---------- 検索 ---------- // ---------- 検索 ----------

View File

@@ -1,101 +1,101 @@
package com.example.demo.service; package com.example.demo.service;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Locale; import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
// 失敗回数とロック時間を管理 // 失敗回数とロック時間を管理
@Service @Service
public class LoginAttemptService { public class LoginAttemptService {
// 最大失敗回数 // 最大失敗回数
private static final int MAX_ATTEMPTS = 5; private static final int MAX_ATTEMPTS = 5;
// ロック時間 // ロック時間
private static final int LOCK_MINUTES = 10; private static final int LOCK_MINUTES = 10;
// 失敗回数を保存 // 失敗回数を保存
private final ConcurrentMap<String, AttemptState> attempts = new ConcurrentHashMap<>(); private final ConcurrentMap<String, AttemptState> attempts = new ConcurrentHashMap<>();
public static class AttemptState { public static class AttemptState {
// 何回失敗したか // 何回失敗したか
private final int failedAttempts; private final int failedAttempts;
// いつロックを解除するか // いつロックを解除するか
private final LocalDateTime lockedUntil; private final LocalDateTime lockedUntil;
private AttemptState(int failedAttempts, LocalDateTime lockedUntil) { private AttemptState(int failedAttempts, LocalDateTime lockedUntil) {
this.failedAttempts = failedAttempts; this.failedAttempts = failedAttempts;
this.lockedUntil = lockedUntil; this.lockedUntil = lockedUntil;
} }
} }
private String normalize(String mailAddress) { private String normalize(String mailAddress) {
return mailAddress.trim().toLowerCase(Locale.ROOT); return mailAddress.trim().toLowerCase(Locale.ROOT);
} }
// ログイン失敗時 // ログイン失敗時
public void loginFailed(String mailAddress) { public void loginFailed(String mailAddress) {
String mail = normalize(mailAddress); String mail = normalize(mailAddress);
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
AttemptState current = attempts.get(mail); AttemptState current = attempts.get(mail);
// ロック中なら何もしない // ロック中なら何もしない
if (current != null && current.lockedUntil != null if (current != null && current.lockedUntil != null
&& now.isBefore(current.lockedUntil)) { && now.isBefore(current.lockedUntil)) {
return; return;
} }
// 失敗回数を数える // 失敗回数を数える
int count = (current == null || current.lockedUntil != null) int count = (current == null || current.lockedUntil != null)
? 1 ? 1
: current.failedAttempts + 1; : current.failedAttempts + 1;
// 5回失敗したら10分間ロック // 5回失敗したら10分間ロック
LocalDateTime lockTime = count >= MAX_ATTEMPTS LocalDateTime lockTime = count >= MAX_ATTEMPTS
? now.plusMinutes(LOCK_MINUTES) ? now.plusMinutes(LOCK_MINUTES)
: null; : null;
// 失敗回数とロック時間を保存 // 失敗回数とロック時間を保存
attempts.put(mail, new AttemptState(count, lockTime)); attempts.put(mail, new AttemptState(count, lockTime));
} }
// 現在ロック中かどうか判定 // 現在ロック中かどうか判定
public boolean isBlocked(String mailAddress) { public boolean isBlocked(String mailAddress) {
String mail = normalize(mailAddress); String mail = normalize(mailAddress);
AttemptState current = attempts.get(mail); AttemptState current = attempts.get(mail);
if (current == null) { if (current == null) {
return false; return false;
} }
if (current.lockedUntil == null) { if (current.lockedUntil == null) {
return false; return false;
} }
// 10分経過したらロックを解除 // 10分経過したらロックを解除
if (!LocalDateTime.now().isBefore(current.lockedUntil)) { if (!LocalDateTime.now().isBefore(current.lockedUntil)) {
attempts.remove(mail); attempts.remove(mail);
return false; return false;
} }
return true; return true;
} }
// ログイン成功時に、過去の失敗回数をきれいにリセットする // ログイン成功時に、過去の失敗回数をきれいにリセットする
public void loginSucceeded(String mailAddress) { public void loginSucceeded(String mailAddress) {
attempts.remove(normalize(mailAddress)); attempts.remove(normalize(mailAddress));
} }
public int getFailedAttempts(String mailAddress) { public int getFailedAttempts(String mailAddress) {
AttemptState state = attempts.get(normalize(mailAddress)); AttemptState state = attempts.get(normalize(mailAddress));
return state == null ? 0 : state.failedAttempts; return state == null ? 0 : state.failedAttempts;
} }
public int getRemainingAttempts(String mailAddress) { public int getRemainingAttempts(String mailAddress) {
int failed = getFailedAttempts(mailAddress); int failed = getFailedAttempts(mailAddress);
return Math.max(0, MAX_ATTEMPTS - failed); return Math.max(0, MAX_ATTEMPTS - failed);
} }
} }

View File

@@ -88,3 +88,34 @@ th
{display:block; {display:block;
margin:8px 0 margin:8px 0
} }
/* Responsive (ဖုန်းစခရင်သေးများတွင် အောက်သို့ ဆင်းသွားစေရန်) */
@media (max-width: 600px) {
.login-container-flex {
flex-direction: column;
align-items: center;
text-align: center;
}
.form-content-area {
width: 100%;
}
input[type=text], input[type=password], input[type=email] {
max-width: 100% !important;
}
}
/* ページネーション */
.page-number {
display: inline-block;
background: #eaf4f6;
color: #176a78;
border: 1px solid #d4e3e6;
border-radius: 4px;
padding: 7px 12px;
margin: 2px;
text-decoration: none;
font-size: 14px;
}
.page-number:hover {
background: #d5edf1;
}

View File

@@ -1,12 +1,12 @@
<!DOCTYPE html> <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"> <html xmlns:th="http://www.thymeleaf.org">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>書籍一覧</title> <title>書籍一覧</title>
<link rel="stylesheet" th:href="@{/css/style.css}"> <link rel="stylesheet" th:href="@{/css/style.css}">
</head> </head>
<body> <body>
<div th:replace="~{fragments/header :: header}"></div> <div th:replace="~{fragments/header :: header}"></div>
<main> <main>
@@ -26,11 +26,11 @@
</p> </p>
</form> </form>
</div> </div>
<div class="card"> <div class="card">
<h2>検索結果</h2> <h2>検索結果</h2>
<p th:if="${#lists.isEmpty(books)}">該当する書籍はありません。</p> <p th:if="${bookPage.isEmpty()}">該当する書籍はありません。</p>
<table th:unless="${#lists.isEmpty(books)}"> <table th:unless="${bookPage.isEmpty()}">
<thead> <thead>
<tr> <tr>
<th>蔵書ID</th> <th>蔵書ID</th>
@@ -60,8 +60,88 @@
</tr> </tr>
</tbody> </tbody>
</table> </table>
<a class="page-number"
th:if="${bookPage.hasPrevious()}"
th:href="@{/books(page=${bookPage.number-1}, nmBook=${nmBook}, publisher=${publisher}, note=${note})}">前へ</a>
<span th:each="pageNum : ${pageNumbers}">
<a class="page-number"
th:href="@{/books(page=${pageNum}, nmBook=${nmBook}, publisher=${publisher}, note=${note})}"
th:text="${pageNum + 1}"></a>
</span>
<a class="page-number"
th:if="${bookPage.hasNext()}"
th:href="@{/books(page=${bookPage.number+1}, nmBook=${nmBook}, publisher=${publisher}, note=${note})}">次へ</a>
</div> </div>
</main> </main>
</body> </body>
</html>
<!--<!DOCTYPE html>-->
<!--<html xmlns:th="http://www.thymeleaf.org">-->
</html> <!--<head>-->
<!-- <meta charset="UTF-8">-->
<!-- <title>書籍一覧</title>-->
<!-- <link rel="stylesheet" th:href="@{/css/style.css}">-->
<!--</head>-->
<!--<body>-->
<!-- <div th:replace="~{fragments/header :: header}"></div>-->
<!-- <main>-->
<!-- <h1>書籍一覧</h1>-->
<!-- <div class="error" th:if="${errorMessage}" th:text="${errorMessage}"></div>-->
<!-- <div class="card">-->
<!-- <form th:action="@{/books}" method="get">-->
<!-- <label for="nmBook">書籍名</label>-->
<!-- <input type="text" id="nmBook" name="nmBook" th:value="${nmBook}">-->
<!-- <label for="publisher">出版社</label>-->
<!-- <input type="text" id="publisher" name="publisher" th:value="${publisher}">-->
<!-- <label for="note">特記事項</label>-->
<!-- <input type="text" id="note" name="note" th:value="${note}">-->
<!-- <p><button type="submit">検索</button>-->
<!-- <a class="btn sub" th:href="@{/menu}">メニューに戻る</a>-->
<!-- <a class="btn" th:if="${session.loginUser.admin}" th:href="@{/admin/books/new}">書籍新規登録</a>-->
<!-- </p>-->
<!-- </form>-->
<!-- </div>-->
<!-- <div class="card">-->
<!-- <h2>検索結果</h2>-->
<!-- <p th:if="${#lists.isEmpty(books)}">該当する書籍はありません。</p>-->
<!-- <table th:unless="${#lists.isEmpty(books)}">-->
<!-- <thead>-->
<!-- <tr>-->
<!-- <th>蔵書ID</th>-->
<!-- <th>ISBN</th>-->
<!-- <th>書籍名</th>-->
<!-- <th>書籍名よみ</th>-->
<!-- <th>出版社</th>-->
<!-- <th>特記事項</th>-->
<!-- <th>操作</th>-->
<!-- </tr>-->
<!-- </thead>-->
<!-- <tbody>-->
<!-- <tr th:each="b : ${books}">-->
<!-- <td th:text="${b.idBook}"></td>-->
<!-- <td th:text="${b.isbn}"></td>-->
<!-- <td th:text="${b.nmBook}"></td>-->
<!-- <td th:text="${b.knBook}"></td>-->
<!-- <td th:text="${b.publisher}"></td>-->
<!-- <td th:text="${b.note}"></td>-->
<!-- <td>-->
<!-- 一般:貸出申請(LOAN-01) / 管理者:編集(BOOK-03) -->
<!-- <a class="btn" th:unless="${session.loginUser.admin}"-->
<!-- th:href="@{/loan/apply(idBook=${b.idBook})}">貸出申請</a>-->
<!-- <a class="btn" th:if="${session.loginUser.admin}"-->
<!-- th:href="@{/admin/books/edit(idBook=${b.idBook})}">編集</a>-->
<!-- </td>-->
<!-- </tr>-->
<!-- </tbody>-->
<!-- </table>-->
<!-- </div>-->
<!-- </main>-->
<!--</body>-->
<!--</html>-->