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
package models
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"forge.grandlyon.com/apoyen/elections/internal/auth"
)
type capturerDeskRound struct {
CapturerID uint
DeskRoundID uint
}
// handleCapturer handle API calls on Capturer
func (d *DataHandler) handleCapturerDeskRound(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(strings.TrimPrefix(r.URL.Path, "/api/CapturerDeskRound/"))
switch method := r.Method; method {
case "POST":
switch auth.GetLoggedUserTechnical(w, r).Role {
case "ADMIN":
d.postCapturerDeskRound(w, r)
case "CAPTURER", "VISUALIZER":
http.Error(w, ErrorNotAuthorizeMethodOnRessource, http.StatusMethodNotAllowed)
default:
http.Error(w, ErrorRoleOfLoggedUser, http.StatusInternalServerError)
}
case "DELETE":
switch auth.GetLoggedUserTechnical(w, r).Role {
case "ADMIN":
d.deleteCapturerDeskRound(w, r, id)
case "CAPTURER", "VISUALIZER":
http.Error(w, ErrorNotAuthorizeMethodOnRessource, http.StatusMethodNotAllowed)
default:
http.Error(w, ErrorRoleOfLoggedUser, http.StatusInternalServerError)
}
default:
http.Error(w, "method not allowed", 400)
}
}
func (d *DataHandler) postCapturerDeskRound(w http.ResponseWriter, r *http.Request) {
var o capturerDeskRound
err := json.NewDecoder(r.Body).Decode(&o)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
flag, capturer, deskRound := d.checkCapturerAndDeskRound(o)
if !flag {
http.Error(w, ErrorIDDoesNotExist, http.StatusNotFound)
return
}
d.db.Model(&capturer).Association("DeskRounds").Append(&deskRound)
d.db.Preload("DeskRounds").First(&capturer)
json.NewEncoder(w).Encode(capturer)
}
func (d *DataHandler) deleteCapturerDeskRound(w http.ResponseWriter, r *http.Request, id int) {
var o capturerDeskRound
err := json.NewDecoder(r.Body).Decode(&o)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
flag, capturer, deskRound := d.checkCapturerAndDeskRound(o)
if !flag {
http.Error(w, ErrorIDDoesNotExist, http.StatusNotFound)
}
d.db.Model(&capturer).Association("DeskRounds").Delete(&deskRound)
json.NewEncoder(w).Encode(capturer)
}
func (d *DataHandler) checkCapturerAndDeskRound(o capturerDeskRound) (bool, Capturer, DeskRound) {
var capturer Capturer
var deskRound DeskRound
if err := d.db.First(&capturer, o.CapturerID).Error; err != nil {
return false, capturer, deskRound
}
if err := d.db.First(&deskRound, o.DeskRoundID).Error; err != nil {
return false, capturer, deskRound
}
return true, capturer, deskRound
}