This repository has been archived by the owner on Mar 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
app.go
193 lines (154 loc) · 5.86 KB
/
app.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
package photoshare
import (
"database/sql"
"github.com/gorilla/mux"
"net/http"
)
// authentication behaviours
type authLevel int
const (
authLevelIgnore authLevel = iota // we don't need the user in this handler
authLevelCheck // prefetch user, doesn't matter if not logged in
authLevelLogin // user required, 401 if not available
authLevelAdmin // admin required, 401 if no user, 403 if not admin
)
// contains all the objects needed to run the application
type app struct {
cfg *config
db *sql.DB
mailer *mailer
router *mux.Router
datamapper dataMapper
filestore fileStorage
session sessionManager
auth authenticator
cache cache
}
// our custom handler
type handlerFunc func(c *context, w http.ResponseWriter, r *http.Request) error
func newApp() (*app, error) {
var err error
app := &app{}
app.cfg, err = newConfig()
if err != nil {
return app, err
}
if err := app.initDB(); err != nil {
return app, err
}
app.datamapper, err = newDataMapper(app.db, app.cfg.LogSql)
if err != nil {
return app, err
}
app.filestore = newFileStorage(app.cfg)
app.mailer = newMailer(app.cfg)
app.cache = newCache(app.cfg)
app.auth = newAuthenticator(app.cfg)
app.session, err = newSessionManager(app.cfg)
if err != nil {
return app, err
}
app.initRouter()
return app, nil
}
func (app *app) close() {
app.db.Close()
}
func (app *app) initDB() error {
db, err := dbConnect(app.cfg.DBUser,
app.cfg.DBPassword,
app.cfg.DBName,
app.cfg.DBHost)
if err != nil {
return err
}
app.db = db
return nil
}
// the handler should create a new context on each request, and handle any returned
// errors appropriately.
func (app *app) handler(h handlerFunc, level authLevel) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
handleError(w, r, func() error {
user, err := app.authenticate(r, level)
if err != nil {
return err
}
return h(newContext(app, r, user), w, r)
}())
}
}
// lazily fetches the current session user
func (app *app) authenticate(r *http.Request, level authLevel) (*user, error) {
if level == authLevelIgnore {
return &user{}, nil
}
var errLoginRequired = httpError{http.StatusUnauthorized, "You must be logged in"}
var checkAuthLevel = func(user *user) error {
switch level {
case authLevelLogin:
if !user.IsAuthenticated {
return errLoginRequired
}
break
case authLevelAdmin:
if !user.IsAuthenticated {
return errLoginRequired
}
if !user.IsAdmin {
return httpError{http.StatusForbidden, "You must be an admin"}
}
}
return nil
}
user := &user{}
userID, err := app.session.readToken(r)
if err != nil {
return user, err
}
if userID == 0 {
return user, checkAuthLevel(user)
}
user, err = app.datamapper.getActiveUser(userID)
if err != nil {
if isErrSqlNoRows(err) {
return user, checkAuthLevel(user)
}
return nil, err
}
user.IsAuthenticated = true
return user, checkAuthLevel(user)
}
// generates the routes for the API
func (app *app) initRouter() {
app.router = mux.NewRouter()
api := app.router.PathPrefix("/api/").Subrouter()
photos := api.PathPrefix("/photos/").Subrouter()
photos.HandleFunc("/", app.handler(getPhotos, authLevelIgnore)).Methods("GET").Name("photos")
photos.HandleFunc("/", app.handler(upload, authLevelLogin)).Methods("POST").Name("photos")
photos.HandleFunc("/search", app.handler(searchPhotos, authLevelIgnore)).Methods("GET").Name("search")
photos.HandleFunc("/owner/{ownerID:[0-9]+}", app.handler(photosByOwnerID, authLevelIgnore)).Methods("GET").Name("owner")
photos.HandleFunc("/{id:[0-9]+}", app.handler(getPhotoDetail, authLevelCheck)).Methods("GET").Name("photoDetail")
photos.HandleFunc("/{id:[0-9]+}", app.handler(deletePhoto, authLevelLogin)).Methods("DELETE").Name("deletePhoto")
photos.HandleFunc("/{id:[0-9]+}/title", app.handler(editPhotoTitle, authLevelLogin)).Methods("PATCH").Name("editPhotoTitle")
photos.HandleFunc("/{id:[0-9]+}/tags", app.handler(editPhotoTags, authLevelLogin)).Methods("PATCH").Name("editPhotoTags")
photos.HandleFunc("/{id:[0-9]+}/upvote", app.handler(voteUp, authLevelLogin)).Methods("PATCH").Name("upvote")
photos.HandleFunc("/{id:[0-9]+}/downvote", app.handler(voteDown, authLevelLogin)).Methods("PATCH").Name("downvote")
auth := api.PathPrefix("/auth/").Subrouter()
auth.HandleFunc("/", app.handler(getSessionInfo, authLevelCheck)).Methods("GET").Name("sessionInfo")
auth.HandleFunc("/", app.handler(login, authLevelIgnore)).Methods("POST").Name("login")
auth.HandleFunc("/", app.handler(logout, authLevelLogin)).Methods("DELETE").Name("logout")
auth.HandleFunc("/emailExists", app.handler(emailExists, authLevelIgnore)).Methods("GET").Name("emailExists")
auth.HandleFunc("/signup", app.handler(signup, authLevelIgnore)).Methods("POST").Name("signup")
auth.HandleFunc("/recoverpass", app.handler(recoverPassword, authLevelIgnore)).Methods("PUT").Name("recoverPassword")
auth.HandleFunc("/changepass", app.handler(changePassword, authLevelIgnore)).Methods("PUT").Name("changePassword")
auth.HandleFunc("/oauth2/{provider}/url", app.handler(getAuthRedirectURL, authLevelIgnore)).Methods("GET")
auth.HandleFunc("/oauth2/{provider}/callback/", app.handler(authCallback, authLevelIgnore)).Methods("GET")
api.HandleFunc("/tags/", app.handler(getTags, authLevelIgnore)).Methods("GET").Name("tags")
api.Handle("/messages/{path:.*}", messageHandler).Name("messages")
feeds := app.router.PathPrefix("/feeds/").Subrouter()
feeds.HandleFunc("", app.handler(latestFeed, authLevelIgnore)).Methods("GET").Name("latestFeed")
feeds.HandleFunc("popular/", app.handler(popularFeed, authLevelIgnore)).Methods("GET").Name("popularFeed")
feeds.HandleFunc("owner/{ownerID:[0-9]+}", app.handler(ownerFeed, authLevelIgnore)).Methods("GET").Name("ownerFeed")
app.router.PathPrefix("/").Handler(http.FileServer(http.Dir(app.cfg.PublicDir)))
}