diff options
| author | realtradam <[email protected]> | 2024-07-27 02:00:57 -0400 |
|---|---|---|
| committer | realtradam <[email protected]> | 2024-07-27 02:00:57 -0400 |
| commit | de3d80ce3ea20a869d700c3238020d44059de099 (patch) | |
| tree | ef849326ea4922530990d5dc29cb8ff3532e82fe /backend/src/main/java/com | |
| parent | 6b342f97f6a605b7e1fe34584abbbf962ca39b7c (diff) | |
| download | spring-blog-de3d80ce3ea20a869d700c3238020d44059de099.tar.gz spring-blog-de3d80ce3ea20a869d700c3238020d44059de099.zip | |
working login and auth
Diffstat (limited to 'backend/src/main/java/com')
8 files changed, 75 insertions, 25 deletions
diff --git a/backend/src/main/java/com/blog/web/controllers/ArticleController.java b/backend/src/main/java/com/blog/web/controllers/ArticleController.java index 7ffa2fe..ec8af85 100644 --- a/backend/src/main/java/com/blog/web/controllers/ArticleController.java +++ b/backend/src/main/java/com/blog/web/controllers/ArticleController.java @@ -7,16 +7,14 @@ import com.blog.web.models.UserEntity; import com.blog.web.services.ArticleService; import com.blog.web.services.UserService; import jakarta.validation.Valid; -import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.HashSet; -import java.util.List; -@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true") +@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true", allowedHeaders = "*") @RestController @RequestMapping("/api/v1") public class ArticleController { @@ -31,7 +29,7 @@ public class ArticleController { @GetMapping("/get") public Article getMethod() { return new Article( - 5, + 5L, "blah", "blah", "blah", @@ -42,12 +40,8 @@ public class ArticleController { } @GetMapping("/articles") - public HashSet<ArticlePublicDto> listArticles(Model model) { + public HashSet<ArticlePublicDto> listArticles() { HashSet<ArticlePublicDto> articles = new HashSet<ArticlePublicDto>(articleService.findAllArticles()); - //UserEntity user = userService.getLoggedInUser().orElse(new UserEntity()); - //model.addAttribute("user", user); - //model.addAttribute("articles", articles); - //return "index"; return articles; } @@ -68,20 +62,18 @@ public class ArticleController { return "articles/new"; }*/ - @PostMapping("/articles/new") - public String saveArticle(@Valid @ModelAttribute("article") ArticleDto articleDto, BindingResult result, Model model) { + @PostMapping("/article/new") + public String saveArticle(@Valid @ModelAttribute("article") ArticleDto articleDto, BindingResult result) { // if non-authenticated in user tries to create an article // redirect them to login page UserEntity user = userService.getLoggedInUser().orElse(null); if (user == null) { - return "redirect:/userlogin"; - } else if (result.hasErrors()) { - model.addAttribute("article", articleDto); - return "articles/new"; - } else { + return "redirect:/login"; + } else if (!result.hasErrors()) { articleService.saveArticle(articleDto); - return "redirect:/articles"; + return "redirect:/"; } + return ""; } @GetMapping("/articles/delete/{articleId}") diff --git a/backend/src/main/java/com/blog/web/controllers/AuthController.java b/backend/src/main/java/com/blog/web/controllers/AuthController.java index a870086..4da346b 100644 --- a/backend/src/main/java/com/blog/web/controllers/AuthController.java +++ b/backend/src/main/java/com/blog/web/controllers/AuthController.java @@ -1,15 +1,15 @@ package com.blog.web.controllers; import com.blog.web.dto.RegistrationDto; +import com.blog.web.dto.UserPublicDto; import com.blog.web.models.UserEntity; import com.blog.web.services.UserService; import jakarta.validation.Valid; import org.apache.commons.lang3.StringUtils; -import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; -@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true") +@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true", allowedHeaders = "*") @RestController @RequestMapping("/api/v1") public class AuthController { @@ -37,4 +37,10 @@ public class AuthController { } return user; } + + @GetMapping("/profile") + public UserPublicDto profile() { + final UserEntity user = userService.getLoggedInUser().orElse(null); + return new UserPublicDto(user); + } } diff --git a/backend/src/main/java/com/blog/web/dto/ArticleDto.java b/backend/src/main/java/com/blog/web/dto/ArticleDto.java index d275f3b..beede12 100644 --- a/backend/src/main/java/com/blog/web/dto/ArticleDto.java +++ b/backend/src/main/java/com/blog/web/dto/ArticleDto.java @@ -110,5 +110,7 @@ public class ArticleDto { this.createdBy = createdBy; } - public String getUsername() { return createdBy.getUsername(); } + public String getUsername() { + return createdBy.getUsername(); + } } diff --git a/backend/src/main/java/com/blog/web/dto/ArticlePublicDto.java b/backend/src/main/java/com/blog/web/dto/ArticlePublicDto.java index 3ced6d2..ecf27eb 100644 --- a/backend/src/main/java/com/blog/web/dto/ArticlePublicDto.java +++ b/backend/src/main/java/com/blog/web/dto/ArticlePublicDto.java @@ -50,7 +50,7 @@ public class ArticlePublicDto { return title; } - public void setTitle( String title) { + public void setTitle(String title) { this.title = title; } @@ -66,7 +66,7 @@ public class ArticlePublicDto { return content; } - public void setContent( String content) { + public void setContent(String content) { this.content = content; } diff --git a/backend/src/main/java/com/blog/web/dto/UserPublicDto.java b/backend/src/main/java/com/blog/web/dto/UserPublicDto.java new file mode 100644 index 0000000..547a7b2 --- /dev/null +++ b/backend/src/main/java/com/blog/web/dto/UserPublicDto.java @@ -0,0 +1,22 @@ +package com.blog.web.dto; + +import com.blog.web.models.UserEntity; + +public class UserPublicDto { + private String username; + + public UserPublicDto() { + } + + public UserPublicDto(String username) { + this.username = username; + } + + public UserPublicDto(UserEntity user) { + this.username = user.getUsername(); + } + + public String getUsername() { + return username; + } +} diff --git a/backend/src/main/java/com/blog/web/models/Article.java b/backend/src/main/java/com/blog/web/models/Article.java index b54907a..78ad668 100644 --- a/backend/src/main/java/com/blog/web/models/Article.java +++ b/backend/src/main/java/com/blog/web/models/Article.java @@ -11,7 +11,7 @@ import java.time.LocalDateTime; public class Article { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; + private Long id; private String title; private String photoUrl; private String content; @@ -23,7 +23,7 @@ public class Article { @JoinColumn(name = "created_by", nullable = false) private UserEntity createdBy; - public Article(long id, String title, String photoUrl, String content, UserEntity createdBy, LocalDateTime createdOn, LocalDateTime updatedOn) { + public Article(Long id, String title, String photoUrl, String content, UserEntity createdBy, LocalDateTime createdOn, LocalDateTime updatedOn) { this.id = id; this.title = title; this.photoUrl = photoUrl; diff --git a/backend/src/main/java/com/blog/web/security/CorsConfig.java b/backend/src/main/java/com/blog/web/security/CorsConfig.java new file mode 100644 index 0000000..55db15a --- /dev/null +++ b/backend/src/main/java/com/blog/web/security/CorsConfig.java @@ -0,0 +1,21 @@ +package com.blog.web.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class CorsConfig { + + // Configures CORS for the application + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**").allowedOrigins("http://localhost:5173").allowedMethods("GET", "POST", "PUT", "DELETE").allowedHeaders("*").allowCredentials(true); + } + }; + } +} diff --git a/backend/src/main/java/com/blog/web/security/SecurityConfig.java b/backend/src/main/java/com/blog/web/security/SecurityConfig.java index 2be6909..e562041 100644 --- a/backend/src/main/java/com/blog/web/security/SecurityConfig.java +++ b/backend/src/main/java/com/blog/web/security/SecurityConfig.java @@ -2,6 +2,7 @@ package com.blog.web.security; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -9,6 +10,11 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import java.util.Arrays; @Configuration @EnableWebSecurity @@ -28,11 +34,12 @@ public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // disabling csrf leaves us vulnerable, in a real production app do not do this - http.csrf(c -> c.disable()).cors(c -> c.disable()).authorizeHttpRequests(auths -> auths.anyRequest().permitAll()).formLogin(form -> form.loginPage("/login").usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/").loginProcessingUrl("/userlogin").failureUrl("/userlogin?error=true").permitAll()).logout(logout -> logout.logoutUrl("/logout").logoutSuccessUrl("/articles")); + http.csrf(c -> c.disable()).cors(Customizer.withDefaults()).authorizeHttpRequests(auths -> auths.anyRequest().permitAll()).formLogin(form -> form.loginPage("/api/v1/login").usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/").loginProcessingUrl("/api/v1/login").failureUrl("/login?error=true").permitAll()).logout(logout -> logout.logoutUrl("/api/v1/logout").logoutSuccessUrl("/articles")); return http.build(); } public void configure(AuthenticationManagerBuilder builder) throws Exception { builder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } + } |
