/
oauth.go
331 lines (274 loc) · 9.59 KB
/
oauth.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package handler
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
"github.com/bnema/gordon/internal/db"
"github.com/bnema/gordon/internal/db/queries"
"github.com/bnema/gordon/internal/server"
"github.com/bnema/gordon/internal/templating/render"
"github.com/gorilla/sessions"
_ "github.com/joho/godotenv/autoload"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
)
var urlToken string
// compareGordonToken compares the token from the URL query parameter with the one from the config.yml
func CompareGordonToken(c echo.Context, a *server.App) error {
configToken, err := a.Config.GetToken()
if err != nil {
return err
}
if urlToken != configToken {
return fmt.Errorf("token is empty or not valid")
}
return nil
}
// RenderLoginPage renders the login.html template
func RenderLoginPage(c echo.Context, a *server.App) error {
urlToken = c.QueryParam("token")
data := map[string]interface{}{
"Title": "Login",
}
// Navigate inside the fs.FS to get the template
path := "html/login"
rendererData, err := render.GetHTMLRenderer(path, "index.gohtml", a.TemplateFS, a)
if err != nil {
return err
}
renderedHTML, err := rendererData.Render(data, a)
if err != nil {
return err
}
return c.HTML(200, renderedHTML)
}
// StartOAuthGithub starts the Github OAuth flow.
func StartOAuthGithub(c echo.Context, a *server.App) error {
fmt.Println("Attempting to get an existing session.")
sess, err := getSession(c)
if err != nil || sess == nil || sess.Values == nil {
fmt.Println("Session retrieval failed, initiating new GitHub OAuth flow.")
return initiateGithubOAuthFlow(c, a)
}
fmt.Println("Attempting to assert session values.")
sessionID, ok1 := sess.Values["sessionID"].(string)
accountID, ok2 := sess.Values["accountID"].(string)
authenticated, ok3 := sess.Values["authenticated"].(bool)
if !ok1 || !ok2 || !ok3 || !authenticated {
fmt.Println("Session assertion failed, or user not authenticated. Initiating new OAuth flow.")
return initiateGithubOAuthFlow(c, a)
}
fmt.Println("Checking if session exists in DB.")
sessionExists, err := queries.CheckDBSessionExists(a, sessionID)
if err != nil {
fmt.Printf("Error checking if session exists: %v\n", err)
return fmt.Errorf("could not check if session exists: %w", err)
}
if !sessionExists {
fmt.Println("Session does not exist in DB, initiating new OAuth flow.")
return initiateGithubOAuthFlow(c, a)
}
fmt.Println("Getting the expiration time of the session.")
currentTime := time.Now()
sessionExpiration, err := queries.GetSessionExpiration(a, accountID, sessionID, currentTime)
if err != nil {
fmt.Printf("Error getting session expiration: %v\n", err)
return fmt.Errorf("could not get session expiration: %w", err)
}
if currentTime.After(sessionExpiration) {
fmt.Println("Current time is after session expiration, initiating new OAuth flow.")
return initiateGithubOAuthFlow(c, a)
}
fmt.Println("Extending session expiration time by 30 minutes.")
newExpirationTime := currentTime.Add(30 * time.Minute)
err = queries.ExtendSessionExpiration(a, accountID, sessionID, newExpirationTime)
if err != nil {
fmt.Printf("Error extending session expiration: %v\n", err)
return fmt.Errorf("could not extend session expiration: %w", err)
}
fmt.Println("Session is valid and extended. Redirecting to admin panel.")
return c.Redirect(http.StatusFound, a.Config.Admin.Path)
}
// initiateGithubOAuthFlow starts a new GitHub OAuth flow
func initiateGithubOAuthFlow(c echo.Context, a *server.App) error {
clientID := os.Getenv("GITHUB_APP_ID")
redirectDomain := a.GenerateOauthCallbackURL()
encodedState := base64.StdEncoding.EncodeToString([]byte("redirectDomain:" + redirectDomain))
// Redirect to GitHub's OAuth endpoint to grab the OAuth access
proxyURL := a.Config.Build.ProxyURL
oauthURL := fmt.Sprintf(
"%s/github/authorize?client_id=%s&redirect_uri=%s&state=%s",
proxyURL,
clientID,
redirectDomain,
encodedState,
)
return c.Redirect(http.StatusFound, oauthURL)
}
type Sessions struct {
*db.Sessions
}
// OAuthCallback handles the callback response from Github OAuth
func OAuthCallback(c echo.Context, a *server.App) error {
redirectPath := a.Config.Admin.Path
accessToken, encodedState, err := parseQueryParams(c)
if err != nil {
return c.String(http.StatusBadRequest, err.Error())
}
// update the struct with the new access token
a.DBTables.Sessions.AccessToken = accessToken
// Compare the state parameter with the redirect domain
redirectDomain := a.GenerateOauthCallbackURL()
encodedRedirectDomain := base64.StdEncoding.EncodeToString([]byte("redirectDomain:" + redirectDomain))
if encodedState != encodedRedirectDomain {
return c.String(http.StatusBadRequest, "invalid state parameter")
}
sess, err := getSession(c)
if err != nil {
return err
}
browserInfo := c.Request().UserAgent()
userInfo, err := githubGetUserDetails(c, a)
if err != nil {
return err
}
user, err := handleUser(c, a, accessToken, browserInfo, userInfo)
if err != nil {
return err
}
err = setSessionValues(c, sess, user, a.DBTables.Account.ID, a.DBTables.Sessions.Expires, a.DBTables.Sessions.ID)
if err != nil {
return err
}
return c.Redirect(http.StatusFound, redirectPath)
}
// parseQueryParams parses the query parameters from the callback URL
func parseQueryParams(c echo.Context) (string, string, error) {
accessToken := c.QueryParam("access_token")
encodedState := c.QueryParam("state")
_, err := base64.StdEncoding.DecodeString(encodedState)
if err != nil {
return "", "", fmt.Errorf("invalid state parameter")
}
return accessToken, encodedState, nil
}
// getSession gets the session from the context
func getSession(c echo.Context) (*sessions.Session, error) {
sess, err := session.Get("session", c)
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, "Could not get session")
}
return sess, nil
}
// handleUser handles the user creation or update
func handleUser(c echo.Context, a *server.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
userExists, err := queries.CheckDBUserExists(a)
if err != nil {
return nil, fmt.Errorf("could not check if user exists: %w", err)
}
if !userExists {
// if it is a new user creation we compare the gordon token
err := CompareGordonToken(c, a)
if err != nil {
return nil, echo.NewHTTPError(http.StatusUnauthorized, "Token is empty or not valid")
}
return createUser(a, accessToken, browserInfo, userInfo)
}
if userExists {
// if it is an existing user we compare the login and email to see if it is the same user
isGoodUser, err := queries.CheckDBUserIsGood(a, userInfo)
if err != nil {
return nil, fmt.Errorf("could not check if user is good: %w", err)
}
if !isGoodUser {
return nil, echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
}
if isGoodUser {
// Update the user
updatedUser, err := updateUser(a, accessToken, browserInfo, userInfo)
if err != nil {
return nil, fmt.Errorf("could not update user: %w", err)
}
return updatedUser, nil
}
}
return nil, fmt.Errorf("could not handle user")
}
// createUser creates a new user in the database
func createUser(a *server.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
err := queries.CreateUser(a, accessToken, browserInfo, userInfo)
if err != nil {
return nil, fmt.Errorf("could not create user: %w", err)
}
return &a.DBTables.User, nil
}
// updateUser updates an existing user in the database
func updateUser(a *server.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
user, err := queries.UpdateUser(a, accessToken, browserInfo, userInfo)
if err != nil {
return nil, fmt.Errorf("could not update user: %w", err)
}
return user, nil
}
// setSessionValues sets the session values for the user
func setSessionValues(c echo.Context, sess *sessions.Session, user *db.User, accountID string, expires string, sessionID string) error {
sess.Values["authenticated"] = true
sess.Values["accountID"] = accountID
sess.Values["expires"] = expires
sess.Values["sessionID"] = sessionID
if err := sess.Save(c.Request(), c.Response()); err != nil {
return fmt.Errorf("could not save session: %w", err)
}
return nil
}
// fetchGithubAPI fetches the Github API
func fetchGithubAPI(url string, authHeader string, result interface{}) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", authHeader)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("got status code %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, &result)
if err != nil {
return err
}
return nil
}
// githubGetUserDetails gets the user details from the Github API using the access token
func githubGetUserDetails(c echo.Context, a *server.App) (userInfo *queries.GithubUserInfo, err error) {
accessToken := c.QueryParam("access_token")
// Fetch user info
err = fetchGithubAPI("https://api.github.com/user", "Bearer "+accessToken, &userInfo)
if err != nil {
return nil, err
}
// Fetch user emails
var emailObjects []struct {
Email string `json:"email"`
}
err = fetchGithubAPI("https://api.github.com/user/emails", "Bearer "+accessToken, &emailObjects)
if err != nil {
return nil, err
}
// Extract emails and populate the Emails field in userInfo
for _, emailObj := range emailObjects {
userInfo.Emails = append(userInfo.Emails, emailObj.Email)
}
return userInfo, nil
}