BobTheFarmer / Colin-Blog3

MIT License
0 stars 2 forks source link

JWT Hacks #11

Open BobTheFarmer opened 10 months ago

BobTheFarmer commented 10 months ago

Popcorn Hacks

Popcorn Hacks

Poster contest submission

Poster-4

My API working in postman

Screenshot 2024-01-07 at 8 21 35 PM

Basic API

I modified the person jwt class to be a dog instead.

Dog.java:

package com.nighthawk.spring_portfolio.mvc.dog;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Convert;
import static jakarta.persistence.FetchType.EAGER;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;

import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;
import org.springframework.format.annotation.DateTimeFormat;

import com.vladmihalcea.hibernate.type.json.JsonType;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Convert(attributeName ="dog", converter = JsonType.class)
public class Dog {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NonNull
    @Size(min = 2, max = 30, message = "Name (2 to 30 chars)")
    private String name;

    @NonNull
    private String breed;

    private float weight;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date dob;

    @JdbcTypeCode(SqlTypes.JSON)
    @Column(columnDefinition = "jsonb")
    private Map<String,Map<String, Object>> stats = new HashMap<>();

    public Dog(String name, String breed, float weight, Date dob) {
        this.name = name;
        this.breed = breed;
        this.weight = weight;
        this.dob = dob;
    }

    public int getAge() {
        if (this.dob != null) {
            LocalDate birthDay = this.dob.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            return Period.between(birthDay, LocalDate.now()).getYears();
        }
        return -1;
    }

    public static Dog[] init() {
        Dog d1 = new Dog();
        d1.setName("Fido");
        d1.setBreed("Labrador");
        d1.setWeight(30.0f);
        try {
            Date d = new SimpleDateFormat("MM-dd-yyyy").parse("12-08-2016");
            d1.setDob(d);
        } catch (Exception e) {
        }

        Dog d2 = new Dog();
        d2.setName("Rex");
        d2.setBreed("German Shepherd");
        d2.setWeight(40.0f);
        try {
            Date d = new SimpleDateFormat("MM-dd-yyyy").parse("01-02-2017");
            d2.setDob(d);
        } catch (Exception e) {
        }

        Dog dogs[] = {d1, d2};
        return(dogs);
    }

    public static void main(String[] args) {
        Dog dogs[] = init();
        for(Dog dog : dogs) {
            System.out.println(dog);
        }
    }
}

API controller

package com.nighthawk.spring_portfolio.mvc.dog;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.text.SimpleDateFormat;

@RestController
@RequestMapping("/api/dog")
public class DogApiController {

    @Autowired
    private DogJpaRepository repository;

    @Autowired
    private DogDetailsService dogDetailsService;

    @GetMapping("/")
    public ResponseEntity<List<Dog>> getDogs() {
        return new ResponseEntity<>( repository.findAllByOrderByNameAsc(), HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Dog> getDog(@PathVariable long id) {
        Optional<Dog> optional = repository.findById(id);
        if (optional.isPresent()) {
            Dog dog = optional.get();
            return new ResponseEntity<>(dog, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);       
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Dog> deleteDog(@PathVariable long id) {
        Optional<Dog> optional = repository.findById(id);
        if (optional.isPresent()) {
            Dog dog = optional.get();
            repository.deleteById(id);
            return new ResponseEntity<>(dog, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST); 
    }

    @PostMapping( "/post")
    public ResponseEntity<Object> postDog(@RequestParam("name") String name,
                                          @RequestParam("breed") String breed,
                                          @RequestParam("weight") float weight,
                                          @RequestParam("dob") String dobString) {
        Date dob;
        try {
            dob = new SimpleDateFormat("MM-dd-yyyy").parse(dobString);
        } catch (Exception e) {
            return new ResponseEntity<>(dobString +" error; try MM-dd-yyyy", HttpStatus.BAD_REQUEST);
        }
        Dog dog = new Dog(name, breed, weight, dob);
        dogDetailsService.save(dog);
        return new ResponseEntity<>(name +" is created successfully", HttpStatus.CREATED);
    }

    @PostMapping(value = "/search", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Object> dogSearch(@RequestBody final Map<String,String> map) {
        String term = (String) map.get("term");
        List<Dog> list = repository.findByNameContainingIgnoreCaseOrBreedContainingIgnoreCase(term, term);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }
}