-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
executable file
·110 lines (88 loc) · 2.46 KB
/
server.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
package main
// * Author: Antonio Orozco
// * Date: January 26 2017
import (
"log"
"net/http"
"github.com/RangelReale/osin"
)
// Start Inicializa el servidor de oAuth2
func main() {
storage := NewStore()
err := storage.InitSchemas()
if err != nil {
panic(err)
}
cfg := osin.NewServerConfig()
cfg.AllowGetAccessRequest = true
cfg.AllowClientSecretInParams = true
cfg.AccessExpiration = 7200
cfg.AllowedAccessTypes = osin.AllowedAccessType{
osin.AUTHORIZATION_CODE,
osin.CLIENT_CREDENTIALS,
osin.REFRESH_TOKEN,
}
// TestStorage implements the "osin.Storage" interface
server := osin.NewServer(cfg, storage)
// Authorization code endpoint
http.HandleFunc("/oauth2/authorize", func(w http.ResponseWriter, r *http.Request) {
resp := server.NewResponse()
// defer resp.Close()
var hint string
if hint = r.FormValue("hint"); hint == "" {
hint = r.PostFormValue("hint")
}
if ar := server.HandleAuthorizeRequest(resp, r); ar != nil {
ar.Authorized = true
ar.UserData = hint
server.FinishAuthorizeRequest(resp, r, ar)
}
if resp.IsError && resp.InternalError != nil {
log.Printf("ERROR: %s\n", resp.InternalError)
}
osin.OutputJSON(resp, w, r)
})
// Access token endpoint
http.HandleFunc("/oauth2/token", func(w http.ResponseWriter, r *http.Request) {
resp := server.NewResponse()
// defer resp.Close()
var hint string
if hint = r.FormValue("hint"); hint == "" {
hint = r.PostFormValue("hint")
}
ar := server.HandleAccessRequest(resp, r)
if ar != nil {
ar.Authorized = true
ar.UserData = hint
server.FinishAccessRequest(resp, r, ar)
}
if resp.IsError && resp.InternalError != nil {
log.Printf("ERROR: %s\n", resp.InternalError)
}
osin.OutputJSON(resp, w, r)
})
http.HandleFunc("/oauth2/passport", func(w http.ResponseWriter, r *http.Request) {
resp := server.NewResponse()
var token string
if token = r.FormValue("access_token"); token == "" {
token = r.PostFormValue("access_token")
}
if token != "" {
access, err := storage.LoadAccess(token)
if err != nil {
resp.SetError("invalid_request", "Token is not valid.")
} else {
if access.IsExpired() {
resp.SetError("invalid_request", "Token has expired.")
} else {
resp.Output["is_valid"] = true
resp.Output["token"] = access
}
}
} else {
resp.SetError("invalid_request", "Required token is missing from the request.")
}
osin.OutputJSON(resp, w, r)
})
http.ListenAndServe(":8080", nil)
}