Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Register API #28

Merged
merged 3 commits into from
Apr 2, 2024
Merged
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
Expand Up @@ -2,8 +2,10 @@

import com.example.BloggerApp.service.impl.CustomUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
Expand All @@ -13,6 +15,12 @@
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.List;

@Configuration
@EnableWebSecurity
Expand All @@ -33,7 +41,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers(AppConstants.PUBLIC_URLS).permitAll().anyRequest().authenticated().and().exceptionHandling().authenticationEntryPoint(this.jwtAuthenticationEntryPoint).and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.cors().and().csrf().disable().authorizeRequests().antMatchers(AppConstants.PUBLIC_URLS).permitAll().
antMatchers(HttpMethod.GET).permitAll().anyRequest().authenticated().and().exceptionHandling().authenticationEntryPoint(this.jwtAuthenticationEntryPoint).and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
Expand All @@ -48,4 +57,21 @@ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public FilterRegistrationBean coresFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.addAllowedOriginPattern("*");
configuration.addAllowedMethod("POST");
configuration.addAllowedMethod("GET");
configuration.addAllowedHeader("Authorization");
configuration.addAllowedHeader("Accept");
configuration.addAllowedHeader("Content-Type");

source.registerCorsConfiguration("/**", configuration);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(-110);
return bean;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.example.BloggerApp.http.request.CreateBlogRequest;
import com.example.BloggerApp.http.request.TagRequest;
import com.example.BloggerApp.http.request.UpdateBlogRequest;
import com.example.BloggerApp.http.response.GetBlogFeedResponse;
import com.example.BloggerApp.http.response.GetBlogResponse;
import com.example.BloggerApp.http.response.GetTagResponse;
import com.example.BloggerApp.models.BlogEntity;
Expand All @@ -11,6 +12,7 @@
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
Expand All @@ -36,12 +38,14 @@ public BlogController(BlogServiceImpl blogServiceImpl){
this.blogServiceImpl = blogServiceImpl;
}

@CrossOrigin(origins = "http://localhost:3000",allowedHeaders = "*")
@PostMapping("/create/user/{user_id}/category/{category_id}")
public ResponseEntity<String> createBlog(@RequestBody CreateBlogRequest createBlogRequest,@PathVariable("user_id") long userId,@PathVariable("category_id") long categoryId){
blogServiceImpl.addBlog(fromBlogRequestToBlogModel.apply(createBlogRequest),userId,categoryId);
return new ResponseEntity<>("Blog Created",HttpStatus.CREATED);
}

@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/get-all")
public ResponseEntity<List<GetBlogResponse>> getAllBlogs(
@RequestParam(value = "pageNumber",defaultValue = "0",required = false) Integer pageNumber,
Expand All @@ -52,6 +56,16 @@ public ResponseEntity<List<GetBlogResponse>> getAllBlogs(
return new ResponseEntity<>(blogEntityList.stream().map(fromBlogModelToBlogResponse).collect(Collectors.toList()), HttpStatus.OK);
}

@GetMapping("/get-all-info")
public ResponseEntity<List<GetBlogFeedResponse>> getAllBlogsWithUserAndCategoryDetails(
@RequestParam(value = "pageNumber",defaultValue = "0",required = false) Integer pageNumber,
@RequestParam(value = "limit",defaultValue = "2",required = false) Integer limit
){
return new ResponseEntity<>(blogServiceImpl.getBlogWithUserAndCategoryDetails(pageNumber,limit), HttpStatus.OK);
}



@GetMapping("/get/{id}")
public ResponseEntity<GetBlogResponse> getBlogById(@PathVariable("id") long id){
BlogEntity blogEntity = blogServiceImpl.getBlogById(id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand Down Expand Up @@ -38,6 +39,7 @@ public ResponseEntity<GetCategoryResponse> getCategoryById(@PathVariable("id") l
return new ResponseEntity<>(categoryServiceImpl.getCategoryById(id), HttpStatus.OK);
}

@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/get-all")
public ResponseEntity<List<GetCategoryResponse>> getCategoryList(
@RequestParam(value = "pageNumber",defaultValue = "0",required = false) Integer pageNumber,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package com.example.BloggerApp.controller;

import com.example.BloggerApp.configurations.JWTTokenHelper;
import com.example.BloggerApp.http.request.CreateUser;
import com.example.BloggerApp.http.request.LoginRequest;
import com.example.BloggerApp.http.response.GetUserResponse;
import com.example.BloggerApp.http.response.LoginResponse;
import com.example.BloggerApp.models.UserEntity;
import com.example.BloggerApp.service.UserService;
import com.example.BloggerApp.service.impl.CustomUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
Expand All @@ -29,19 +33,36 @@ public class LoginController {
@Autowired
private CustomUserDetailService customUserDetailService;

@Autowired
private UserService userService;

@CrossOrigin(origins = "http://localhost:3000")
@PostMapping("/login")
public ResponseEntity<LoginResponse> createToken(@RequestBody LoginRequest loginRequest){
this.authenticate(loginRequest.getUsername(),loginRequest.getPassword());
UserDetails userDetails = customUserDetailService.loadUserByUsername(loginRequest.getUsername());

String token = jwtTokenHelper.generateToken(userDetails);

UserEntity userEntity = userService.getUserEntityByUsername(loginRequest.getUsername());
LoginResponse loginResponse = new LoginResponse();
loginResponse.setToken(token);
loginResponse.setUserId(userEntity.getId());
loginResponse.setUsername(userEntity.getUsername());
loginResponse.setEmail(userEntity.getEmail());
loginResponse.setImage(userEntity.getImage());
loginResponse.setCreatedDate(userEntity.getCreatedDate());
loginResponse.setAbout(userEntity.getBio());
loginResponse.setRoles(userEntity.getRoles());
return new ResponseEntity<>(loginResponse, HttpStatus.CREATED);
}

@CrossOrigin(origins = "http://localhost:3000")
@PostMapping("/register")
public ResponseEntity<GetUserResponse> registerUser(@RequestBody CreateUser createUser){
GetUserResponse getUserResponse = userService.registerUser(createUser);
return new ResponseEntity<>(getUserResponse,HttpStatus.CREATED);
}

private void authenticate(String email, String password) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(email,password);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,6 @@ public ResponseEntity<String> deleteUserById(@PathVariable("id") Long id){
return new ResponseEntity<>("User Deleted",HttpStatus.ACCEPTED);
}

@PostMapping("/register")
public ResponseEntity<GetUserResponse> registerUser(@RequestBody CreateUser createUser){
GetUserResponse getUserResponse = userServiceImpl.registerUser(createUser);
return new ResponseEntity<>(getUserResponse,HttpStatus.CREATED);
}

private final Function<UpdateUser,UserEntity> fromUpdateUserRequestToUserEntity =
updateUser -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.example.BloggerApp.http.response;

import com.example.BloggerApp.models.Comment;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Setter
@AllArgsConstructor
@NoArgsConstructor
public class GetBlogFeedResponse {
@JsonProperty("id")
private Long id;

@JsonProperty("title")
private String title;

@JsonProperty("subtitle")
private String subtitle;

@JsonProperty("getTagResponses")
private List<GetTagResponse> getTagResponses;

@JsonProperty("content")
private String content;

@JsonProperty("createdAt")
private String createdAt;

@JsonProperty("cover")
private String imageCover;

@JsonProperty("category")
private String category;

@JsonProperty("authorName")
private String authorName;

@JsonProperty("authorAvatar")
private String authorAvatar;

@JsonProperty("comments")
public Set<Comment> comments = new HashSet<>();

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.BloggerApp.http.response;

import com.example.BloggerApp.models.Roles;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
Expand All @@ -22,6 +23,7 @@ public class GetUserResponse {

public String email;

@JsonIgnore
public String password;

public String image;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,37 @@
package com.example.BloggerApp.http.response;

import com.example.BloggerApp.models.Roles;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Data
public class LoginResponse {

@JsonProperty("token")
private String token;

@JsonProperty("userId")
public Long userId;

@JsonProperty("username")
public String username;

@JsonProperty("email")
public String email;

@JsonProperty("image")
public String image;

@JsonProperty("about")
public String about;

@JsonProperty("createdDate")
public Date createdDate;

@JsonProperty("roles")
public Set<Roles> roles = new HashSet<>();
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.example.BloggerApp.models.BlogEntity;
import com.example.BloggerApp.models.CategoryEntity;
import com.example.BloggerApp.models.UserEntity;
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.Modifying;
import org.springframework.data.jpa.repository.Query;
Expand All @@ -11,6 +13,7 @@
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Repository
public interface BlogRepository extends JpaRepository<BlogEntity,Long> {
Expand All @@ -26,4 +29,8 @@ public interface BlogRepository extends JpaRepository<BlogEntity,Long> {
List<BlogEntity> getBlogByCategoryEntity(CategoryEntity categoryEntity);

List<BlogEntity> getBlogByUserEntity(UserEntity userEntity);

@Query(value = "SELECT mywork.blog_entity.id,mywork.blog_entity.title, mywork.category_entity.title as category,mywork.blog_entity.body,mywork.blog_entity.created_at,mywork.blog_entity.image_cover as cover,mywork.user_entity.image,mywork.user_entity.username from mywork.blog_entity inner join mywork.user_entity on mywork.blog_entity.user_entity_id=mywork.user_entity.id inner join mywork.category_entity on mywork.blog_entity.category_entity_id=mywork.category_entity.id ORDER BY mywork.blog_entity.id limit ?1 offset ?2 ;",
countQuery = "select count(*) from mywork.blog_entity;",nativeQuery = true)
List<Map<String,Object>> findAllBlogEntitywithUserDetails(long limit,long offset);
}
6 changes: 6 additions & 0 deletions src/main/java/com/example/BloggerApp/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.example.BloggerApp.service;

import com.example.BloggerApp.http.request.CreateUser;
import com.example.BloggerApp.http.response.GetUserResponse;
import com.example.BloggerApp.models.UserEntity;

import java.util.List;
Expand All @@ -16,5 +18,9 @@ public interface UserService {

void deleteUseryId(Long id);

GetUserResponse registerUser(CreateUser createUser);

UserEntity getUserEntityByUsername(String username);


}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.example.BloggerApp.http.request.TagRequest;
import com.example.BloggerApp.http.request.UpdateBlogRequest;
import com.example.BloggerApp.http.response.GetBlogFeedResponse;
import com.example.BloggerApp.http.response.GetBlogResponse;
import com.example.BloggerApp.models.BlogEntity;
import com.example.BloggerApp.models.CategoryEntity;
import com.example.BloggerApp.models.TagEntity;
Expand All @@ -15,7 +17,13 @@
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -51,6 +59,12 @@ public BlogEntity getBlogById(long id){
return blogRepository.getById(id);
}

public List<GetBlogFeedResponse> getBlogWithUserAndCategoryDetails(int pageNumber,int limit){
List<Map<String,Object>> result=blogRepository.findAllBlogEntitywithUserDetails(limit,pageNumber);
List<GetBlogFeedResponse> getBlogFeedResponseList = result.stream().map(fromMapToFeedResponse).collect(Collectors.toList());
return getBlogFeedResponseList;
}

public BlogEntity deleteBlogById(long id){
return blogRepository.deleteById(id);
}
Expand Down Expand Up @@ -89,4 +103,21 @@ public List<BlogEntity> getBlogEntitiesByUserId(Long userId) {
tagEntity.setTag(tagRequest.getTag());
return tagEntity;
};

private final Function<Map<String,Object>, GetBlogFeedResponse> fromMapToFeedResponse =
map ->{
GetBlogFeedResponse getBlogFeedResponse = new GetBlogFeedResponse();
BigInteger id = (BigInteger) map.get("id");
getBlogFeedResponse.setId(id.longValue());
getBlogFeedResponse.setTitle((String) map.get("title"));
getBlogFeedResponse.setContent((String) map.get("body"));
getBlogFeedResponse.setImageCover((String) map.get("cover"));
getBlogFeedResponse.setCategory((String) map.get("category"));
getBlogFeedResponse.setAuthorName((String) map.get("username"));
getBlogFeedResponse.setAuthorAvatar((String) map.get("image"));
Timestamp timestamp = (Timestamp) map.get("created_at");
LocalDate localDate = timestamp.toLocalDateTime().toLocalDate();
getBlogFeedResponse.setCreatedAt(""+localDate.getMonth()+" ,"+localDate.getDayOfMonth()+" "+localDate.getYear());
return getBlogFeedResponse;
};
}
Loading
Loading