91 lines
2 KiB
Go
91 lines
2 KiB
Go
|
package api
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"github.com/gorilla/mux"
|
||
|
"net/http"
|
||
|
"sonarqube-badge/router/middlewares"
|
||
|
"sonarqube-badge/router/utils"
|
||
|
"sonarqube-badge/security/aes"
|
||
|
"sonarqube-badge/store"
|
||
|
"strconv"
|
||
|
)
|
||
|
|
||
|
type ProjectPayload struct {
|
||
|
Name string `json:"name"`
|
||
|
Token string `json:"token"`
|
||
|
}
|
||
|
|
||
|
func setProject(w http.ResponseWriter, r *http.Request) {
|
||
|
db, cfg, _, isError := utils.VerifyUser(w, r)
|
||
|
if isError {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
idString := mux.Vars(r)["id"]
|
||
|
id, err := strconv.Atoi(idString)
|
||
|
payload := ProjectPayload{}
|
||
|
err = json.NewDecoder(r.Body).Decode(&payload)
|
||
|
if err != nil {
|
||
|
w.WriteHeader(http.StatusBadRequest)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
project := store.Project{}
|
||
|
db.Where("id = ?", id).First(&project)
|
||
|
if project.ID == 0 {
|
||
|
w.WriteHeader(http.StatusNotFound)
|
||
|
}
|
||
|
|
||
|
project.ProjectName = payload.Name
|
||
|
if project.Token != payload.Token {
|
||
|
project.Token = aes.EncryptAES(cfg.Secret, payload.Token)
|
||
|
}
|
||
|
db.Save(&project)
|
||
|
}
|
||
|
|
||
|
func createProject(w http.ResponseWriter, r *http.Request) {
|
||
|
db, _, user, isError := utils.VerifyUser(w, r)
|
||
|
if isError {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
project := user.CreateProject(db)
|
||
|
|
||
|
w.WriteHeader(http.StatusOK)
|
||
|
w.Header().Set("Content-Type", "application/json")
|
||
|
json.NewEncoder(w).Encode(project)
|
||
|
}
|
||
|
|
||
|
func deleteProject(w http.ResponseWriter, r *http.Request) {
|
||
|
db, _, user, isError := utils.VerifyUser(w, r)
|
||
|
if isError {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
projectIdString := mux.Vars(r)["id"]
|
||
|
projectId, err := strconv.Atoi(projectIdString)
|
||
|
if err != nil {
|
||
|
w.WriteHeader(http.StatusBadRequest)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
project := store.Project{}
|
||
|
db.Where("id = ? AND owner_id = ?", projectId, user.ID).First(&project)
|
||
|
if project.ID == 0 {
|
||
|
w.WriteHeader(http.StatusNotFound)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
db.Delete(&project)
|
||
|
w.WriteHeader(http.StatusOK)
|
||
|
}
|
||
|
|
||
|
func ProjectRouter(r *mux.Router) {
|
||
|
sr := r.PathPrefix("").Subrouter()
|
||
|
sr.Use(middlewares.CheckJwtToken)
|
||
|
sr.HandleFunc("", createProject).Methods(http.MethodPost)
|
||
|
sr.HandleFunc("/{id}", setProject).Methods(http.MethodPost)
|
||
|
sr.HandleFunc("/{id}", deleteProject).Methods(http.MethodDelete)
|
||
|
}
|