IPCheckController.java 2.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
package adt.mainnode.controller;

import adt.mainnode.entity.*;
import adt.mainnode.repository.*;

import java.util.ArrayList;
import java.lang.Integer;
import java.util.List;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@RestController
@RequestMapping("presence_check")
@Api(
        value = "/presence_check",//"/asset",
        produces = MediaType.APPLICATION_JSON_VALUE,
        tags = {"PRESENCE_CHECK"}
)
@Slf4j
public class IPCheckController {

    private final CredentialsRepository credentialsRepository;
    private final HostRepository hostRepository;

    @Autowired
    public IPCheckController(CredentialsRepository credentialsRepository, HostRepository hostRepository) {
        this.credentialsRepository = credentialsRepository;
        this.hostRepository = hostRepository;
    }


    @CrossOrigin
    @ApiOperation(value = "Allows a distributed node to double-check the information about a specific IP.",
            response = Integer.class)
    @ResponseStatus(HttpStatus.CREATED)
    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    int checkIP(HttpServletResponse response, @RequestParam(value = "token") String token,
                @RequestParam(value = "ip") String ip,
                @RequestParam(value = "mac") String mac){//@RequestParam(value = "params") String params) {

        /*String[] paramsArr = params.split("&");
        String token = paramsArr[0];
        String ip = paramsArr[1];
        String mac = paramsArr[2];
        */
        log.info("Received query from Distributed Node DHCP Service. Parameters to check:\nIP: {}\nMAC: {}", ip, mac);

        Credentials credential = credentialsRepository.findByToken(token);

        if(credential != null) {

            List<Host> hosts = null;
            if(mac != null) {
                hosts = hostRepository.findAllByIpAndMac(ip, mac);
            }else{
                // TODO: review later on
                hosts = hostRepository.findAllByIp(ip);
            }

            if (hosts != null && hosts.size() > 0){

                return 1;
            }else{

                return 0;
            }
        }

        try {
            response.sendError(400, "Unrecognized token. Access denied.");
        }catch(IOException ioe){
            // handled
        }

        return -1;
    }


}