-
Notifications
You must be signed in to change notification settings - Fork 578
/
Copy pathhandlers.go
114 lines (96 loc) · 2.42 KB
/
handlers.go
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package handlers
import (
"encoding/json"
"fmt"
"github.com/go-oauth2/oauth2/v4/server"
"io"
"log"
"net/http"
"net/http/httputil"
"os"
"strings"
"time"
)
var dumpvar bool
const (
authServerURL string = "http://localhost:9096"
)
type Handlers struct {
Permissions
Authentication
}
func NewHandlers(dv bool, srv *server.Server) *Handlers {
dumpvar = dv
perm := NewPermissions(srv)
auth := NewAuthentication(srv)
return &Handlers{
Permissions: perm,
Authentication: auth,
}
}
type Permissions struct {
srv *server.Server
}
func NewPermissions(srv *server.Server) Permissions {
return Permissions{
srv: srv,
}
}
// Endpoint to validate token and permission
func (p Permissions) ValidPermission(w http.ResponseWriter, r *http.Request) {
if dumpvar {
_ = dumpRequest(os.Stdout, "validPermission", r) // Ignore the error
}
// validate the token
token, err := p.srv.ValidationBearerToken(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
permission := r.URL.Query().Get("permission")
// validate the permission
switch permission {
case "read":
log.Println("In read permission")
if !strings.Contains(token.GetScope(), "read") && !strings.Contains(token.GetScope(), "all") {
http.Error(w, "Unauthorized", http.StatusBadRequest)
return
}
case "write":
log.Println("In write permission")
if !strings.Contains(token.GetScope(), "write") && !strings.Contains(token.GetScope(), "all") {
fmt.Println("do not have Write permission.")
http.Error(w, "Unauthorized", http.StatusBadRequest)
return
}
case "all":
log.Println("In all permission")
if !strings.Contains(token.GetScope(), "all") {
fmt.Println("do not have All permission.")
http.Error(w, "Unauthorized", http.StatusBadRequest)
return
}
default:
log.Println("In default permission")
http.Error(w, "Unauthorized", http.StatusBadRequest)
return
}
data := map[string]interface{}{
"expires_in": int64(token.GetAccessCreateAt().Add(token.GetAccessExpiresIn()).Sub(time.Now()).Seconds()),
"client_id": token.GetClientID(),
"user_id": token.GetUserID(),
"permission": token.GetScope(),
}
e := json.NewEncoder(w)
e.SetIndent("", " ")
e.Encode(data)
}
func dumpRequest(writer io.Writer, header string, r *http.Request) error {
data, err := httputil.DumpRequest(r, true)
if err != nil {
return err
}
writer.Write([]byte("\n" + header + ": \n"))
writer.Write(data)
return nil
}