Blame view

http_utility.go 3.03 KB
ea858b8a7   Marko Tikvić   refactoring
1
  package webutility
64041a2ea   Marko Tikvić   first commit
2
3
4
5
  
  import (
  	"net/http"
  	"encoding/json"
33d137a67   Marko Tikvić   Functional role c...
6
  	"fmt"
64041a2ea   Marko Tikvić   first commit
7
  )
64041a2ea   Marko Tikvić   first commit
8
9
10
11
  const templateHttpErr500_EN = "An internal server error has occurred."
  const templateHttpErr500_RS = "Došlo je do greške na serveru."
  const templateHttpErr400_EN = "Bad request: invalid request body."
  const templateHttpErr400_RS = "Neispravan zahtev."
33fd58161   markotikvic   minor changes, sh...
12
13
  const templateHttpErr401_EN = "Unauthorized request."
  const templateHttpErr401_RS = "Neautorizovan zahtev."
64041a2ea   Marko Tikvić   first commit
14

33fd58161   markotikvic   minor changes, sh...
15
  type httpError struct {
64041a2ea   Marko Tikvić   first commit
16
17
18
19
20
21
22
23
  	Error   []HttpErrorDesc `json:"error"`
  	Request string          `json:"request"`
  }
  
  type HttpErrorDesc struct {
  	Lang string `json:"lang"`
  	Desc string `json:"description"`
  }
e1fbb41f9   Marko Tikvić   added comments
24
  // ErrorResponse writes HTTP error to w.
33fd58161   markotikvic   minor changes, sh...
25
26
  func ErrorResponse(w http.ResponseWriter, r *http.Request, code int, desc []HttpErrorDesc) {
  	err := httpError{ desc, r.Method + " " + r.URL.Path }
64041a2ea   Marko Tikvić   first commit
27
28
29
  	w.WriteHeader(code)
  	json.NewEncoder(w).Encode(err)
  }
e1fbb41f9   Marko Tikvić   added comments
30
  // BadRequestResponse writes HTTP error 400 to w.
33fd58161   markotikvic   minor changes, sh...
31
32
33
34
  func BadRequestResponse(w http.ResponseWriter, req *http.Request) {
  	ErrorResponse(w, req, http.StatusBadRequest, []HttpErrorDesc{
  		{ "en", templateHttpErr400_EN },
  		{ "rs", templateHttpErr400_RS },
25e001550   Marko Tikvić   exported everything
35
  	})
64041a2ea   Marko Tikvić   first commit
36
  }
e1fbb41f9   Marko Tikvić   added comments
37
  // InternalSeverErrorResponse writes HTTP error 500 to w.
33fd58161   markotikvic   minor changes, sh...
38
39
40
41
  func InternalServerErrorResponse(w http.ResponseWriter, req *http.Request) {
  	ErrorResponse(w, req, http.StatusInternalServerError, []HttpErrorDesc{
  		{ "en", templateHttpErr500_EN },
  		{ "rs", templateHttpErr500_RS },
25e001550   Marko Tikvić   exported everything
42
  	})
64041a2ea   Marko Tikvić   first commit
43
  }
e1fbb41f9   Marko Tikvić   added comments
44
  // UnauthorizedError writes HTTP error 401 to w.
33fd58161   markotikvic   minor changes, sh...
45
46
  func UnauthorizedResponse(w http.ResponseWriter, req *http.Request) {
  	ErrorResponse(w, req, http.StatusUnauthorized, []HttpErrorDesc{
c47161efb   Marko Tikvić   fixed bug: Unauth...
47
48
  		{ "en", templateHttpErr401_EN },
  		{ "rs", templateHttpErr401_RS },
33fd58161   markotikvic   minor changes, sh...
49
50
  	})
  }
33fd58161   markotikvic   minor changes, sh...
51
  // TODO: Check for content type
33d137a67   Marko Tikvić   Functional role c...
52
  // WrapHandler sets common headers, checks for token validity and performs access control checks.
3a5383589   Marko Tikvić   Improved document...
53
  // If authentication passes it calls the handlerFunc.
33d137a67   Marko Tikvić   Functional role c...
54
  func WrapHandler(handlerFunc http.HandlerFunc, authorizedRoles []string) http.HandlerFunc {
64041a2ea   Marko Tikvić   first commit
55
  	return func(w http.ResponseWriter, req *http.Request) {
64041a2ea   Marko Tikvić   first commit
56
  		w.Header().Set("Access-Control-Allow-Origin", "*")
33fd58161   markotikvic   minor changes, sh...
57

64041a2ea   Marko Tikvić   first commit
58
  		w.Header().Set("Access-Control-Allow-Methods",
33fd58161   markotikvic   minor changes, sh...
59
  			"POST, GET, PUT, DELETE, OPTIONS")
64041a2ea   Marko Tikvić   first commit
60
  		w.Header().Set("Access-Control-Allow-Headers",
4b4ea384f   Marko Tikvić   hmm
61
62
  			`Accept, Content-Type, Content-Length,
  			Accept-Encoding, X-CSRF-Token, Authorization`)
33fd58161   markotikvic   minor changes, sh...
63

64041a2ea   Marko Tikvić   first commit
64
65
66
67
68
  		w.Header().Set("Content-Type", "application/json; charset=utf-8")
  
  		if req.Method == "OPTIONS" {
  			return
  		}
33d137a67   Marko Tikvić   Functional role c...
69
  		if authorizedRoles != nil {
33fd58161   markotikvic   minor changes, sh...
70
  			token := req.Header.Get("Authorization")
33d137a67   Marko Tikvić   Functional role c...
71
72
73
74
  			claims, err := ParseAPIToken(token);
  			if err != nil || !roleAuthorized(authorizedRoles, claims) {
  				fmt.Printf("not authorized %s %s...
  ", claims.Username, claims.Role)
4b4ea384f   Marko Tikvić   hmm
75
  				UnauthorizedResponse(w, req)
33fd58161   markotikvic   minor changes, sh...
76
  				return
64041a2ea   Marko Tikvić   first commit
77
78
79
80
81
  			}
  		}
  
  		err := req.ParseForm()
  		if err != nil {
33fd58161   markotikvic   minor changes, sh...
82
  			BadRequestResponse(w, req)
64041a2ea   Marko Tikvić   first commit
83
84
  			return
  		}
4a51e54d7   Marko Tikvić   simplified
85
86
  
  		// execute HandlerFunc
90f4ed079   Marko Tikvić   sped up loadTable()
87
  		handlerFunc(w, req)
64041a2ea   Marko Tikvić   first commit
88
89
  	}
  }
e1fbb41f9   Marko Tikvić   added comments
90
  // NotFoundHandler writes HTTP error 404 to w.
25e001550   Marko Tikvić   exported everything
91
  func NotFoundHandler(w http.ResponseWriter, req *http.Request) {
33fd58161   markotikvic   minor changes, sh...
92
93
94
  	ErrorResponse(w, req, http.StatusNotFound, []HttpErrorDesc{
  		{ "en", "Not found." },
  		{ "rs", "Traženi resurs ne postoji." },
25e001550   Marko Tikvić   exported everything
95
  	})
64041a2ea   Marko Tikvić   first commit
96
  }