-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
85 lines (74 loc) · 2.05 KB
/
main.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
// Copyright (C) 2016 JT Olds
// See LICENSE for copying information
// This example shows how to set up a web service that allows users to log in
// via one single OAuth2 Provider
package main
import (
"encoding/hex"
"flag"
"fmt"
"net/http"
"gopkg.in/go-webhelp/whoauth2.v1"
"gopkg.in/webhelp.v1/whcompat"
"gopkg.in/webhelp.v1/wherr"
"gopkg.in/webhelp.v1/whlog"
"gopkg.in/webhelp.v1/whmux"
"gopkg.in/webhelp.v1/whsess"
)
var (
listenAddr = flag.String("addr", ":8080", "address to listen on")
cookieSecret = flag.String("cookie_secret", "abcdef0123456789",
"the secret for securing cookie information")
githubClientId = flag.String("github_client_id", "", "")
githubClientSecret = flag.String("github_client_secret", "", "")
)
type SampleHandler struct {
Prov *whoauth2.ProviderHandler
Restricted bool
}
func (s *SampleHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t, err := s.Prov.Token(whcompat.Context(r))
if err != nil {
wherr.Handle(w, r, err)
return
}
w.Header().Set("Content-Type", "text/html")
if s.Restricted {
fmt.Fprintf(w, `<h3>Restricted</h3>`)
}
if t != nil {
fmt.Fprintf(w, `
<p>Logged in | <a href="%s">Log out</a></p>
`, s.Prov.LogoutURL("/"))
} else {
fmt.Fprintf(w, `
<p><a href="%s">Log in</a> | Logged out</p>
`, s.Prov.LoginURL(r.RequestURI, false))
}
if !s.Restricted {
fmt.Fprintf(w, `
<p><a href="/restricted">Restricted</a></p>
`)
}
}
func main() {
flag.Parse()
secret, err := hex.DecodeString(*cookieSecret)
if err != nil {
panic(err)
}
store := whsess.NewCookieStore(secret)
oauth := whoauth2.NewProviderHandler(
whoauth2.Github(whoauth2.Config{
ClientID: *githubClientId,
ClientSecret: *githubClientSecret}),
"oauth-github", "/auth",
whoauth2.RedirectURLs{})
whlog.ListenAndServe(*listenAddr, whlog.LogRequests(whlog.Default,
whsess.HandlerWithStore(store,
whmux.Dir{
"": &SampleHandler{Prov: oauth, Restricted: false},
"restricted": oauth.LoginRequired(
&SampleHandler{Prov: oauth, Restricted: true}),
"auth": oauth})))
}