Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
148 lines (133 loc) · 4.65 KB
/
Copy pathmain.go
File metadata and controls
148 lines (133 loc) · 4.65 KB
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
// Command quickstart is the README's quick start as a program you can run:
// email and password sign-in on net/http, stored in a SQLite file.
//
// go run ./quickstart
//
// Mail is printed to the log instead of sent; plug an SMTP or API client
// into logMailer's place.
package main
import (
"cmp"
"context"
"database/sql"
"encoding/json"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/ubgo/auth"
"github.com/ubgo/auth/authhttp"
"github.com/ubgo/auth/plugin/email"
"github.com/ubgo/auth/plugin/password"
"github.com/ubgo/sqlb"
_ "modernc.org/sqlite" // registers the "sqlite" database/sql driver
)
const (
// dbFile is the SQLite database, created next to where you run the program.
dbFile = "quickstart.db"
// authPrefix is where the library's routes are mounted.
authPrefix = "/auth"
// readHeaderTimeout bounds how long a client may take to send headers, so
// a slow client cannot hold a connection open forever.
readHeaderTimeout = 5 * time.Second
)
//ds:def id=addr-gefhyvsy
var (
// port is the port the app listens on: 8081, or $PORT when it is set, so
// two examples can run side by side.
port = cmp.Or(os.Getenv("PORT"), "8081")
// addr is where the server listens: this machine only, for development.
// Use ":" + port to accept connections from the network.
addr = "localhost:" + port
// baseURL is the app's public URL. Its origin is the only one allowed to
// send cookie-authenticated POSTs, and links in mail point at it.
baseURL = "http://localhost:" + port
)
// sqlitePragmas are the settings every SQLite connection needs: WAL so readers
// do not block the writer, a busy timeout instead of an immediate "database is
// locked", and foreign keys, which SQLite leaves off and the library's cascades
// depend on.
//
//ds:def id=sqlitepragmas-t73gzsxj
const sqlitePragmas = "_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)"
// sqliteDSN builds the SQLite URI for a database file. It escapes the path
// instead of concatenating "file:"+path, because a "#" or "?" in a path would
// otherwise start the URI's fragment or query and open a different file. It
// escapes only the path, never building a url.URL with a scheme, because Go
// writes a relative path such as "auth.db" as "file://auth.db", which SQLite
// reads as a host.
//
//ds:def id=sqlitedsn-6k7zzy93
func sqliteDSN(path string) string {
return "file:" + (&url.URL{Path: path}).EscapedPath() + "?" + sqlitePragmas
}
//ds:def id=main-7mrnbhrx
func main() {
db, err := sql.Open("sqlite", sqliteDSN(dbFile))
if err != nil {
log.Fatal(err)
}
defer db.Close()
a, err := newAuth(db, logMailer{})
if err != nil {
log.Fatal(err) // a broken plugin combination fails here, not in production
}
defer a.Close()
if _, err := a.Migrate(context.Background()); err != nil {
log.Fatal(err)
}
log.Printf("listening on %s", baseURL)
srv := &http.Server{Addr: addr, Handler: newHandler(a), ReadHeaderTimeout: readHeaderTimeout}
log.Fatal(srv.ListenAndServe())
}
// newAuth wires the library: email addresses to sign in with and recover
// through, and passwords. The test builds the app with the same function, so
// what it proves is what main serves.
//
//ds:def id=newauth-smwje7vu
func newAuth(db *sql.DB, m email.Mailer) (*auth.Auth, error) {
return auth.New(
auth.WithDB(db, sqlb.SQLiteDialect{}),
auth.WithBaseURL(baseURL),
auth.WithPlugins(
email.New(email.Login(), email.Recover(), email.WithMailer(m)),
password.New(),
),
)
}
// newHandler mounts the library's routes and one page of the app's own that
// only a signed-in user may see.
//
//ds:def id=newhandler-zmz4j9w2
func newHandler(a *auth.Auth) http.Handler {
mux := http.NewServeMux()
mux.Handle(authPrefix+"/", authhttp.Handler(a, authhttp.Prefix(authPrefix)))
mux.Handle("/me", authhttp.Middleware(a)(authhttp.RequireUser(http.HandlerFunc(me))))
return mux
}
// meResponse is what /me answers.
//
//ds:def id=meresponse-zccxxpf9
type meResponse struct {
ID string `json:"id"`
Hello string `json:"hello"`
}
// me is an app handler: RequireUser has already refused anyone signed out.
//
//ds:def id=me-6d2msbjr
func me(w http.ResponseWriter, r *http.Request) {
u := authhttp.MustUser(r)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(meResponse{ID: u.ID, Hello: u.Name}) // a client that hung up cannot be told
}
// logMailer prints mail instead of sending it. Replace it with SMTP, an email
// API or a queue.
type logMailer struct{}
// Send logs the message, including the link, so you can open it by hand.
//
//ds:def id=logmailer-send-457tbsyq
func (logMailer) Send(_ context.Context, m email.Mail) error {
log.Printf("mail to=%s subject=%q\n%s", m.To, m.Subject, m.Text)
return nil
}