Commit 4ca625fa authored by saliou673's avatar saliou673
Browse files

fix possible user duplication and add version to api

parent 668415b4
{
"systemParams": "linux-x64-83",
"modulesFolders": [],
"flags": [],
"linkedModules": [],
"topLevelPatterns": [],
"lockfileEntries": {},
"files": [],
"artifacts": {}
}
\ No newline at end of file
......@@ -5,51 +5,20 @@ import com.example.server.model.user.UserEntity;
import com.example.server.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@EnableAutoConfiguration(exclude = {EmbeddedMongoAutoConfiguration.class})
@EnableMongoRepositories
@SpringBootApplication
public class ServerApplication {
@Autowired
private UserRepository repository;
@PostConstruct
public void initUsers() {
List<User> users = Stream.of(
new UserEntity("mohammed","kasmi", "kasmi", "kasmi1997", "ADMIN"),
new UserEntity("mohammed","kasmi", "user1", "pwd1", "USER"),
new UserEntity("mohammed","kasmi", "user2", "pwd2", "USER"),
new UserEntity("mohammed","kasmi", "user3", "pwd3", "USER")
).collect(Collectors.toList());
repository.saveAll(users);
}
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
@PreDestroy
public void emptyDataBase(){
repository.deleteAll();
}
// @Bean
// public WebMvcConfigurer corsConfigurer(){
// return new WebMvcConfigurer() {
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/*").allowedHeaders("*").allowedOrigins("*").allowedMethods("*")
// .allowCredentials(true);
// }
// };
// }
}
......@@ -48,13 +48,13 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
// http.cors().disable();
http.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/api/admin/**").hasRole(Const.ADMIN)
.antMatchers("/api/home").permitAll()
.antMatchers("/api/users/add").permitAll()
.antMatchers("/api/users/login").permitAll()
.antMatchers("/api/post/**").authenticated()
.antMatchers("/api/comment/**").authenticated()
.antMatchers("/api/users/all").authenticated()
.antMatchers("/api/v1/admin/**").hasRole(Const.ADMIN)
.antMatchers("/api/v1/home").permitAll()
.antMatchers("/api/v1/users/add").permitAll()
.antMatchers("/api/v1/users/login").permitAll()
.antMatchers("/api/v1/post/**").authenticated()
.antMatchers("/api/v1/comment/**").authenticated()
.antMatchers("/api/v1/users/all").authenticated()
.and().exceptionHandling().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
......
......@@ -24,7 +24,7 @@ import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/post")
@RequestMapping("/posts")
public class PostController {
private final PostService postService;
......
......@@ -7,6 +7,8 @@ import com.example.server.services.user.UserService;
import com.example.server.utils.JwtUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -18,7 +20,7 @@ import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("api/users")
@RequestMapping("/users")
public class UserController {
private final UserService userService;
......@@ -29,6 +31,10 @@ public class UserController {
@PostMapping()
public ResponseEntity<User> add(@RequestBody UserEntity user) throws JsonProcessingException {
Logger logger = LoggerFactory.getLogger(UserController.class);
if (user != null && userService.getByUsername(user.getUserName()) != null) {
return ResponseEntity.badRequest().build();
}
return new ResponseEntity<>(userService.add(user), HttpStatus.CREATED);
}
......@@ -41,7 +47,6 @@ public class UserController {
} catch (Exception ex) {
throw new Exception("invalid username/password");
}
System.out.println("Token generated:: " + jwtUtil.generateToken(authRequest.getUserName()));
return jwtUtil.generateToken(authRequest.getUserName());
}
......@@ -61,9 +66,8 @@ public class UserController {
return new ResponseEntity<>("Deleted successfully !", HttpStatus.OK);
}
@GetMapping("/all")
@GetMapping()
public ResponseEntity<List<User>> getAllUsers() {
System.out.println("get all users method is called...");
return new ResponseEntity<>(userService.findAll(), HttpStatus.OK);
}
......
......@@ -14,5 +14,5 @@ public interface UserRepository extends MongoRepository<User, String> {
UserEntity getUserById(String id);
UserEntity getUserEntityByUserName(String username);
UserEntity findByUserName(String userName);
}
......@@ -17,7 +17,7 @@ public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = repository.getUserEntityByUserName(username);
User user = repository.findByUserName(username);
return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), new ArrayList<>());
}
}
......@@ -13,4 +13,5 @@ public interface UserService {
List<User> findAll();
void deleteById(String id);
void deleteAll();
UserEntity getByUsername(String username);
}
......@@ -56,4 +56,9 @@ public class UserServiceImplement implements UserService{
repository.deleteAll();
}
}
@Override
public UserEntity getByUsername(String username) {
return repository.findByUserName(username);
}
}
server.port = 8000
server.servlet.context-path=/api/v1
#spring.rsocket.server.port = 8000
#spring.data.mongodb.uri=mongodb+srv://mdiallo:mdiallo@cluster0.eagd9.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
#spring.data.mongodb.database=middleware
spring.data.mongodb.uri=mongodb://localhost:27017/middleware
spring.data.mongodb.database=middleware
spring.data.mongodb.uri=mongodb://localhost:27017
spring.datasource.username=mdiallo
spring.datasource.password=mdiallo
......@@ -14,7 +14,7 @@ import {Global} from "../global-classes/global";
export class LoginComponent implements OnInit {
loginForm: any;
token: string = "";
baseUrl: string = "http://127.0.0.1:8000/api/users";
baseUrl: string = "http://127.0.0.1:8000/api/v1/users";
constructor(private jwtClientService: JwtClientService,
private fb: FormBuilder,
......
......@@ -11,7 +11,7 @@ export class JwtClientService {
public static isAuth: boolean = false;
public static currentToken : string = "";
baseUrl: string = "http://127.0.0.1:8000/api/users";
baseUrl: string = "http://127.0.0.1:8000/api/v1/users";
constructor(private http: HttpClient,
private cookie: CookieService) {
......@@ -38,7 +38,7 @@ export class JwtClientService {
// get list of users when user is authenticated...
const headers = new HttpHeaders();
headers.set('Authorization', tokenStr);
return this.http.get(this.baseUrl + "/all", {headers, responseType: "text" as 'json'});
return this.http.get(this.baseUrl , {headers, responseType: "text" as 'json'});
}
public connect(userToken: string) {
......
......@@ -28,10 +28,13 @@ export class SignupComponent implements OnInit {
role: 'USER'
};
//submit data
this.http.post("http://127.0.0.1:8000/api/users", data).subscribe(response => {
this.http.post("http://127.0.0.1:8000/api/v1/users", data).subscribe(response => {
this.toastr.success("Compte crée avec succès");
setTimeout(()=>{}, 2000);
this.router.navigate(['/login'])
},
error => {
this.toastr.error("Ce nom d'utilisateur n'est pas disponible.");
})
}
......
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment