diff --git a/pom.xml b/pom.xml
index dfd9d36..eb483db 100644
--- a/pom.xml
+++ b/pom.xml
@@ -28,7 +28,7 @@
17
- 0.12.5
+ 0.11.5
diff --git a/src/main/java/com/example/gecekodubackend/business/abstracts/EventService.java b/src/main/java/com/example/gecekodubackend/business/abstracts/EventService.java
index cae2dd2..dae3677 100644
--- a/src/main/java/com/example/gecekodubackend/business/abstracts/EventService.java
+++ b/src/main/java/com/example/gecekodubackend/business/abstracts/EventService.java
@@ -17,5 +17,7 @@ public interface EventService {
Result deleteEvent(int id);
+ // Result addUserToEvent(int eventId, int userId);
+
//DataResult> getAllEventsWithDto();
}
\ No newline at end of file
diff --git a/src/main/java/com/example/gecekodubackend/business/abstracts/UserService.java b/src/main/java/com/example/gecekodubackend/business/abstracts/UserService.java
index 80c214b..9065854 100644
--- a/src/main/java/com/example/gecekodubackend/business/abstracts/UserService.java
+++ b/src/main/java/com/example/gecekodubackend/business/abstracts/UserService.java
@@ -4,14 +4,28 @@
import com.example.gecekodubackend.core.utilities.results.DataResult;
import com.example.gecekodubackend.core.utilities.results.Result;
import com.example.gecekodubackend.core.entities.*;
+import org.springframework.security.core.userdetails.UserDetailsService;
import java.util.List;
-public interface UserService {
+public interface UserService extends UserDetailsService {
DataResult> getAllUsers();
+
DataResult getUserById(int id);
+
Result addUser(User user);
+
Result updateUser(GetUserDto userDto, int id);
+
Result deleteUser(int id);
- DataResult getUserByEmail(String email);
+
+ DataResult getUserByEmail(String email);
+
+ DataResult getUserEntityByEmail(String email);
+
+ DataResult getUserEntityById(int id);
+
+ Result addUserToEvent(int userId, int eventId);
+
+
}
diff --git a/src/main/java/com/example/gecekodubackend/business/abstracts/WorkshopService.java b/src/main/java/com/example/gecekodubackend/business/abstracts/WorkshopService.java
index 40688e4..fd31ce4 100644
--- a/src/main/java/com/example/gecekodubackend/business/abstracts/WorkshopService.java
+++ b/src/main/java/com/example/gecekodubackend/business/abstracts/WorkshopService.java
@@ -8,8 +8,14 @@
public interface WorkshopService {
DataResult> getAllWorkshops();
+
DataResult getWorkshopById(int id);
+
Result addWorkshop(Workshop workshop);
+
Result updateWorkshop(Workshop workshop,int id);
+
Result deleteWorkshop(int id);
+
+
}
diff --git a/src/main/java/com/example/gecekodubackend/business/concretes/EventManager.java b/src/main/java/com/example/gecekodubackend/business/concretes/EventManager.java
index b67aac2..e3ed0b4 100644
--- a/src/main/java/com/example/gecekodubackend/business/concretes/EventManager.java
+++ b/src/main/java/com/example/gecekodubackend/business/concretes/EventManager.java
@@ -1,7 +1,9 @@
package com.example.gecekodubackend.business.concretes;
import com.example.gecekodubackend.business.abstracts.EventService;
+import com.example.gecekodubackend.business.abstracts.UserService;
import com.example.gecekodubackend.business.constants.EventMessages;
+import com.example.gecekodubackend.business.constants.UserMessages;
import com.example.gecekodubackend.core.utilities.results.*;
import com.example.gecekodubackend.dataAccess.abstracts.EventDao;
import com.example.gecekodubackend.entity.concretes.Event;
@@ -14,12 +16,15 @@
@Service
public class EventManager implements EventService {
- private final EventDao eventDao;
+ private final EventDao eventDao;
+
@Autowired
public EventManager(EventDao eventDao) {
super();
this.eventDao = eventDao;
+
+
}
/*
@@ -92,6 +97,8 @@ public Result deleteEvent(int id) {
return new SuccessResult(EventMessages.eventDeletedSuccessfully);
}
+
+
public Result checkIfEventExists(int id){
Optional result = eventDao.findById(id);
diff --git a/src/main/java/com/example/gecekodubackend/business/concretes/UserManager.java b/src/main/java/com/example/gecekodubackend/business/concretes/UserManager.java
index 30f1b36..5430ecf 100644
--- a/src/main/java/com/example/gecekodubackend/business/concretes/UserManager.java
+++ b/src/main/java/com/example/gecekodubackend/business/concretes/UserManager.java
@@ -1,5 +1,6 @@
package com.example.gecekodubackend.business.concretes;
+import com.example.gecekodubackend.business.abstracts.EventService;
import com.example.gecekodubackend.business.abstracts.UserService;
import com.example.gecekodubackend.business.constants.UserMessages;
import com.example.gecekodubackend.core.dtos.GetUserDto;
@@ -8,6 +9,9 @@
import com.example.gecekodubackend.core.entities.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@@ -16,29 +20,36 @@
@Service
public class UserManager implements UserService {
+
private final UserDao userDao;
+ private EventService eventService;
+
+
+ private BCryptPasswordEncoder passwordEncoder;
@Autowired
- public UserManager(UserDao userDao){
+ public UserManager(UserDao userDao, BCryptPasswordEncoder passwordEncoder, EventService eventService) {
super();
this.userDao = userDao;
+ this.passwordEncoder = passwordEncoder;
+ this.eventService = eventService;
}
@Override
public DataResult> getAllUsers() {
- List userDtoList = new ArrayList<>();
List users = userDao.findAll();
- if (users.isEmpty()){
+ if(users.isEmpty()){
return new ErrorDataResult<>(UserMessages.usersNotFound);
}
- // against to solid? needs some refactor
- for(User user : userDtoList){
+ List userDtoList = new ArrayList<>();
+ for(User user : users){
GetUserDto userDto = new GetUserDto();
BeanUtils.copyProperties(user, userDto);
userDtoList.add(userDto);
}
+
return new SuccessDataResult<>(userDtoList, UserMessages.usersBroughtSuccessfully);
}
@@ -50,7 +61,9 @@ public DataResult getUserById(int id) {
return new ErrorDataResult<>(UserMessages.userNotFound);
}
- return new SuccessDataResult<>(result.get(),UserMessages.userBroughtSuccessfully);
+ GetUserDto userDto = new GetUserDto();
+ BeanUtils.copyProperties(result.get(), userDto);
+ return new SuccessDataResult<>(userDto, UserMessages.userBroughtSuccessfully);
}
@Override
@@ -66,8 +79,50 @@ public Result deleteUser(int id) {
}
@Override
- public DataResult getUserByEmail(String email) {
- return null;
+ public DataResult getUserByEmail(String email) {
+ var result = userDao.getUserByEmail(email);
+
+ if(result == null){
+ return new ErrorDataResult<>(UserMessages.userNotFound);
+ }
+
+ GetUserDto userDto = new GetUserDto();
+ BeanUtils.copyProperties(result, userDto);
+ return new SuccessDataResult<>(userDto, UserMessages.userBroughtSuccessfully);
+ }
+
+ @Override
+ public DataResult getUserEntityByEmail(String email) {
+ var result = userDao.getUserByEmail(email);
+
+ if(result == null){
+ return new ErrorDataResult<>(UserMessages.userNotFound);
+ }
+
+ return new SuccessDataResult<>(result, UserMessages.userBroughtSuccessfully);
+ }
+
+ @Override
+ public DataResult getUserEntityById(int id) {
+ var result = userDao.findById(id);
+
+ if(result.isEmpty()){
+ return new ErrorDataResult<>(UserMessages.userNotFound);
+ }
+
+ return new SuccessDataResult<>(result.get(), UserMessages.userBroughtSuccessfully);
+ }
+
+ @Override
+ public Result addUserToEvent(int userId, int eventId) {
+
+ var userResult = getUserEntityById(userId);
+ var eventResult = eventService.getEventById(eventId);
+
+ userResult.getData().getEvents().add(eventResult.getData());
+ userDao.save(userResult.getData());
+
+ return new SuccessResult(UserMessages.userAddedToEventSuccessfully);
}
@Override
@@ -78,17 +133,27 @@ public Result updateUser(GetUserDto userDto, int id) {
return new ErrorResult(UserMessages.userNotFound);
}
- DataResult userToUpdate = getUserById(id);
- userToUpdate.getData().setFirstName(userDto.getFirstName());
- userToUpdate.getData().setLastName(userDto.getLastName());
- userToUpdate.getData().setEmail(userDto.getEmail());
+ var userToUpdate = userDao.findById(id).get();
+ userToUpdate.setFirstName(userDto.getFirstName());
+ userToUpdate.setLastName(userDto.getLastName());
+ userToUpdate.setEmail(userDto.getEmail());
+
userDao.save(userToUpdate);
return new SuccessResult(UserMessages.userUpdatedSuccessfully);
}
@Override
public Result addUser(User user) {
- return null;
+
+ user.setPassword(passwordEncoder.encode(user.getPassword()));
+
+ if(userDao.existsByEmail(user.getEmail())){
+ return new ErrorResult(UserMessages.emailAlreadyExists);
+ }
+
+
+ userDao.save(user);
+ return new SuccessResult(UserMessages.userAddedSuccessfully);
}
public Result checkIfUserExists(int id){
@@ -100,4 +165,10 @@ public Result checkIfUserExists(int id){
return new ErrorResult(UserMessages.userNotFound);
}
+ @Override
+
+ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+ var user = getUserEntityByEmail(username).getData();
+ return user;
+ }
}
diff --git a/src/main/java/com/example/gecekodubackend/business/constants/EventMessages.java b/src/main/java/com/example/gecekodubackend/business/constants/EventMessages.java
index 66531e7..a2a4471 100644
--- a/src/main/java/com/example/gecekodubackend/business/constants/EventMessages.java
+++ b/src/main/java/com/example/gecekodubackend/business/constants/EventMessages.java
@@ -10,4 +10,5 @@ public class EventMessages {
public static String eventsAlreadyExists = "Bu etkinlik mevcut!";
public static String eventUpdatedSuccessfully = "Etkinlik başarıyla güncellendi!";
public static String eventDeletedSuccessfully = "Etkinlik başarıyla silindi!";
+ public static String userAddedToEventSuccessfully = "Kullanıcı etkinliğe başarıyla eklendi!";
}
diff --git a/src/main/java/com/example/gecekodubackend/business/constants/UserMessages.java b/src/main/java/com/example/gecekodubackend/business/constants/UserMessages.java
index 0f989cc..c4a8d20 100644
--- a/src/main/java/com/example/gecekodubackend/business/constants/UserMessages.java
+++ b/src/main/java/com/example/gecekodubackend/business/constants/UserMessages.java
@@ -12,4 +12,6 @@ public class UserMessages {
public static String userDeletedSuccessfully = "Kullanıcı başarıyla silindi!";
public static String emailCannotBeNull = "Email adresiniz boş olamaz!";
public static String userDoesNotExist = "Kullanıcı mevcut değil!";
+ public static String userAddedToEventSuccessfully = "Kullanıcı etkinliğe başarıyla eklendi!";
+ ;
}
diff --git a/src/main/java/com/example/gecekodubackend/core/config/SecurityConfig.java b/src/main/java/com/example/gecekodubackend/core/config/SecurityConfig.java
index a19a0bc..b449190 100644
--- a/src/main/java/com/example/gecekodubackend/core/config/SecurityConfig.java
+++ b/src/main/java/com/example/gecekodubackend/core/config/SecurityConfig.java
@@ -1,7 +1,9 @@
package com.example.gecekodubackend.core.config;
+import com.example.gecekodubackend.core.security.JwtAuthFilter;
+import org.springframework.http.HttpMethod;
import com.example.gecekodubackend.business.abstracts.UserService;
-import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
@@ -13,6 +15,7 @@
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@@ -22,44 +25,108 @@
public class SecurityConfig {
private final JwtAuthFilter jwtAuthFilter;
-
private final UserService userService;
-
private final PasswordEncoder passwordEncoder;
- public SecurityConfig(JwtAuthFilter jwtAuthFilter, UserService userService, PasswordEncoder passwordEncoder){
+ @Autowired
+ public SecurityConfig(JwtAuthFilter jwtAuthFilter, UserService userService, PasswordEncoder passwordEncoder) {
this.jwtAuthFilter = jwtAuthFilter;
this.userService = userService;
this.passwordEncoder = passwordEncoder;
}
- public SecurtyFilterChain securtyFilterChain(HttpSecurity httpSecurity) throws Exception{
+ @Bean
+ public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
- .csrf(AbstractHttpConfigurer :: disable)
+ .csrf(AbstractHttpConfigurer::disable)
+
.authorizeHttpRequests(x ->
x
- .requestMatchers("webApi/auth/**").permitALl()
- .requestMatchers("webApi/users/**").hasAnyRole("USER", "ADMIN")
- .requestMatchers("webApi/events/**").hasAnyRole("ADMIN")
- .requestMatchers("webApi/workshops/**").hasAnyRole("ADMIN")
+ .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
+
+
+ .requestMatchers("/api/auth/**").permitAll()
+
+ .requestMatchers("/api/users/addUser").permitAll()
+ .requestMatchers("/api/users/deleteUser").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("/api/users/updateUser").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("/api/users/getUserById").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("/api/users/getUserByUsername").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("/api/users/getUsers").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("/api/users/addModerator").hasRole("ADMIN")
+ .requestMatchers("/api/users/removeModerator").hasRole("ADMIN")
+ .requestMatchers("/api/users/addVip").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("/api/users/removeVip").hasAnyRole("ADMIN", "MODERATOR")
+
+ .requestMatchers("/api/games/addGame").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/games/connectPlayer").permitAll()
+ .requestMatchers("/api/games/deleteGame").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/games/endGame").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/games/getGameByGameCode").permitAll()
+
+ .requestMatchers("/api/games/getGameEntityByGameCode").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("/api/games/getGameId").permitAll()
+ .requestMatchers("/api/games/getGameEntityByGameId").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("/api/games/getGamesByHostId").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("api/games/getGameStarted").permitAll()
+ .requestMatchers("/api/games/getLeaderboard").permitAll()
+ // .requestMatchers("/api/games/getNextQuestion").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/games/startGame").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/games/updateGame").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+
+ .requestMatchers("/api/questions/addQuestion").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/questions/deleteQuestion").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/questions/getQuestionById").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("/api/questions/updateQuestion").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/questions/getQuestionsByHost").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/questions/getQuestionEntityById").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("/api/questions/getQuestionsByGameId").hasAnyRole("ADMIN", "MODERATOR")
+
+ .requestMatchers("/api/answerOptions/addAnswerOption").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/answerOptions/deleteAnswerOption").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/answerOptions/getAnswerOptionById").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/answerOptions/updateAnswerOption").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/answerOptions/getAnswerOptionEntityById").hasAnyRole("ADMIN", "MODERATOR")
+ // .requestMatchers("/api/answerOptions/getAnswerOptionsByQuestionId").hasAnyRole("ADMIN", "MODERATOR")
+
+ .requestMatchers("/api/players/addPlayer").permitAll()
+ .requestMatchers("/api/players/**").hasAnyRole("ADMIN", "MODERATOR")
+
+ .requestMatchers("/api/playerAnswers/addPlayerAnswer").permitAll()
+ .requestMatchers("/api/playerAnswers/getPlayerAnswerById").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/playerAnswers/deletePlayerAnswer").hasAnyRole("ADMIN", "MODERATOR")
+ .requestMatchers("/api/playerAnswers/getPlayerAnswersByPlayerId").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/playerAnswers/getPlayerAnswersByQuestionId").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+ .requestMatchers("/api/playerAnswers/validatePlayerAnswer").hasAnyRole("ADMIN", "MODERATOR", "VIP")
+
+
+
+
+
+
.anyRequest().permitAll()
+
)
- .sessionManagement(x -> sessionCreationPolicy(SessionCreationPolicy.STATELESS))
+ .sessionManagement(x -> x.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.build();
+
+
}
@Bean
- public AuthenticationProvider authenticationProvider(){
- DaoAuthenticationProvider auhthenticationProvider = new DaoAuthenticationProvider();
- authenticationProvider().setUserDetailsService(userService);
- authenticationProvider().setPasswordEncoder(passwordEncoder);
+ public AuthenticationProvider authenticationProvider() {
+ DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
+ authenticationProvider.setUserDetailsService(userService);
+ authenticationProvider.setPasswordEncoder(passwordEncoder);
return authenticationProvider;
+
}
@Bean
- public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception{
- return configuration.getAuthenticationManager();
+ public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
+ return authenticationConfiguration.getAuthenticationManager();
}
-}
+
+}
\ No newline at end of file
diff --git a/src/main/java/com/example/gecekodubackend/core/dataAccess/UserDao.java b/src/main/java/com/example/gecekodubackend/core/dataAccess/UserDao.java
index e5954ef..ad5fc83 100644
--- a/src/main/java/com/example/gecekodubackend/core/dataAccess/UserDao.java
+++ b/src/main/java/com/example/gecekodubackend/core/dataAccess/UserDao.java
@@ -5,5 +5,9 @@
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDao extends JpaRepository {
- GetUserDto getUserByEmail(String email);
+ User getUserByEmail(String email);
+
+ boolean existsByEmail(String email);
+
+
}
diff --git a/src/main/java/com/example/gecekodubackend/core/dtos/GetUserDto.java b/src/main/java/com/example/gecekodubackend/core/dtos/GetUserDto.java
index bb49b7b..200acca 100644
--- a/src/main/java/com/example/gecekodubackend/core/dtos/GetUserDto.java
+++ b/src/main/java/com/example/gecekodubackend/core/dtos/GetUserDto.java
@@ -23,4 +23,5 @@ public class GetUserDto {
private List workshopDto;
private List eventDto;
+
}
diff --git a/src/main/java/com/example/gecekodubackend/core/entities/User.java b/src/main/java/com/example/gecekodubackend/core/entities/User.java
index 51e9d76..5255777 100644
--- a/src/main/java/com/example/gecekodubackend/core/entities/User.java
+++ b/src/main/java/com/example/gecekodubackend/core/entities/User.java
@@ -2,7 +2,9 @@
import com.example.gecekodubackend.entity.abstracts.Entity;
import com.example.gecekodubackend.entity.concretes.Event;
+import com.example.gecekodubackend.entity.concretes.Role;
import com.example.gecekodubackend.entity.concretes.Workshop;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Max;
@@ -11,7 +13,11 @@
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+import java.util.Collection;
+import java.util.List;
import java.util.Set;
@Data
@@ -19,7 +25,7 @@
@jakarta.persistence.Entity
@NoArgsConstructor
@AllArgsConstructor
-public class User implements Entity {
+public class User implements UserDetails {
@Id
@Column(name = "user_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@@ -47,6 +53,7 @@ public class User implements Entity {
private String password;
@ManyToMany
+ @JsonIgnore
@JoinTable(
name = "user_workshop",
joinColumns = @JoinColumn(name = "user_id"),
@@ -54,9 +61,46 @@ public class User implements Entity {
private Set workshops;
@ManyToMany
+ @JsonIgnore
@JoinTable(
name = "user_event",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "event_id"))
private Set events;
+
+ @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
+ @JoinTable(name = "authorities", joinColumns = @JoinColumn(name = "user_id"))
+ @Column(name = "role", nullable = false)
+ @Enumerated(EnumType.STRING)
+ private Set authorities;
+
+ @Override
+ public String getUsername() {
+ return email;
+ }
+
+ @Override
+ @JsonIgnore
+ public boolean isAccountNonExpired() {
+ return true;
+ }
+
+ @Override
+ @JsonIgnore
+ public boolean isAccountNonLocked() {
+ return true;
+ }
+
+ @Override
+ @JsonIgnore
+ public boolean isCredentialsNonExpired() {
+ return true;
+ }
+
+ @Override
+ @JsonIgnore
+ public boolean isEnabled() {
+ return true;
+ }
+
}
diff --git a/src/main/java/com/example/gecekodubackend/core/security/JwtAuthFilter.java b/src/main/java/com/example/gecekodubackend/core/security/JwtAuthFilter.java
index ffc72e4..06f791f 100644
--- a/src/main/java/com/example/gecekodubackend/core/security/JwtAuthFilter.java
+++ b/src/main/java/com/example/gecekodubackend/core/security/JwtAuthFilter.java
@@ -40,7 +40,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
if(username != null && SecurityContextHolder.getContext().getAuthentication() == null){
UserDetails user = userService.loadUserByUsername(username);
if(jwtService.validateToken(token, user)){
- UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
+ UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
diff --git a/src/main/java/com/example/gecekodubackend/core/security/JwtService.java b/src/main/java/com/example/gecekodubackend/core/security/JwtService.java
index efd92ec..c264b3c 100644
--- a/src/main/java/com/example/gecekodubackend/core/security/JwtService.java
+++ b/src/main/java/com/example/gecekodubackend/core/security/JwtService.java
@@ -16,25 +16,25 @@
@Service
public class JwtService {
- //defines the secret key for jwt
- @Value("${jwt.key}")
+
+ @Value("${jwt.secret}")
private String SECRET;
+
public String generateToken(String username){
- Map claims = new HashMap<>();
- claims.put("can","wia");
- return createToken(claims.username);
+ Map claims = new HashMap<>();
+ return createToken(claims, username);
}
- private Boolean validateToken(String token, UserDetails userDetails){
- String username = exractUser(token);
+ public Boolean validateToken(String token, UserDetails userDetails){
+ String username = extractUser(token);
Date expirationDate = extractExpiration(token);
- return userDetails.getUsername().equals(username) && expirationDate.after(new Date());
+ return userDetails.getUsername().equals(username) && !expirationDate.before(new Date());
}
- private Date extractExpiration(String token){
+ private Date extractExpiration(String token) {
Claims claims = Jwts
- .parseBuilder()
+ .parserBuilder()
.setSigningKey(getSignKey())
.build()
.parseClaimsJws(token)
@@ -42,9 +42,9 @@ private Date extractExpiration(String token){
return claims.getExpiration();
}
- private String exractUser(String token){
+ public String extractUser(String token) {
Claims claims = Jwts
- .parseBuilder()
+ .parserBuilder()
.setSigningKey(getSignKey())
.build()
.parseClaimsJws(token)
@@ -52,17 +52,21 @@ private String exractUser(String token){
return claims.getSubject();
}
- private String createToken(Map claims, String username){
- return Jwts.builder()
+ private String createToken(Map claims, String username) {
+ var result = Jwts.builder()
.setClaims(claims)
.setSubject(username)
- .setIssuedAt(new Date(System.currentTimeMillis() + 1000*60*2))
+ .setIssuedAt(new Date(System.currentTimeMillis()))
+ .setExpiration(new Date(System.currentTimeMillis()+ 1000 * 60 * 60 * 24)) //token is valid for 24 hours
.signWith(getSignKey(), SignatureAlgorithm.HS256)
.compact();
+ return result;
}
- private Key getSignKey(){
+ private Key getSignKey() {
byte[] keyBytes = Decoders.BASE64.decode(SECRET);
return Keys.hmacShaKeyFor(keyBytes);
+
}
+
}
diff --git a/src/main/java/com/example/gecekodubackend/entity/concretes/Role.java b/src/main/java/com/example/gecekodubackend/entity/concretes/Role.java
index 8920707..3b08489 100644
--- a/src/main/java/com/example/gecekodubackend/entity/concretes/Role.java
+++ b/src/main/java/com/example/gecekodubackend/entity/concretes/Role.java
@@ -1,12 +1,18 @@
-package com.example.gecekodubackend.entity.concretes;
+package com.example.gecekodubackend.entity.concretes;
+
+import org.springframework.security.core.GrantedAuthority;
public enum Role implements GrantedAuthority {
+
+ ROLE_ADMIN("ADMIN"),
+ ROLE_MODERATOR("MODERATOR"),
ROLE_USER("USER"),
- ROLE_ADMIN("ADMIN");
+ ROLE_VIP("VIP");
+
private String value;
- Role(String value){
+ Role(String value) {
this.value = value;
}
@@ -15,7 +21,8 @@ public String getValue(){
}
@Override
- public String getAuthority(){
+ public String getAuthority() {
return name();
}
}
+
diff --git a/src/main/java/com/example/gecekodubackend/entity/dtos/auth/AuthDto.java b/src/main/java/com/example/gecekodubackend/entity/dtos/auth/AuthDto.java
new file mode 100644
index 0000000..bb7c6f2
--- /dev/null
+++ b/src/main/java/com/example/gecekodubackend/entity/dtos/auth/AuthDto.java
@@ -0,0 +1,30 @@
+package com.example.gecekodubackend.entity.dtos.auth;
+
+public class AuthDto {
+ private String email;
+ private String password;
+
+ public AuthDto() {
+ }
+
+ public AuthDto(String email, String password) {
+ this.email = email;
+ this.password = password;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+}
diff --git a/src/main/java/com/example/gecekodubackend/webApi/controllers/AuthController.java b/src/main/java/com/example/gecekodubackend/webApi/controllers/AuthController.java
new file mode 100644
index 0000000..e21f680
--- /dev/null
+++ b/src/main/java/com/example/gecekodubackend/webApi/controllers/AuthController.java
@@ -0,0 +1,40 @@
+package com.example.gecekodubackend.webApi.controllers;
+
+import com.example.gecekodubackend.business.abstracts.UserService;
+import com.example.gecekodubackend.core.security.JwtService;
+import com.example.gecekodubackend.core.utilities.results.DataResult;
+import com.example.gecekodubackend.core.utilities.results.ErrorDataResult;
+import com.example.gecekodubackend.core.utilities.results.SuccessDataResult;
+import com.example.gecekodubackend.entity.dtos.auth.AuthDto;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/webApi/auth")
+public class AuthController {
+
+ private AuthenticationManager authenticationManager;
+ private JwtService jwtService;
+ private UserService userService;
+
+ public AuthController(UserService userService,AuthenticationManager authenticationManager, JwtService jwtService){
+ this.authenticationManager = authenticationManager;
+ this.jwtService = jwtService;
+ this.userService = userService;
+ }
+
+
+ @PostMapping("/generateToken")
+ public DataResult generateToken(@RequestBody AuthDto authRequest) {
+ Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authRequest.getEmail(), authRequest.getPassword()));
+ if (authentication.isAuthenticated()) {
+ return new SuccessDataResult(jwtService.generateToken(authRequest.getEmail()), "Token generated successfully");
+ }
+ return new ErrorDataResult<>("Invalid email or password");
+ }
+}
diff --git a/src/main/java/com/example/gecekodubackend/webApi/controllers/EventsController.java b/src/main/java/com/example/gecekodubackend/webApi/controllers/EventsController.java
index 3fabdae..9d2d229 100644
--- a/src/main/java/com/example/gecekodubackend/webApi/controllers/EventsController.java
+++ b/src/main/java/com/example/gecekodubackend/webApi/controllers/EventsController.java
@@ -72,4 +72,6 @@ public ResponseEntity> deleteEvent(@PathVariable int id){
return ResponseEntity.badRequest().body(result);
}
+
+
}
diff --git a/src/main/java/com/example/gecekodubackend/webApi/controllers/UsersController.java b/src/main/java/com/example/gecekodubackend/webApi/controllers/UsersController.java
index 481a54c..2310e2a 100644
--- a/src/main/java/com/example/gecekodubackend/webApi/controllers/UsersController.java
+++ b/src/main/java/com/example/gecekodubackend/webApi/controllers/UsersController.java
@@ -25,7 +25,7 @@ public UsersController(UserService userService){
}
@GetMapping("/getAllUsers")
- public DataResult> getAllUsers(){
+ public DataResult> getAllUsers(){
return this.userService.getAllUsers();
}
@@ -40,8 +40,8 @@ public DataResult getUserById(@PathVariable(name = "id") Integer use
}
@PutMapping("/updateUser/{id}")
- public Result updateUser(@RequestBody User user, @PathVariable int id){
- return this.userService.updateUser(user, id);
+ public Result updateUser(@RequestBody GetUserDto getUserDto, @PathVariable int id){
+ return this.userService.updateUser(getUserDto, id);
}
@DeleteMapping("/deleteUser/{id}")
@@ -58,4 +58,9 @@ public DataResult getUserByEmail(@PathVariable(name = "email") Strin
}
return ResponseEntity.badRequest().body(result).getBody();
}
+
+ @PostMapping("/addUserToEvent")
+ public Result addUserToEvent(@RequestParam int userId, @RequestParam int eventId){
+ return this.userService.addUserToEvent(userId, eventId);
+ }
}
diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties
index a0f4824..b441813 100644
--- a/src/main/resources/application.properties
+++ b/src/main/resources/application.properties
@@ -6,6 +6,10 @@ spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/GeceKodu
spring.datasource.username=postgres
-spring.datasource.password=1@1@8en0meR
+spring.datasource.password=alper3848
+#spring.datasource.username=postgres
+#spring.datasource.password=1@1@8en0meR
-spring.jpa.properties.javax.persistence.validation.mode = none
\ No newline at end of file
+spring.jpa.properties.javax.persistence.validation.mode = none
+
+jwt.secret = c761997740ba86ed2966f1f562f76b6e56596dba810f3260dcda6e808be55a79