-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
236 lines (200 loc) · 6.43 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package main
import (
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"strconv"
"text/template"
"time"
"go.hacdias.com/indielib/indieauth"
)
const (
oauthCookieName string = "indieauth-cookie"
)
var (
indexTemplate = `<!DOCTYPE html>
<html>
<head>
<title>IndieAuth Client Demo</title>
</head>
<body>
<h1>IndieAuth Client Demo</h1>
<p>Sign in with your domain:</p>
<form action="/login" method="post">
<input type="text" name="profile" placeholder="yourdomain.com" required />
<button/>Sign In</button>
</form>
</body>
</html>`
loggedInTemplate = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<html>
<head>
<title>You are logged in!</title>
</head>
<body>
<h1>Welcome {{ .Me }}!</h1>
<p>You are now successfully logged in. This is what we gathered about you:</p>
<ul>
<li>Name: {{ or .Profile.Name "unknown" }}</li>
<li>URL: {{ or .Profile.URL "unknown" }}</li>
<li>Photo: {{ or .Profile.Photo "unknown" }}</li>
<li>E-mail: {{ or .Profile.Email "unknown" }}</li>
</ul>
</body>
</html>
`))
)
func main() {
// Setup flags.
portPtr := flag.Int("port", 3535, "port to listen on")
addressPtr := flag.String("client", "http://localhost:3535/", "client ID, front facing address to listen on")
flag.Parse()
clientID := *addressPtr
callbackURI := clientID + "callback"
// Validate the given Client ID before starting the HTTP server.
err := indieauth.IsValidClientIdentifier(clientID)
if err != nil {
log.Fatal(err)
}
// Create a new client.
client := &client{
iac: indieauth.NewClient(clientID, callbackURI, nil),
}
http.HandleFunc("/", client.indexHandler)
http.HandleFunc("/login", client.loginHandler)
http.HandleFunc("/callback", client.callbackHandler)
log.Printf("Listening on http://localhost:%d", *portPtr)
log.Printf("Listening on %s", clientID)
if err := http.ListenAndServe(":"+strconv.Itoa(*portPtr), nil); err != nil {
log.Fatal(err)
}
}
type client struct {
iac *indieauth.Client
}
// indexHandler serves a simple index page with a login form.
func (c *client) indexHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(indexTemplate))
}
// loginHandler handles the login process after submitting the domain via the
// index page.
func (c *client) loginHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
profileURL := r.FormValue("profile")
if profileURL == "" {
http.Error(w, "empty profile", http.StatusBadRequest)
return
}
// After retrieving the profile URL from the login form, canonicalize it,
// and check if it is valid.
profileURL = indieauth.CanonicalizeURL(profileURL)
if err := indieauth.IsValidProfileURL(profileURL); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Generates the redirect request to the target profile so that the user can
// authorize the request. We also ask for the "profile" and "email" scope so
// that we can get more information about the user.
authInfo, redirect, err := c.iac.Authenticate(r.Context(), profileURL, "profile email")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// We store the authInfo in a cookie. This information will be later needed
// to validate the callback request from the authentication server.
err = c.storeAuthInfo(w, r, authInfo)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Redirect to the authentication server so that the user can authorize it.
http.Redirect(w, r, redirect, http.StatusSeeOther)
}
// callbackHandler handles the callback from the authentication server.
func (c *client) callbackHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve the authentication info from the cookie.
authInfo, err := c.getAuthInfo(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Validate the callback using authInfo and the current request.
code, err := c.iac.ValidateCallback(authInfo, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// We now fetch the profile of the user so we know more about the user.
// Depending on the authentication server, this information might be more
// or less complete. However, ".Me" must always be present.
profile, err := c.iac.FetchProfile(r.Context(), authInfo, code)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Validate the ".Me" - please note that loopback (localhost) is invalid.
if err := indieauth.IsValidProfileURL(profile.Me); err != nil {
http.Error(w, fmt.Sprintf("invalid 'me': %s", err), http.StatusBadRequest)
return
}
// The user is now logged in to your application. We simply display a simple
// page with the profile information. However, in your application, you likely
// want to create a session cookie (or something similar) to know that the user
// is logged in.
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = loggedInTemplate.Execute(w, profile)
}
// storeAuthInfo stores [indieauth.AuthInfo] into a cookie. This information is
// required to then validate the request once the callback is received. Note that
// this is just an example. You could use other methods, such as encoding with JWT
// tokens, a database, you name it.
func (c *client) storeAuthInfo(w http.ResponseWriter, r *http.Request, i *indieauth.AuthInfo) error {
data, err := json.Marshal(i)
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: oauthCookieName,
Value: base64.StdEncoding.EncodeToString(data),
Expires: time.Now().Add(time.Minute * 10),
Secure: r.URL.Scheme == "https",
HttpOnly: true,
Path: "/",
SameSite: http.SameSiteLaxMode,
})
return nil
}
// getAuthInfo gets the [indieauth.AuthInfo] stored into a cookie.
func (c *client) getAuthInfo(w http.ResponseWriter, r *http.Request) (*indieauth.AuthInfo, error) {
cookie, err := r.Cookie(oauthCookieName)
if err != nil {
return nil, err
}
value, err := base64.StdEncoding.DecodeString(cookie.Value)
if err != nil {
return nil, err
}
var i *indieauth.AuthInfo
err = json.Unmarshal([]byte(value), &i)
if err != nil {
return nil, err
}
// Delete cookie.
http.SetCookie(w, &http.Cookie{
Name: oauthCookieName,
MaxAge: -1,
Secure: r.URL.Scheme == "https",
Path: "/",
HttpOnly: true,
})
return i, nil
}