Changeset 0c6b92a for imaps-backend/backendRender
- Timestamp:
- 12/12/24 17:06:06 (5 weeks ago)
- Branches:
- main
- Parents:
- d565449
- Location:
- imaps-backend/backendRender/src
- Files:
-
- 50 added
- 9 deleted
- 14 edited
- 3 moved
Legend:
- Unmodified
- Added
- Removed
-
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/graph/Edge.java
rd565449 r0c6b92a 4 4 import lombok.Getter; 5 5 import lombok.Setter; 6 import lombok.ToString; 6 7 7 8 import java.util.Map; 8 9 9 10 @Setter @Getter 11 @ToString 10 12 public class Edge{ 11 13 private MapNode node; -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/graph/MapNode.java
rd565449 r0c6b92a 14 14 private Coordinates<Double,Double> coordinates; 15 15 private List<String> connectionNames = new ArrayList<>(); 16 private String className; 17 private int floorNumber; 16 18 17 public MapNode(String name, String description, Coordinates<Double, Double> coordinates ) {19 public MapNode(String name, String description, Coordinates<Double, Double> coordinates,String className,int floorNumber) { 18 20 this.name = name; 19 21 this.description = description; 20 22 this.coordinates = coordinates; 23 this.className = className; 24 this.floorNumber = floorNumber; 21 25 } 22 26 … … 27 31 } 28 32 29 public MapNode(String name, String description, Coordinates<Double, Double> coordinates, String connectedRoom) {30 this.name = name;31 this.description = description;32 this.coordinates = coordinates;33 this.connectedRoom = connectedRoom;34 }35 33 36 34 public MapNode() { -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/graph/MapNodeParser.java
rd565449 r0c6b92a 2 2 3 3 4 import com.fasterxml.jackson.core.JsonProcessingException;5 4 import com.fasterxml.jackson.databind.JsonNode; 6 5 import com.fasterxml.jackson.databind.ObjectMapper; … … 10 9 11 10 public class MapNodeParser { 12 public List<MapNode> parseAndCreateNodes(String mapJson) throws Exception { 11 12 13 public List<MapNode> parseAndCreate(String mapJson) throws Exception { 13 14 final List<MapNode> mapNodes = new ArrayList<>(); 14 15 15 System.out.println("======= MAP JSON ====== " + mapJson); 16 17 // if(mapJson == null || mapJson.isEmpty() || mapJson.equals("[]")) { 18 // throw new MapParseException("Cannot parse empty map"); 19 // } 16 if (mapJson == null || mapJson.isEmpty() || mapJson.equals("[]")) { 17 throw new MapParseException("Cannot parse empty map"); 18 } 20 19 21 20 ObjectMapper objectMapper = new ObjectMapper(); 22 String[] shapes = objectMapper.readValue(mapJson, String[].class);21 List<Shape> shapes = objectMapper.readValue(mapJson, objectMapper.getTypeFactory().constructCollectionType(List.class, Shape.class)); 23 22 24 Arrays.stream(shapes).forEach(shape -> { 25 try { 26 JsonNode parsedNode = objectMapper.readTree(shape); 27 String type = parsedNode.get("className").asText(); 28 29 // Wall i room ne se bitni za navigacija 30 if(Objects.equals(type,"Wall") || Objects.equals(type,"Room")) return; 31 32 JsonNode attrs = parsedNode.get("attrs"); 33 MapNode mapNode = createMapNode(attrs); 34 35 if(attrs.has("connected_pins")){ 36 JsonNode connectedPins = attrs.get("connected_pins"); 37 if (connectedPins.isArray()) { 38 for (JsonNode pin : connectedPins) { 39 System.out.println("Connected node (markup) : " + pin.asText() + " to: " + attrs.get("obj_name")); 40 mapNode.addConnectionName(pin.asText()); 41 } 42 } 23 shapes.forEach(shape -> { 24 try { 25 String type = shape.getClassName(); 26 if (Objects.equals(type, "Wall") || Objects.equals(type, "Room")) return; 27 MapNode mapNode = createMapNode(shape); 28 @SuppressWarnings("unchecked") 29 List<String> connectedPins = (List<String>) shape.getAttrs().get("connected_pins"); 30 if (connectedPins != null) { 31 for (String pin : connectedPins) { 32 System.out.println("Connected node (markup) : " + pin + " to: " + shape.getAttrs().get("obj_name")); 33 mapNode.addConnectionName(pin); 43 34 } 44 45 mapNodes.add(mapNode);46 47 } catch (JsonProcessingException e) {48 throw new RuntimeException(e);49 35 } 50 }); 51 52 mapNodes.forEach(node -> System.out.println("Added node: ----> " + node.toString())); 53 54 return mapNodes; 55 36 mapNodes.add(mapNode); 37 } catch (Exception e) { 38 throw new RuntimeException(e); 39 } 40 }); 41 mapNodes.forEach(node -> System.out.println("Added node: ----> " + node.toString())); 42 return mapNodes; 56 43 } 57 44 58 45 59 private static String findAttr(String key,JsonNode attrs){ 60 if(attrs.has(key)){ 61 return attrs.get(key).asText(); 62 } else { 63 System.out.println("No attribute found for key:" + key); 64 return null; 65 } 46 private static MapNode createMapNode(Shape shape) { 47 String name = (String) shape.getAttrs().get("obj_name"); 48 String description = (String) shape.getAttrs().get("description"); 49 String connectedRoom = (String) shape.getAttrs().get("connected_room"); 50 double x = Double.parseDouble(Objects.requireNonNull(shape.getAttrs().get("x")).toString()); 51 double y = Double.parseDouble(Objects.requireNonNull(shape.getAttrs().get("y")).toString()); 52 Coordinates<Double, Double> coordinates = new Coordinates<>(x, y); 53 int floorNumber = (int) shape.getAttrs().get("floor_num"); 66 54 67 } 68 69 70 private static MapNode createMapNode(JsonNode attrs) { 71 String name = findAttr("obj_name",attrs); 72 String description = findAttr("description",attrs); 73 String connectedRoom = findAttr("connected_room",attrs); 74 double x = Double.parseDouble(Objects.requireNonNull(findAttr("x", attrs))); 75 double y = Double.parseDouble(Objects.requireNonNull(findAttr("y", attrs))); 76 Coordinates<Double,Double> coordinates = new Coordinates<>(x,y); 77 78 MapNode mapNode = new MapNode(name, description, coordinates); 79 if(connectedRoom != null){ 55 MapNode mapNode = new MapNode(name, description, coordinates, shape.getClassName(), floorNumber); 56 if (connectedRoom != null) { 80 57 mapNode.setConnectedRoom(connectedRoom); 81 58 } -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/graph/RouteGraph.java
rd565449 r0c6b92a 7 7 private final Map<String, MapNode> nameToNodeMap = new HashMap<>(); 8 8 9 public RouteGraph(List<MapNode> nodes) {10 9 11 10 public void loadNodeNames(List<MapNode> nodes){ 12 11 for (MapNode node : nodes) { 13 12 nameToNodeMap.put(node.getName(), node); 14 13 } 15 14 16 for (MapNode mapNode : nodes) { 15 for(Map.Entry<String,MapNode> entries : nameToNodeMap.entrySet()) { 16 System.out.println(entries.getKey() + " " + entries.getValue()); 17 } 18 } 19 20 public void loadEdges(){ 21 for (MapNode mapNode : nameToNodeMap.values()) { 17 22 for (String connectionName : mapNode.getConnectionNames()) { 23 System.out.println("CONN: " + mapNode.getName() + " " + connectionName); 18 24 MapNode connectedNode = nameToNodeMap.get(connectionName); 19 25 if (connectedNode != null) { 20 26 addEdge(mapNode, connectedNode); 27 }else { 28 System.out.println("CANT ADD EDGE ========== " + "FROM: " + mapNode.getName() + " TO: " + connectionName); 21 29 } 22 30 } … … 28 36 double x1 = a.getCoordinates().x; 29 37 double y1 = a.getCoordinates().y; 38 30 39 double x2 = b.getCoordinates().x; 31 40 double y2 = b.getCoordinates().y; … … 42 51 if (sourceNode == null || targetNode == null) { 43 52 System.out.println(this.toString()); 53 System.out.println("SOURCE NODE FROM MAP " + sourceNode); 54 System.out.println("TARGET NODE FROM MAP " + targetNode); 44 55 throw new IllegalArgumentException("Source or target node not found. SOURCE: " + source + " TARGET: " + target); 45 56 } … … 95 106 } 96 107 97 Collections.reverse(path); 108 Collections.reverse(path);// deka se staveni vo obraten redosled, pa reverse ni dava pateka od pocetok do kraj. 98 109 99 110 if (!path.isEmpty() && path.get(0).equals(sourceNode)) { 111 System.out.println("FOUND PATH: " + path); 100 112 return path; 101 113 } else { … … 129 141 } 130 142 return null; 143 //throw new IllegalArgumentException("Cant find room connected to entrance: " + roomName); 131 144 } 132 133 public String getNodeNameByName(String name){134 return nameToNodeMap.get(name).getName();135 }136 137 145 138 146 … … 145 153 MapNode node = entry.getKey(); 146 154 Set<Edge> connectedNodes = entry.getValue(); 155 156 System.out.println("CONN NODES PRINT: " + connectedNodes); 147 157 148 158 sb.append(node.getName()).append(" -> "); -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/controllers/AuthController.java
rd565449 r0c6b92a 2 2 3 3 import internettehnologii.imaps.backendRender.web.entities.IMapsUser; 4 import internettehnologii.imaps.backendRender.web.service.JWTService; 5 import internettehnologii.imaps.backendRender.web.service.MapUserDetailsService; 6 import internettehnologii.imaps.backendRender.web.service.UserService; 4 import internettehnologii.imaps.backendRender.web.entities.IndoorMap; 5 import internettehnologii.imaps.backendRender.web.service.impl.JWTService; 6 import internettehnologii.imaps.backendRender.web.service.impl.MapUserDetailsService; 7 import internettehnologii.imaps.backendRender.web.service.impl.UserServiceImpl; 8 import internettehnologii.imaps.backendRender.web.service.interfaces.MapService; 9 import internettehnologii.imaps.backendRender.web.util.DTO.UserAuthSuccessDTO; 10 import internettehnologii.imaps.backendRender.web.util.DTO.UserLoginDTO; 7 11 import jakarta.servlet.http.HttpServletRequest; 8 12 import org.springframework.beans.factory.annotation.Autowired; 9 13 import org.springframework.context.ApplicationContext; 14 import org.springframework.http.ResponseEntity; 10 15 import org.springframework.security.core.userdetails.UserDetails; 16 import org.springframework.security.core.userdetails.UserDetailsService; 11 17 import org.springframework.web.bind.annotation.*; 12 18 19 import javax.management.relation.RoleNotFoundException; 13 20 import java.util.HashMap; 14 import java.util.List;15 21 import java.util.Map; 16 22 … … 21 27 22 28 @Autowired 23 private UserService userService;29 private UserServiceImpl userService; 24 30 @Autowired 25 31 private JWTService jwtService; … … 29 35 30 36 @PostMapping("/register") 31 public IMapsUser register(@RequestBody IMapsUser user) {37 public IMapsUser register(@RequestBody IMapsUser user) throws RoleNotFoundException { 32 38 return userService.register(user); 33 39 } 34 40 35 41 @PostMapping("/login") 36 public Map<String, Object> login(@RequestBody IMapsUser user, HttpServletRequest request) {42 public Map<String, Object> login(@RequestBody UserLoginDTO user) { 37 43 System.out.println(user); 38 44 Map<String, Object> response = new HashMap<>(); 39 String token = userService.verify(user); 40 response.put("token", token); 41 response.put("username", user.getUsername()); 45 46 try{ 47 UserAuthSuccessDTO userAuthSuccessDTO = userService.login(user); 48 response.put("token", userAuthSuccessDTO.getToken()); 49 response.put("username", userAuthSuccessDTO.getUsername()); 50 response.put("roles", userAuthSuccessDTO.getRoles()); 51 } catch (Exception e){ 52 System.out.println(e.getMessage()); 53 response.put("error", e.getMessage()); 54 } 55 42 56 return response; 43 57 } 44 58 45 59 46 //ZA TESTIRANJE47 @GetMapping("/list")48 public List<IMapsUser> showUsers() {49 return userService.getUsers();50 }51 52 60 @GetMapping("/verify") 53 public Map<String,Object> authenticateUser(@RequestParam String token) { 61 public ResponseEntity<Map<String,Object>> authenticateUser(@RequestParam String token) { 62 System.out.println("VERIFY"); 54 63 Map<String, Object> response = new HashMap<>(); 55 64 try{ … … 57 66 UserDetails userDetails = context.getBean(MapUserDetailsService.class).loadUserByUsername(username); 58 67 boolean auth = jwtService.validateToken(token, userDetails); 59 if(auth){ 60 response.put("username", username); 68 69 if(!auth){ 70 response.put("error", "Token could not be validated"); 71 return ResponseEntity.status(403).body(response); 61 72 } 62 73 63 System.out.println(auth + " auth"); 74 response.put("username", username); 75 System.out.println("Authenticated user: " + username); 64 76 } catch (Exception e){ 77 response.put("auth",false); 65 78 System.out.println("ERROR: NOT AUTHENTICATED: " + e.getMessage()); 66 79 } 67 80 68 return response;81 return ResponseEntity.ok(response); 69 82 70 83 } 84 85 @GetMapping("/test_auth") 86 public ResponseEntity<Map<String,Object>> testAuth(){ 87 Map<String, Object> response = new HashMap<>(); 88 response.put("auth",true); 89 return ResponseEntity.ok(response); 90 } 91 71 92 } -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/entities/IMapsUser.java
rd565449 r0c6b92a 1 1 package internettehnologii.imaps.backendRender.web.entities; 2 import internettehnologii.imaps.backendRender.web.entities.RBA.Role; 2 3 import jakarta.persistence.*; 3 4 import lombok.Getter; 4 5 import lombok.Setter; 5 6 6 @Getter 7 import java.time.LocalDateTime; 8 import java.util.Date; 9 import java.util.HashSet; 10 import java.util.Set; 11 7 12 @Entity 8 13 @Table(name = "users") 14 @Getter @Setter 9 15 public class IMapsUser { 10 16 @Id 11 @SequenceGenerator( 12 name = "users_id_seq", 13 sequenceName = "users_id_seq", 14 allocationSize = 1 15 ) 16 @GeneratedValue( 17 strategy = GenerationType.SEQUENCE, 18 generator = "users_id_seq" 19 ) 17 @SequenceGenerator(name = "users_id_seq", sequenceName = "users_id_seq", allocationSize = 1) 18 @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "users_id_seq") 20 19 private int id; 21 @Setter22 @Column(name = "name")23 20 private String username; 24 @Setter25 21 private String email; 26 @Getter @Setter27 22 private String password; 28 23 24 @Column(name = "created_at") 25 private LocalDateTime createdAt; 26 27 @Column(name = "last_login_at") 28 private LocalDateTime lastLoginAt; 29 30 @Column(name = "profile_image_url") 31 private String profileImageUrl; 32 33 @ManyToMany 34 @JoinTable( 35 name = "favourites", 36 joinColumns = @JoinColumn(name = "user_id"), 37 inverseJoinColumns = @JoinColumn(name = "map_id") 38 ) 39 private Set<IndoorMap> favoriteMaps; 40 41 @ManyToMany(mappedBy = "users",cascade = CascadeType.PERSIST) 42 private Set<Role> roles = new HashSet<>(); 29 43 30 44 public IMapsUser() {} -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/entities/IndoorMap.java
rd565449 r0c6b92a 1 1 package internettehnologii.imaps.backendRender.web.entities; 2 import internettehnologii.imaps.backendRender.web.security.json.DataJson;3 2 import jakarta.persistence.*; 4 import org.hibernate.annotations.JdbcTypeCode; 5 import org.hibernate.type.SqlTypes; 3 import lombok.Getter; 4 import lombok.Setter; 5 6 import java.time.LocalDateTime; 7 import java.util.ArrayList; 8 import java.util.HashSet; 9 import java.util.List; 10 import java.util.Set; 6 11 7 12 @Entity 13 @Getter @Setter 8 14 @Table(name = "maps") 9 15 public class IndoorMap { 10 16 @Id 11 @SequenceGenerator( 12 name = "map_id_seq", 13 sequenceName = "map_id_seq", 14 allocationSize = 1 15 ) 16 @GeneratedValue( 17 strategy = GenerationType.SEQUENCE, 18 generator = "map_id_seq" 19 ) 17 @SequenceGenerator(name = "maps_id_seq", sequenceName = "maps_id_seq", allocationSize = 1) 18 @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "maps_id_seq") 20 19 private Integer id; 21 private String name;22 20 23 @JdbcTypeCode(SqlTypes.JSON) 24 private DataJson mapData; //json 21 private String name = ""; 25 22 26 @ JdbcTypeCode(SqlTypes.JSON)27 private DataJson graphData; //json23 @Column(name = "gmaps_url") 24 private String gmapsUrl = ""; 28 25 29 private boolean isPublic;30 private String url;26 @Enumerated(EnumType.STRING) 27 private MAP_STATUS status; 31 28 29 @Column(name = "published_at") 30 private LocalDateTime publishedAt; 32 31 33 public IndoorMap(String name, DataJson mapData, boolean isPublic, String url) { 34 this.name = name; 35 this.mapData = mapData; 36 this.isPublic = isPublic; 37 this.url = url; 32 @Column(name = "created_at") 33 private LocalDateTime createdAt; 34 35 @Column(name = "modified_at") 36 private LocalDateTime modifiedAt; 37 38 @Column(name = "map_type") 39 private String mapType; 40 41 @Column(name = "image_url") 42 private String imageUrl; 43 @Column(name = "is_published") 44 private Boolean isPublished; 45 46 @ManyToOne 47 @JoinColumn(name = "usr_id",referencedColumnName = "id", nullable = false) 48 private IMapsUser user; 49 50 @OneToMany(mappedBy = "indoorMap") 51 private List<RoomType> roomTypes = new ArrayList<>(); 52 @OneToMany(mappedBy = "indoorMap") 53 private List<Floor> floors = new ArrayList<>(); 54 @ManyToMany(mappedBy = "favoriteMaps") 55 private Set<IMapsUser> favoritedBy = new HashSet<>(); 56 57 @PrePersist 58 protected void onCreate(){ 59 this.createdAt = LocalDateTime.now(); 60 this.status = MAP_STATUS.PRIVATE; 38 61 } 39 62 40 public IndoorMap(){41 63 public int getFavouriteCount(){ 64 return this.favoritedBy.size(); 42 65 } 43 66 44 public IndoorMap(Integer id, String name, DataJson mapData, boolean isPublic, String url) { 45 this.id = id; 46 this.name = name; 47 this.mapData = mapData; 48 this.isPublic = isPublic; 49 this.url = url; 67 @PreUpdate 68 protected void onUpdate(){ 69 this.modifiedAt = LocalDateTime.now(); 50 70 } 51 71 52 public IndoorMap(Integer id, String name, DataJson mapData, DataJson graphData, boolean isPublic, String url) {53 this.id = id;54 this.name = name;55 this.mapData = mapData;56 this.graphData = graphData;57 this.isPublic = isPublic;58 this.url = url;59 }60 61 public IndoorMap(String name, DataJson mapData, DataJson graphData, boolean isPublic, String url) {62 this.name = name;63 this.mapData = mapData;64 this.graphData = graphData;65 this.isPublic = isPublic;66 this.url = url;67 }68 69 public IndoorMap(String name, DataJson dataJson) {70 this.name = name;71 this.mapData = dataJson;72 }73 74 public Integer getId() {75 return id;76 }77 78 public String getName() {79 return name;80 }81 82 public DataJson getMapData() {83 return mapData;84 }85 86 public DataJson getGraphData() {87 return graphData;88 }89 90 public boolean isPublic() {91 return isPublic;92 }93 94 public String getUrl() {95 return url;96 }97 98 public void setName(String name) {99 this.name = name;100 }101 102 public void setMapData(DataJson mapData) {103 this.mapData = mapData;104 }105 106 public void setGraphData(DataJson graphData) {107 this.graphData = graphData;108 }109 110 public void setPublic(boolean aPublic) {111 isPublic = aPublic;112 }113 114 public void setUrl(String url) {115 this.url = url;116 }117 118 @Override119 public String toString() {120 return "Map{" +121 "id=" + id +122 ", name='" + name + '\'' +123 ", mapData='" + mapData + '\'' +124 ", graphData='" + graphData + '\'' +125 ", isPublic=" + isPublic +126 ", url='" + url + '\'' +127 '}';128 }129 72 } -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/repo/MapRepository.java
rd565449 r0c6b92a 1 1 package internettehnologii.imaps.backendRender.web.repo; 2 2 3 import internettehnologii.imaps.backendRender.web.entities.IMapsUser; 3 4 import internettehnologii.imaps.backendRender.web.entities.IndoorMap; 4 import internettehnologii.imaps.backendRender.web.security.json.DataJson; 5 import internettehnologii.imaps.backendRender.web.entities.MAP_STATUS; 6 import internettehnologii.imaps.backendRender.web.util.json.JsonMapData; 5 7 import org.springframework.data.jpa.repository.JpaRepository; 6 import org.springframework.data.jpa.repository.Modifying;7 8 import org.springframework.data.jpa.repository.Query; 9 import org.springframework.data.repository.query.Param; 8 10 import org.springframework.stereotype.Repository; 9 11 12 import java.util.List; 10 13 import java.util.Optional; 11 14 … … 13 16 public interface MapRepository extends JpaRepository<IndoorMap, Long> { 14 17 15 // @Modifying16 // @Query(nativeQuery = true,17 // value = "UPDATE maps SET map_data = ?2 WHERE name = ?1")18 // void updateMapData(IndoorMap map);19 //20 // @Modifying21 // @Query(nativeQuery = true,22 // value = "INSERT INTO maps(name,map_data) VALUES (?1, ?2)")23 // void insertMapData(String name, DataJson data);24 18 25 19 @Query(nativeQuery = true, … … 27 21 Optional<IndoorMap> findMapByName(String name); 28 22 29 @Query(nativeQuery = true, 30 value = "SELECT maps.map_data FROM map WHERE name = ?1") 31 Optional<DataJson> findMapDataByName(String name); 23 @Query("FROM IndoorMap m WHERE m.status = ?1") 24 Optional<List<IndoorMap>> findAllByStatus(MAP_STATUS status); 25 26 @Query("FROM IndoorMap m WHERE m.user.id = ?1") 27 Optional<List<IndoorMap>> findAllMapsForUser(long userId); 28 29 @Query("FROM IndoorMap m WHERE m.status = 'PUBLIC'") 30 Optional<List<IndoorMap>> findAllPublicMaps(); 31 32 @Query("FROM IndoorMap m WHERE m.user = ?1 AND m.id = ?2") 33 Optional<IndoorMap> getMapForUser(IMapsUser user, int mapId); 34 35 boolean existsByName(String name); 32 36 33 37 38 Optional<IndoorMap> getIndoorMapByName(String name); 39 @Query(value = "FROM IndoorMap m where m.name = ?1 and m.status = ?2") 40 Optional<IndoorMap> getIndoorMapByNameAndStatus(String name, MAP_STATUS status); 34 41 } -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/repo/UserRepository.java
rd565449 r0c6b92a 11 11 public interface UserRepository extends JpaRepository<IMapsUser, Long> { 12 12 13 // za da testiras queries, kaj so imat specijalen karakter primer @, moras vo navodnici da klajs.14 15 13 @Query(nativeQuery = true, 16 14 value = "SELECT * FROM users u WHERE email= :usremail LIMIT 1") … … 18 16 19 17 @Query(nativeQuery = true, 20 value = "SELECT * FROM users u WHERE u.name = ?1 LIMIT 1") 21 IMapsUser findUserByName(String usrname); 18 value = "SELECT * FROM users u WHERE u.username = ?1 LIMIT 1") 19 Optional<IMapsUser> findUserByName(String usrname); 20 21 @Query(value = "FROM IMapsUser u WHERE u.username = ?1 OR u.email = ?1") 22 Optional<IMapsUser> getIMapsUserByUsernameOrEmail(String usernameOrEmail); 22 23 23 24 @Query(nativeQuery = true, 24 25 value = "SELECT * FROM users u WHERE u.id= ?1") 25 IMapsUser getUserById(Long usrid); 26 26 Optional<IMapsUser> getUserById(Long usrid); 27 27 } -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/security/JwtFilter.java
rd565449 r0c6b92a 1 1 package internettehnologii.imaps.backendRender.web.security; 2 2 3 import internettehnologii.imaps.backendRender.web.service. JWTService;4 import internettehnologii.imaps.backendRender.web.service. MapUserDetailsService;3 import internettehnologii.imaps.backendRender.web.service.impl.JWTService; 4 import internettehnologii.imaps.backendRender.web.service.impl.MapUserDetailsService; 5 5 import jakarta.servlet.FilterChain; 6 6 import jakarta.servlet.ServletException; … … 52 52 UserDetails userDetails = context.getBean(MapUserDetailsService.class).loadUserByUsername(username); 53 53 if(jwtService.validateToken(token,userDetails)){ 54 UsernamePasswordAuthenticationToken upAuthToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); 54 UsernamePasswordAuthenticationToken upAuthToken = new UsernamePasswordAuthenticationToken(userDetails, null, jwtService.getAuthorities(token)); 55 System.out.println("TOKEN CLAIMS: " + jwtService.getAuthorities(token)); 55 56 upAuthToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 56 57 SecurityContextHolder.getContext().setAuthentication(upAuthToken); -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/security/WebSecurityConfig.java
rd565449 r0c6b92a 1 1 package internettehnologii.imaps.backendRender.web.security; 2 2 3 import internettehnologii.imaps.backendRender.web.service. MapUserDetailsService;3 import internettehnologii.imaps.backendRender.web.service.impl.MapUserDetailsService; 4 4 import org.springframework.beans.factory.annotation.Autowired; 5 5 import org.springframework.context.annotation.Bean; … … 36 36 .csrf(AbstractHttpConfigurer::disable) 37 37 .cors(Customizer.withDefaults()) 38 .authorizeHttpRequests(request -> request.requestMatchers("/api/auth/**","api/public/**") 39 .permitAll() 38 .authorizeHttpRequests(request -> 39 request.requestMatchers("/protected/**") 40 .hasRole("USER") 41 .requestMatchers("/api/admin/**") 42 .hasRole("ADMIN") 40 43 .anyRequest() 41 . authenticated())44 .permitAll()) 42 45 .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) 43 46 .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class); … … 64 67 65 68 66 //TODO password encoding67 68 69 @Bean 69 70 public AuthenticationProvider authenticationProvider() { -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/service/impl/JWTService.java
rd565449 r0c6b92a 1 package internettehnologii.imaps.backendRender.web.service ;1 package internettehnologii.imaps.backendRender.web.service.impl; 2 2 3 3 import io.jsonwebtoken.Claims; 4 4 import io.jsonwebtoken.Jwts; 5 5 import io.jsonwebtoken.security.Keys; 6 import org.springframework.security.core.GrantedAuthority; 7 import org.springframework.security.core.authority.SimpleGrantedAuthority; 6 8 import org.springframework.security.core.userdetails.UserDetails; 7 9 import org.springframework.stereotype.Service; … … 9 11 import javax.crypto.KeyGenerator; 10 12 import javax.crypto.SecretKey; 11 import java.security.Key;12 13 import java.security.NoSuchAlgorithmException; 13 import java.security.SignatureException; 14 import java.util.Base64; 15 import java.util.Date; 16 import java.util.HashMap; 17 import java.util.Map; 14 import java.util.*; 18 15 import java.util.function.Function; 19 import java.util. prefs.BackingStoreException;16 import java.util.stream.Collectors; 20 17 21 18 … … 36 33 37 34 38 public String generateToken( String username){35 public String generateToken(UserDetails userDetails){ 39 36 Map<String,Object> claims = new HashMap<>(); 37 String authorities = userDetails.getAuthorities().stream() 38 .map(GrantedAuthority::getAuthority) 39 .collect(Collectors.joining(",")); 40 claims.put("roles", authorities); 41 40 42 return Jwts 41 43 .builder() 42 44 .claims() 43 45 .add(claims) 44 .subject(user name)46 .subject(userDetails.getUsername()) 45 47 .issuedAt(new Date(System.currentTimeMillis())) 46 .expiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000)) 48 .expiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000)) // 1 sat traet token 47 49 .and() 48 50 .signWith(getKey()) 49 51 .compact(); 52 } 53 54 public Collection<GrantedAuthority> getAuthorities(String token){ 55 Claims claims = extractAllClaims(token); 56 String roles = claims.get("roles", String.class); 57 58 return Arrays.stream(roles.split(",")) 59 .map(SimpleGrantedAuthority::new) 60 .collect(Collectors.toList()); 50 61 } 51 62 -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/service/impl/MapUserDetailsService.java
rd565449 r0c6b92a 1 package internettehnologii.imaps.backendRender.web.service ;1 package internettehnologii.imaps.backendRender.web.service.impl; 2 2 3 3 … … 5 5 import internettehnologii.imaps.backendRender.web.repo.UserRepository; 6 6 import internettehnologii.imaps.backendRender.web.util.UserPrincipal; 7 import org.springframework.beans.factory.annotation.Autowired;8 7 import org.springframework.security.core.userdetails.UserDetails; 9 8 import org.springframework.security.core.userdetails.UserDetailsService; … … 11 10 import org.springframework.stereotype.Service; 12 11 12 import java.util.Optional; 13 13 14 @Service 14 15 public class MapUserDetailsService implements UserDetailsService { 15 @Autowired 16 private UserRepository userRepository; 16 private final UserRepository userRepository; 17 18 public MapUserDetailsService(UserRepository userRepository) { 19 this.userRepository = userRepository; 20 } 21 17 22 @Override 18 23 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 19 IMapsUseruser = userRepository.findUserByName(username);20 if(user == null) {24 Optional<IMapsUser> user = userRepository.findUserByName(username); 25 if(user.isEmpty()) { 21 26 throw new UsernameNotFoundException(username); 22 27 } 23 28 24 return new UserPrincipal(user );29 return new UserPrincipal(user.get()); 25 30 } 26 31 } -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/util/UserPrincipal.java
rd565449 r0c6b92a 3 3 import internettehnologii.imaps.backendRender.web.entities.IMapsUser; 4 4 import org.springframework.security.core.GrantedAuthority; 5 import org.springframework.security.core.authority.SimpleGrantedAuthority; 5 6 import org.springframework.security.core.userdetails.UserDetails; 6 7 … … 16 17 @Override 17 18 public Collection<? extends GrantedAuthority> getAuthorities() { 18 return List.of();19 return user.getRoles().stream().map(r -> new SimpleGrantedAuthority("ROLE_" + r.getName())).toList(); 19 20 } 20 21 -
imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/util/json/JsonNodeConverter.java
rd565449 r0c6b92a 1 package internettehnologii.imaps.backendRender.web. security.json;1 package internettehnologii.imaps.backendRender.web.util.json; 2 2 3 3 import com.fasterxml.jackson.databind.JsonNode; -
imaps-backend/backendRender/src/main/resources/application.properties
rd565449 r0c6b92a 1 1 spring.application.name=backendRender 2 spring.datasource.url=jdbc:postgresql://localhost: 6432/imaps3 spring.datasource.username= imaps_admin4 spring.datasource.password= iMapsResen20242 spring.datasource.url=jdbc:postgresql://localhost:5432/imaps_prod 3 spring.datasource.username=${DB_USER} 4 spring.datasource.password=${DB_PASS} 5 5 spring.jpa.hibernate.ddl-auto=validate 6 6 spring.jpa.show-sql=true 7 7 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect 8 8 spring.jpa.properties.hibernate.format_sql=true 9 logging.level.org.springframework.security=DEBUG10 9 10 logging.level.org.springframework.web=DEBUG 11 -
imaps-backend/backendRender/src/test/java/internettehnologii/imaps/backendRender/RouteGraphTest.java
rd565449 r0c6b92a 24 24 25 25 List<MapNode> nodes = Arrays.asList(nodeA, nodeB, nodeC,nodeD); 26 routeGraph = new RouteGraph(nodes); 26 routeGraph = new RouteGraph(); 27 routeGraph.loadNodeNames(nodes); 27 28 } 28 29
Note:
See TracChangeset
for help on using the changeset viewer.