Ignore:
Timestamp:
12/12/24 17:06:06 (5 weeks ago)
Author:
stefan toskovski <stefantoska84@…>
Branches:
main
Parents:
d565449
Message:

Pred finalna verzija

Location:
imaps-backend/backendRender/src/main
Files:
50 added
9 deleted
13 edited
3 moved

Legend:

Unmodified
Added
Removed
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/graph/Edge.java

    rd565449 r0c6b92a  
    44import lombok.Getter;
    55import lombok.Setter;
     6import lombok.ToString;
    67
    78import java.util.Map;
    89
    910@Setter @Getter
     11@ToString
    1012public class Edge{
    1113  private MapNode node;
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/graph/MapNode.java

    rd565449 r0c6b92a  
    1414    private Coordinates<Double,Double> coordinates;
    1515    private List<String> connectionNames = new ArrayList<>();
     16    private String className;
     17    private int floorNumber;
    1618
    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) {
    1820        this.name = name;
    1921        this.description = description;
    2022        this.coordinates = coordinates;
     23        this.className = className;
     24        this.floorNumber = floorNumber;
    2125    }
    2226
     
    2731    }
    2832
    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     }
    3533
    3634    public MapNode() {
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/graph/MapNodeParser.java

    rd565449 r0c6b92a  
    22
    33
    4 import com.fasterxml.jackson.core.JsonProcessingException;
    54import com.fasterxml.jackson.databind.JsonNode;
    65import com.fasterxml.jackson.databind.ObjectMapper;
     
    109
    1110public class MapNodeParser {
    12     public List<MapNode> parseAndCreateNodes(String mapJson) throws Exception {
     11
     12
     13    public List<MapNode> parseAndCreate(String mapJson) throws Exception {
    1314        final List<MapNode> mapNodes = new ArrayList<>();
    1415
    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        }
    2019
    2120        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));
    2322
    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);
    4334                    }
    44 
    45                     mapNodes.add(mapNode);
    46 
    47                 } catch (JsonProcessingException e) {
    48                     throw new RuntimeException(e);
    4935                }
    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;
    5643    }
    5744
    5845
    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");
    6654
    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) {
    8057            mapNode.setConnectedRoom(connectedRoom);
    8158        }
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/graph/RouteGraph.java

    rd565449 r0c6b92a  
    77    private final Map<String, MapNode> nameToNodeMap = new HashMap<>();
    88
    9     public RouteGraph(List<MapNode> nodes) {
    109
    11 
     10    public void loadNodeNames(List<MapNode> nodes){
    1211        for (MapNode node : nodes) {
    1312            nameToNodeMap.put(node.getName(), node);
    1413        }
    1514
    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()) {
    1722            for (String connectionName : mapNode.getConnectionNames()) {
     23                System.out.println("CONN: " + mapNode.getName() + " " + connectionName);
    1824                MapNode connectedNode = nameToNodeMap.get(connectionName);
    1925                if (connectedNode != null) {
    2026                    addEdge(mapNode, connectedNode);
     27                }else {
     28                    System.out.println("CANT ADD EDGE ========== " + "FROM: " + mapNode.getName() + " TO: " + connectionName);
    2129                }
    2230            }
     
    2836        double x1 = a.getCoordinates().x;
    2937        double y1 = a.getCoordinates().y;
     38
    3039        double x2 = b.getCoordinates().x;
    3140        double y2 = b.getCoordinates().y;
     
    4251        if (sourceNode == null || targetNode == null) {
    4352            System.out.println(this.toString());
     53            System.out.println("SOURCE NODE FROM MAP " + sourceNode);
     54            System.out.println("TARGET NODE FROM MAP " + targetNode);
    4455            throw new IllegalArgumentException("Source or target node not found. SOURCE: " + source + " TARGET: " + target);
    4556        }
     
    95106        }
    96107
    97         Collections.reverse(path); // deka se staveni vo obraten redosled, pa reverse ni dava pateka od pocetok do kraj.
     108        Collections.reverse(path);// deka se staveni vo obraten redosled, pa reverse ni dava pateka od pocetok do kraj.
    98109
    99110        if (!path.isEmpty() && path.get(0).equals(sourceNode)) {
     111            System.out.println("FOUND PATH: " + path);
    100112            return path;
    101113        } else {
     
    129141        }
    130142        return null;
     143        //throw new IllegalArgumentException("Cant find room connected to entrance: " + roomName);
    131144    }
    132 
    133     public String getNodeNameByName(String name){
    134         return nameToNodeMap.get(name).getName();
    135     }
    136 
    137145
    138146
     
    145153            MapNode node = entry.getKey();
    146154            Set<Edge> connectedNodes = entry.getValue();
     155
     156            System.out.println("CONN NODES PRINT: " + connectedNodes);
    147157
    148158            sb.append(node.getName()).append(" -> ");
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/controllers/AuthController.java

    rd565449 r0c6b92a  
    22
    33import 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;
     4import internettehnologii.imaps.backendRender.web.entities.IndoorMap;
     5import internettehnologii.imaps.backendRender.web.service.impl.JWTService;
     6import internettehnologii.imaps.backendRender.web.service.impl.MapUserDetailsService;
     7import internettehnologii.imaps.backendRender.web.service.impl.UserServiceImpl;
     8import internettehnologii.imaps.backendRender.web.service.interfaces.MapService;
     9import internettehnologii.imaps.backendRender.web.util.DTO.UserAuthSuccessDTO;
     10import internettehnologii.imaps.backendRender.web.util.DTO.UserLoginDTO;
    711import jakarta.servlet.http.HttpServletRequest;
    812import org.springframework.beans.factory.annotation.Autowired;
    913import org.springframework.context.ApplicationContext;
     14import org.springframework.http.ResponseEntity;
    1015import org.springframework.security.core.userdetails.UserDetails;
     16import org.springframework.security.core.userdetails.UserDetailsService;
    1117import org.springframework.web.bind.annotation.*;
    1218
     19import javax.management.relation.RoleNotFoundException;
    1320import java.util.HashMap;
    14 import java.util.List;
    1521import java.util.Map;
    1622
     
    2127
    2228    @Autowired
    23     private UserService userService;
     29    private UserServiceImpl userService;
    2430    @Autowired
    2531    private JWTService jwtService;
     
    2935
    3036    @PostMapping("/register")
    31     public IMapsUser register(@RequestBody IMapsUser user) {
     37    public IMapsUser register(@RequestBody IMapsUser user) throws RoleNotFoundException {
    3238        return userService.register(user);
    3339    }
    3440
    3541    @PostMapping("/login")
    36     public Map<String, Object> login(@RequestBody IMapsUser user, HttpServletRequest request) {
     42    public Map<String, Object> login(@RequestBody UserLoginDTO user) {
    3743        System.out.println(user);
    3844        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
    4256        return response;
    4357    }
    4458
    4559
    46     //ZA TESTIRANJE
    47     @GetMapping("/list")
    48     public List<IMapsUser> showUsers() {
    49         return userService.getUsers();
    50     }
    51 
    5260    @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");
    5463        Map<String, Object> response = new HashMap<>();
    5564        try{
     
    5766            UserDetails userDetails = context.getBean(MapUserDetailsService.class).loadUserByUsername(username);
    5867            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);
    6172            }
    6273
    63             System.out.println(auth + " auth");
     74            response.put("username", username);
     75            System.out.println("Authenticated user: " + username);
    6476        } catch (Exception e){
     77            response.put("auth",false);
    6578            System.out.println("ERROR: NOT AUTHENTICATED: " + e.getMessage());
    6679        }
    6780
    68         return response;
     81        return ResponseEntity.ok(response);
    6982
    7083    }
     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
    7192}
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/entities/IMapsUser.java

    rd565449 r0c6b92a  
    11package internettehnologii.imaps.backendRender.web.entities;
     2import internettehnologii.imaps.backendRender.web.entities.RBA.Role;
    23import jakarta.persistence.*;
    34import lombok.Getter;
    45import lombok.Setter;
    56
    6 @Getter
     7import java.time.LocalDateTime;
     8import java.util.Date;
     9import java.util.HashSet;
     10import java.util.Set;
     11
    712@Entity
    813@Table(name = "users")
     14@Getter @Setter
    915public class IMapsUser {
    1016    @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")
    2019    private int id;
    21     @Setter
    22     @Column(name = "name")
    2320    private String username;
    24     @Setter
    2521    private String email;
    26     @Getter @Setter
    2722    private String password;
    2823
     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<>();
    2943
    3044    public IMapsUser() {}
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/entities/IndoorMap.java

    rd565449 r0c6b92a  
    11package internettehnologii.imaps.backendRender.web.entities;
    2 import internettehnologii.imaps.backendRender.web.security.json.DataJson;
    32import jakarta.persistence.*;
    4 import org.hibernate.annotations.JdbcTypeCode;
    5 import org.hibernate.type.SqlTypes;
     3import lombok.Getter;
     4import lombok.Setter;
     5
     6import java.time.LocalDateTime;
     7import java.util.ArrayList;
     8import java.util.HashSet;
     9import java.util.List;
     10import java.util.Set;
    611
    712@Entity
     13@Getter @Setter
    814@Table(name = "maps")
    915public class IndoorMap {
    1016    @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")
    2019    private Integer id;
    21     private String name;
    2220
    23     @JdbcTypeCode(SqlTypes.JSON)
    24     private DataJson mapData; //json
     21    private String name = "";
    2522
    26     @JdbcTypeCode(SqlTypes.JSON)
    27     private DataJson graphData; //json
     23    @Column(name = "gmaps_url")
     24    private String gmapsUrl = "";
    2825
    29     private boolean isPublic;
    30     private String url;
     26    @Enumerated(EnumType.STRING)
     27    private MAP_STATUS status;
    3128
     29    @Column(name = "published_at")
     30    private LocalDateTime publishedAt;
    3231
    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;
    3861    }
    3962
    40     public IndoorMap() {
    41 
     63    public int getFavouriteCount(){
     64        return this.favoritedBy.size();
    4265    }
    4366
    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();
    5070    }
    5171
    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     @Override
    119     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     }
    12972}
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/repo/MapRepository.java

    rd565449 r0c6b92a  
    11package internettehnologii.imaps.backendRender.web.repo;
    22
     3import internettehnologii.imaps.backendRender.web.entities.IMapsUser;
    34import internettehnologii.imaps.backendRender.web.entities.IndoorMap;
    4 import internettehnologii.imaps.backendRender.web.security.json.DataJson;
     5import internettehnologii.imaps.backendRender.web.entities.MAP_STATUS;
     6import internettehnologii.imaps.backendRender.web.util.json.JsonMapData;
    57import org.springframework.data.jpa.repository.JpaRepository;
    6 import org.springframework.data.jpa.repository.Modifying;
    78import org.springframework.data.jpa.repository.Query;
     9import org.springframework.data.repository.query.Param;
    810import org.springframework.stereotype.Repository;
    911
     12import java.util.List;
    1013import java.util.Optional;
    1114
     
    1316public interface MapRepository extends JpaRepository<IndoorMap, Long> {
    1417
    15 //    @Modifying
    16 //    @Query(nativeQuery = true,
    17 //            value = "UPDATE maps SET map_data = ?2 WHERE name = ?1")
    18 //    void updateMapData(IndoorMap map);
    19 //
    20 //    @Modifying
    21 //    @Query(nativeQuery = true,
    22 //            value = "INSERT INTO maps(name,map_data) VALUES (?1, ?2)")
    23 //    void insertMapData(String name, DataJson data);
    2418
    2519    @Query(nativeQuery = true,
     
    2721    Optional<IndoorMap> findMapByName(String name);
    2822
    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);
    3236
    3337
     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);
    3441}
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/repo/UserRepository.java

    rd565449 r0c6b92a  
    1111public interface UserRepository extends JpaRepository<IMapsUser, Long> {
    1212
    13     // za da testiras queries, kaj so imat specijalen karakter primer @, moras vo navodnici da klajs.
    14 
    1513    @Query(nativeQuery = true,
    1614            value = "SELECT * FROM users u WHERE email= :usremail LIMIT 1")
     
    1816
    1917    @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);
    2223
    2324    @Query(nativeQuery = true,
    2425    value = "SELECT * FROM users u WHERE u.id= ?1")
    25     IMapsUser getUserById(Long usrid);
    26 
     26    Optional<IMapsUser> getUserById(Long usrid);
    2727}
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/security/JwtFilter.java

    rd565449 r0c6b92a  
    11package internettehnologii.imaps.backendRender.web.security;
    22
    3 import internettehnologii.imaps.backendRender.web.service.JWTService;
    4 import internettehnologii.imaps.backendRender.web.service.MapUserDetailsService;
     3import internettehnologii.imaps.backendRender.web.service.impl.JWTService;
     4import internettehnologii.imaps.backendRender.web.service.impl.MapUserDetailsService;
    55import jakarta.servlet.FilterChain;
    66import jakarta.servlet.ServletException;
     
    5252                    UserDetails userDetails = context.getBean(MapUserDetailsService.class).loadUserByUsername(username);
    5353                    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));
    5556                        upAuthToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
    5657                        SecurityContextHolder.getContext().setAuthentication(upAuthToken);
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/security/WebSecurityConfig.java

    rd565449 r0c6b92a  
    11package internettehnologii.imaps.backendRender.web.security;
    22
    3 import internettehnologii.imaps.backendRender.web.service.MapUserDetailsService;
     3import internettehnologii.imaps.backendRender.web.service.impl.MapUserDetailsService;
    44import org.springframework.beans.factory.annotation.Autowired;
    55import org.springframework.context.annotation.Bean;
     
    3636                 .csrf(AbstractHttpConfigurer::disable)
    3737                 .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")
    4043                         .anyRequest()
    41                          .authenticated())
     44                         .permitAll())
    4245                 .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
    4346                 .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
     
    6467
    6568
    66     //TODO password encoding
    67 
    6869    @Bean
    6970    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;
     1package internettehnologii.imaps.backendRender.web.service.impl;
    22
    33import io.jsonwebtoken.Claims;
    44import io.jsonwebtoken.Jwts;
    55import io.jsonwebtoken.security.Keys;
     6import org.springframework.security.core.GrantedAuthority;
     7import org.springframework.security.core.authority.SimpleGrantedAuthority;
    68import org.springframework.security.core.userdetails.UserDetails;
    79import org.springframework.stereotype.Service;
     
    911import javax.crypto.KeyGenerator;
    1012import javax.crypto.SecretKey;
    11 import java.security.Key;
    1213import 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;
     14import java.util.*;
    1815import java.util.function.Function;
    19 import java.util.prefs.BackingStoreException;
     16import java.util.stream.Collectors;
    2017
    2118
     
    3633
    3734
    38     public String generateToken(String username){
     35    public String generateToken(UserDetails userDetails){
    3936        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       
    4042        return Jwts
    4143                .builder()
    4244                .claims()
    4345                .add(claims)
    44                 .subject(username)
     46                .subject(userDetails.getUsername())
    4547                .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
    4749                .and()
    4850                .signWith(getKey())
    4951                .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());
    5061    }
    5162
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/service/impl/MapUserDetailsService.java

    rd565449 r0c6b92a  
    1 package internettehnologii.imaps.backendRender.web.service;
     1package internettehnologii.imaps.backendRender.web.service.impl;
    22
    33
     
    55import internettehnologii.imaps.backendRender.web.repo.UserRepository;
    66import internettehnologii.imaps.backendRender.web.util.UserPrincipal;
    7 import org.springframework.beans.factory.annotation.Autowired;
    87import org.springframework.security.core.userdetails.UserDetails;
    98import org.springframework.security.core.userdetails.UserDetailsService;
     
    1110import org.springframework.stereotype.Service;
    1211
     12import java.util.Optional;
     13
    1314@Service
    1415public 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
    1722    @Override
    1823    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    19        IMapsUser user = userRepository.findUserByName(username);
    20        if(user == null) {
     24       Optional<IMapsUser> user = userRepository.findUserByName(username);
     25       if(user.isEmpty()) {
    2126           throw new UsernameNotFoundException(username);
    2227       }
    2328
    24        return new UserPrincipal(user);
     29       return new UserPrincipal(user.get());
    2530    }
    2631}
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/util/UserPrincipal.java

    rd565449 r0c6b92a  
    33import internettehnologii.imaps.backendRender.web.entities.IMapsUser;
    44import org.springframework.security.core.GrantedAuthority;
     5import org.springframework.security.core.authority.SimpleGrantedAuthority;
    56import org.springframework.security.core.userdetails.UserDetails;
    67
     
    1617    @Override
    1718    public Collection<? extends GrantedAuthority> getAuthorities() {
    18         return List.of();
     19        return user.getRoles().stream().map(r -> new SimpleGrantedAuthority("ROLE_" + r.getName())).toList();
    1920    }
    2021
  • imaps-backend/backendRender/src/main/java/internettehnologii/imaps/backendRender/web/util/json/JsonNodeConverter.java

    rd565449 r0c6b92a  
    1 package internettehnologii.imaps.backendRender.web.security.json;
     1package internettehnologii.imaps.backendRender.web.util.json;
    22
    33import com.fasterxml.jackson.databind.JsonNode;
  • imaps-backend/backendRender/src/main/resources/application.properties

    rd565449 r0c6b92a  
    11spring.application.name=backendRender
    2 spring.datasource.url=jdbc:postgresql://localhost:6432/imaps
    3 spring.datasource.username=imaps_admin
    4 spring.datasource.password=iMapsResen2024
     2spring.datasource.url=jdbc:postgresql://localhost:5432/imaps_prod
     3spring.datasource.username=${DB_USER}
     4spring.datasource.password=${DB_PASS}
    55spring.jpa.hibernate.ddl-auto=validate
    66spring.jpa.show-sql=true
    77spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
    88spring.jpa.properties.hibernate.format_sql=true
    9 logging.level.org.springframework.security=DEBUG
    109
     10logging.level.org.springframework.web=DEBUG
     11
Note: See TracChangeset for help on using the changeset viewer.