-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
177 lines (130 loc) · 4.38 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
package main
import (
"context"
"fmt"
"net/http"
"os"
"todo-app/data"
"github.com/gomodule/redigo/redis"
_ "github.com/joho/godotenv/autoload"
"github.com/julienschmidt/httprouter"
"github.com/rs/cors"
)
var cache redis.Conn
type key int
const (
sessionTokenKey key = iota
userIdKey key = iota
userEmailKey key = iota
)
func pagesAuthMiddleware(n httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
cookie, err := r.Cookie("session_token")
if err != nil {
http.Redirect(w, r, "/", http.StatusPermanentRedirect)
return
}
sessionToken := cookie.Value
response, _ := cache.Do("GET", sessionToken)
if response == nil {
http.Redirect(w, r, "/", http.StatusPermanentRedirect)
return
}
userEmail := fmt.Sprintf("%s", response)
user, err := data.UserByEmail(userEmail)
if err != nil {
http.Redirect(w, r, "/", http.StatusPermanentRedirect)
return
}
ctx := r.Context()
// Get new context with key-value "settings"
ctx = context.WithValue(ctx, sessionTokenKey, sessionToken)
ctx = context.WithValue(ctx, userIdKey, user.Id)
ctx = context.WithValue(ctx, userEmailKey, user.Email)
r = r.WithContext(ctx)
n(w, r, ps)
}
}
// middleware is used to intercept incoming HTTP calls and apply general functions upon them.
func apiAuthMiddleware(n httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// do some authentication
cookie, err := r.Cookie("session_token")
if err != nil {
if err == http.ErrNoCookie {
// If the cookie is not set, return an unauthorized status
respond(w, message(false, err.Error()), http.StatusUnauthorized)
return
}
// For any other type of error, return a bad request status
respond(w, message(false, err.Error()), http.StatusBadRequest)
return
}
sessionToken := cookie.Value
response, err := cache.Do("GET", sessionToken)
if err != nil {
// If there is an error fetching from cache, return an internal server error status
respond(w, message(false, err.Error()), http.StatusInternalServerError)
return
}
if response == nil {
respond(w, message(false, "Unauthenticated"), http.StatusUnauthorized)
return
}
userEmail := fmt.Sprintf("%s", response)
user, err := data.UserByEmail(userEmail)
if err != nil {
respond(w, message(false, err.Error()), http.StatusInternalServerError)
return
}
ctx := r.Context()
// Get new context with key-value "settings"
ctx = context.WithValue(ctx, sessionTokenKey, sessionToken)
ctx = context.WithValue(ctx, userIdKey, user.Id)
ctx = context.WithValue(ctx, userEmailKey, user.Email)
r = r.WithContext(ctx)
n(w, r, ps)
}
}
func main() {
router := httprouter.New()
// init cache
initCache()
// Handles static files
router.ServeFiles("/static/*filepath", http.Dir("public"))
// all routes patterns matched here
// PAGES
router.GET("/", index)
router.GET("/planner", pagesAuthMiddleware(planner))
// APIS
// AUTH
router.POST("/api/signup", signup)
router.POST("/api/login", login)
router.POST("/api/logout", apiAuthMiddleware(logout))
router.POST("/api/refresh-token", apiAuthMiddleware(refreshToken))
// TASKS
router.POST("/api/tasks", apiAuthMiddleware(createTask))
router.GET("/api/tasks", apiAuthMiddleware(userTasks))
router.DELETE("/api/tasks/:id", apiAuthMiddleware(deleteTask))
router.PATCH("/api/tasks/:id/edits", apiAuthMiddleware(updateTask))
router.PATCH("/api/tasks/:id/completed", apiAuthMiddleware(updateCompleteTask))
router.POST("/api/subtask/:taskId", apiAuthMiddleware(createSubTask))
router.PATCH("/api/subtask/:id/:taskId", apiAuthMiddleware(updateCompleteSubTask))
router.DELETE("/api/subtask/:id/:taskId", apiAuthMiddleware(deleteSubTask))
// GOALS
router.POST("/api/goals", apiAuthMiddleware(createGoal))
router.GET("/api/goals", apiAuthMiddleware(userGoals))
router.DELETE("/api/goals/:id", apiAuthMiddleware(deleteGoal))
router.PATCH("/api/goals/:id/edits", apiAuthMiddleware(updateGoal))
router.PATCH("/api/goals/:id/progress", apiAuthMiddleware(updateGoalProgress))
port := os.Getenv("PORT")
http.ListenAndServe(":"+port, cors.Default().Handler(router))
}
func initCache() {
conn, err := redis.DialURL(os.Getenv("REDISCLOUD_URL"))
if err != nil {
panic(err)
}
// Assign the connection to the package level `cache` variable
cache = conn
}