| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "net/http" |
| 6 | "strconv" |
| 7 | "strings" |
| 8 | "time" |
| 9 | |
| 10 | "gitlab.com/Timfa/bluegit/internal/auth" |
| 11 | "gitlab.com/Timfa/bluegit/internal/store" |
| 12 | ) |
| 13 | |
| 14 | func (s *Server) login(w http.ResponseWriter, r *http.Request) { |
| 15 | if s.who(r).OK { |
| 16 | http.Redirect(w, r, "/", http.StatusFound) |
| 17 | return |
| 18 | } |
| 19 | if s.Dev { |
| 20 | id, err := s.Auth.Exchange(r.Context(), "dev", s.Cfg.RedirectURI(), "", "") |
| 21 | if err != nil { |
| 22 | http.Error(w, err.Error(), http.StatusBadGateway) |
| 23 | return |
| 24 | } |
| 25 | s.finishLogin(w, r, id.AuthID, id.Username, id.AvatarURL, id.IsAdmin, id.AccessToken, id.ExpiresIn) |
| 26 | return |
| 27 | } |
| 28 | state, err := randomState() |
| 29 | if err != nil { |
| 30 | http.Error(w, s.tr(r, "err.session"), http.StatusInternalServerError) |
| 31 | return |
| 32 | } |
| 33 | nonce, err := randomState() |
| 34 | if err != nil { |
| 35 | http.Error(w, s.tr(r, "err.session"), http.StatusInternalServerError) |
| 36 | return |
| 37 | } |
| 38 | verifier, err := auth.NewPKCEVerifier() |
| 39 | if err != nil { |
| 40 | http.Error(w, s.tr(r, "err.session"), http.StatusInternalServerError) |
| 41 | return |
| 42 | } |
| 43 | secure := strings.HasPrefix(s.Cfg.BaseURL, "https://") |
| 44 | http.SetCookie(w, &http.Cookie{ |
| 45 | Name: "bluegit_oauth_state", Value: state, Path: "/", MaxAge: 600, |
| 46 | HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode, |
| 47 | }) |
| 48 | http.SetCookie(w, &http.Cookie{ |
| 49 | Name: "bluegit_oauth_nonce", Value: nonce, Path: "/", MaxAge: 600, |
| 50 | HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode, |
| 51 | }) |
| 52 | http.SetCookie(w, &http.Cookie{ |
| 53 | Name: "bluegit_oauth_pkce", Value: verifier, Path: "/", MaxAge: 600, |
| 54 | HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode, |
| 55 | }) |
| 56 | http.Redirect(w, r, s.Auth.AuthorizeURL(state, nonce, s.Cfg.RedirectURI(), auth.PKCEChallenge(verifier)), http.StatusFound) |
| 57 | } |
| 58 | |
| 59 | func (s *Server) callback(w http.ResponseWriter, r *http.Request) { |
| 60 | if s.Dev { |
| 61 | http.NotFound(w, r) |
| 62 | return |
| 63 | } |
| 64 | if msg := r.URL.Query().Get("error"); msg != "" { |
| 65 | s.redirect(w, r, "/login", "", s.tr(r, "err.oauth", msg)) |
| 66 | return |
| 67 | } |
| 68 | stateCookie, err := r.Cookie("bluegit_oauth_state") |
| 69 | if err != nil || stateCookie.Value == "" || stateCookie.Value != r.URL.Query().Get("state") { |
| 70 | http.Error(w, s.tr(r, "err.oauthState"), http.StatusBadRequest) |
| 71 | return |
| 72 | } |
| 73 | nonceCookie, err := r.Cookie("bluegit_oauth_nonce") |
| 74 | nonce := "" |
| 75 | if err == nil { |
| 76 | nonce = nonceCookie.Value |
| 77 | } |
| 78 | pkceCookie, err := r.Cookie("bluegit_oauth_pkce") |
| 79 | verifier := "" |
| 80 | if err == nil { |
| 81 | verifier = pkceCookie.Value |
| 82 | } |
| 83 | http.SetCookie(w, &http.Cookie{Name: "bluegit_oauth_state", Value: "", Path: "/", MaxAge: -1}) |
| 84 | http.SetCookie(w, &http.Cookie{Name: "bluegit_oauth_nonce", Value: "", Path: "/", MaxAge: -1}) |
| 85 | http.SetCookie(w, &http.Cookie{Name: "bluegit_oauth_pkce", Value: "", Path: "/", MaxAge: -1}) |
| 86 | id, err := s.Auth.Exchange(r.Context(), r.URL.Query().Get("code"), s.Cfg.RedirectURI(), nonce, verifier) |
| 87 | if err != nil { |
| 88 | s.Log.Error("oauth", "err", err) |
| 89 | s.redirect(w, r, "/", "", s.tr(r, "err.oauthFail")) |
| 90 | return |
| 91 | } |
| 92 | s.finishLogin(w, r, id.AuthID, id.Username, id.AvatarURL, id.IsAdmin, id.AccessToken, id.ExpiresIn) |
| 93 | } |
| 94 | |
| 95 | func (s *Server) finishLogin(w http.ResponseWriter, r *http.Request, authID int64, username, avatar string, authAdmin bool, token string, expiresIn int) { |
| 96 | if expiresIn <= 0 { |
| 97 | expiresIn = 86400 |
| 98 | } |
| 99 | user, err := s.Store.UpsertUser(r.Context(), authID, username, avatar, authAdmin) |
| 100 | if err != nil { |
| 101 | http.Error(w, err.Error(), http.StatusBadRequest) |
| 102 | return |
| 103 | } |
| 104 | user = s.maybeRefreshEntraAvatar(r.Context(), user, token) |
| 105 | exp := time.Now().Add(time.Duration(expiresIn) * time.Second) |
| 106 | sess, err := s.Store.CreateSession(r.Context(), user.ID, token, exp) |
| 107 | if err != nil { |
| 108 | http.Error(w, s.tr(r, "err.session"), http.StatusInternalServerError) |
| 109 | return |
| 110 | } |
| 111 | s.setSessionCookie(w, sess.ID, exp) |
| 112 | s.redirect(w, r, "/", s.tr(r, "flash.welcome", user.Username), "") |
| 113 | } |
| 114 | |
| 115 | func (s *Server) logout(w http.ResponseWriter, r *http.Request) { |
| 116 | if !s.csrfOK(w, r) { |
| 117 | return |
| 118 | } |
| 119 | p := s.who(r) |
| 120 | if p.OK { |
| 121 | _ = s.Auth.Logout(r.Context(), p.Session.AccessToken) |
| 122 | _ = s.Store.DeleteSession(r.Context(), p.Session.ID) |
| 123 | } |
| 124 | http.SetCookie(w, &http.Cookie{Name: "bluegit_session", Value: "", Path: "/", MaxAge: -1}) |
| 125 | http.Redirect(w, r, "/", http.StatusSeeOther) |
| 126 | } |
| 127 | |
| 128 | func (s *Server) home(w http.ResponseWriter, r *http.Request) { |
| 129 | v := s.view(w, r, "BlueGit") |
| 130 | if v.User != nil { |
| 131 | ids, err := s.Store.ListRepoIDs(r.Context(), v.User.ID) |
| 132 | if err != nil { |
| 133 | http.Error(w, s.tr(r, "err.overview"), http.StatusInternalServerError) |
| 134 | return |
| 135 | } |
| 136 | repos, err := s.Store.ReposByIDs(r.Context(), ids) |
| 137 | if err != nil { |
| 138 | http.Error(w, s.tr(r, "err.overview"), http.StatusInternalServerError) |
| 139 | return |
| 140 | } |
| 141 | store.SortReposByPush(repos) |
| 142 | // Oude links ?all=repos / ?all=groups gaan naar de tabs. |
| 143 | if all := r.URL.Query().Get("all"); all == "repos" || all == "groups" { |
| 144 | http.Redirect(w, r, "/?tab="+all, http.StatusSeeOther) |
| 145 | return |
| 146 | } |
| 147 | tab := r.URL.Query().Get("tab") |
| 148 | if tab != "repos" && tab != "groups" { |
| 149 | tab = "" |
| 150 | } |
| 151 | v.DashTab = tab |
| 152 | v.DashRepoN = len(repos) |
| 153 | if tab == "repos" { |
| 154 | repos = dashPage(&v, r, repos) |
| 155 | } else if len(repos) > dashLimit { |
| 156 | v.MoreRepos = len(repos) - dashLimit |
| 157 | repos = repos[:dashLimit] |
| 158 | } |
| 159 | v.Repos = repos |
| 160 | v.ReleaseRepos = s.releaseOnlyRepos(r, v.User.ID) |
| 161 | groups, err := s.Store.ListGroups(r.Context(), v.User.ID) |
| 162 | if err != nil { |
| 163 | http.Error(w, s.tr(r, "err.overview"), http.StatusInternalServerError) |
| 164 | return |
| 165 | } |
| 166 | if at, err := s.Store.GroupPushTimes(r.Context()); err == nil { |
| 167 | store.SortGroupsByPush(groups, at) |
| 168 | } |
| 169 | v.DashGroupN = len(groups) |
| 170 | if tab == "groups" { |
| 171 | groups = dashPage(&v, r, groups) |
| 172 | } else if len(groups) > dashLimit { |
| 173 | v.MoreGroups = len(groups) - dashLimit |
| 174 | groups = groups[:dashLimit] |
| 175 | } |
| 176 | v.Groups = groups |
| 177 | v.Title = s.tr(r, "nav.dashboard") |
| 178 | v.Page = "dashboard" |
| 179 | v.Heat = s.heatmap(r.Context(), v.User.ID, ids, s.langOf(r)) |
| 180 | total := 0 |
| 181 | if v.Heat != nil { |
| 182 | total = v.Heat.Total |
| 183 | } |
| 184 | card, _, _ := s.profileCard(r, *v.User, v.User.ID, total) |
| 185 | card.Heading = "h2" |
| 186 | v.Card = &card |
| 187 | s.render(w, "dashboard", v) |
| 188 | return |
| 189 | } |
| 190 | ids, err := s.Store.ListRepoIDs(r.Context(), 0) |
| 191 | if err == nil { |
| 192 | v.Repos, _ = s.Store.ReposByIDs(r.Context(), ids) |
| 193 | store.SortReposByPush(v.Repos) |
| 194 | } |
| 195 | v.ReleaseRepos = s.releaseOnlyRepos(r, 0) |
| 196 | v.Title = "" |
| 197 | s.render(w, "home", v) |
| 198 | } |
| 199 | |
| 200 | func (s *Server) newPage(w http.ResponseWriter, r *http.Request) { |
| 201 | if _, ok := s.loginRequired(w, r); !ok { |
| 202 | return |
| 203 | } |
| 204 | v := s.view(w, r, "title.new") |
| 205 | v.Page = "new" |
| 206 | v.Groups, _ = s.Store.ListGroups(r.Context(), v.User.ID) |
| 207 | s.render(w, "new", v) |
| 208 | } |
| 209 | |
| 210 | func (s *Server) account(w http.ResponseWriter, r *http.Request) { |
| 211 | u, ok := s.loginRequired(w, r) |
| 212 | if !ok { |
| 213 | return |
| 214 | } |
| 215 | v := s.view(w, r, "title.account") |
| 216 | v.Page = "account" |
| 217 | v.Tokens, _ = s.Store.ListTokens(r.Context(), u.ID) |
| 218 | for _, tok := range v.Tokens { |
| 219 | if !tok.ExpiresAt.IsZero() { |
| 220 | v.ShowExpiry = true |
| 221 | break |
| 222 | } |
| 223 | } |
| 224 | v.Keys, _ = s.Store.ListSSHKeys(r.Context(), u.ID) |
| 225 | v.NewToken = cookieVal(r, "bluegit_token_once") |
| 226 | if v.NewToken != "" { |
| 227 | http.SetCookie(w, &http.Cookie{Name: "bluegit_token_once", Value: "", Path: "/", MaxAge: -1}) |
| 228 | } |
| 229 | s.fillUserRunners(w, r, &v, u) |
| 230 | s.render(w, "account", v) |
| 231 | } |
| 232 | |
| 233 | func (s *Server) createToken(w http.ResponseWriter, r *http.Request) { |
| 234 | u, ok := s.loginRequired(w, r) |
| 235 | if !ok || !s.csrfOK(w, r) { |
| 236 | return |
| 237 | } |
| 238 | plain, _, err := s.opIssueToken(r.Context(), u, r.FormValue("name"), nil, time.Time{}) |
| 239 | if err != nil { |
| 240 | s.redirect(w, r, "/settings", "", s.trErr(r, err)) |
| 241 | return |
| 242 | } |
| 243 | secure := strings.HasPrefix(s.Cfg.BaseURL, "https://") |
| 244 | http.SetCookie(w, &http.Cookie{Name: "bluegit_token_once", Value: plain, Path: "/settings", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode}) |
| 245 | s.redirect(w, r, "/settings", s.tr(r, "flash.tokenCreated"), "") |
| 246 | } |
| 247 | |
| 248 | func (s *Server) deleteToken(w http.ResponseWriter, r *http.Request) { |
| 249 | u, ok := s.loginRequired(w, r) |
| 250 | if !ok || !s.csrfOK(w, r) { |
| 251 | return |
| 252 | } |
| 253 | var id int64 |
| 254 | _, _ = parseID(r.FormValue("id"), &id) |
| 255 | if err := s.opRevokeToken(r.Context(), u, id); err != nil { |
| 256 | s.redirect(w, r, "/settings", "", s.tr(r, "err.tokenMissing")) |
| 257 | return |
| 258 | } |
| 259 | s.redirect(w, r, "/settings", s.tr(r, "flash.tokenRevoked"), "") |
| 260 | } |
| 261 | |
| 262 | func (s *Server) addSSH(w http.ResponseWriter, r *http.Request) { |
| 263 | u, ok := s.loginRequired(w, r) |
| 264 | if !ok || !s.csrfOK(w, r) { |
| 265 | return |
| 266 | } |
| 267 | if err := s.opAddSSH(r.Context(), u, r.FormValue("name"), r.FormValue("key")); err != nil { |
| 268 | s.redirect(w, r, "/settings", "", s.commitProblem(r, err)) |
| 269 | return |
| 270 | } |
| 271 | s.redirect(w, r, "/settings", s.tr(r, "flash.sshAdded"), "") |
| 272 | } |
| 273 | |
| 274 | func (s *Server) deleteSSH(w http.ResponseWriter, r *http.Request) { |
| 275 | u, ok := s.loginRequired(w, r) |
| 276 | if !ok || !s.csrfOK(w, r) { |
| 277 | return |
| 278 | } |
| 279 | var id int64 |
| 280 | _, _ = parseID(r.FormValue("id"), &id) |
| 281 | if err := s.opRemoveSSH(r.Context(), u, id); err != nil { |
| 282 | s.redirect(w, r, "/settings", "", s.tr(r, "err.sshMissing")) |
| 283 | return |
| 284 | } |
| 285 | s.redirect(w, r, "/settings", s.tr(r, "flash.sshRemoved"), "") |
| 286 | } |
| 287 | |
| 288 | func (s *Server) export(w http.ResponseWriter, r *http.Request) { |
| 289 | u, ok := s.loginRequired(w, r) |
| 290 | if !ok { |
| 291 | return |
| 292 | } |
| 293 | payload := s.opExport(r.Context(), u) |
| 294 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 295 | w.Header().Set("Content-Disposition", `attachment; filename="bluegit-export.json"`) |
| 296 | enc := json.NewEncoder(w) |
| 297 | enc.SetIndent("", " ") |
| 298 | _ = enc.Encode(payload) |
| 299 | } |
| 300 | |
| 301 | func parseID(s string, dest *int64) (int64, error) { |
| 302 | var n int64 |
| 303 | for _, c := range s { |
| 304 | if c < '0' || c > '9' { |
| 305 | return 0, errBadID |
| 306 | } |
| 307 | n = n*10 + int64(c-'0') |
| 308 | } |
| 309 | if dest != nil { |
| 310 | *dest = n |
| 311 | } |
| 312 | return n, nil |
| 313 | } |
| 314 | |
| 315 | var errBadID = http.ErrMissingFile |
| 316 | |
| 317 | // dashLimit is het aantal repos en groepen op het overzicht. |
| 318 | const dashLimit = 10 |
| 319 | |
| 320 | // dashPerPage: de tabs Repositories en Groepen tonen 50 per pagina. |
| 321 | const dashPerPage = 50 |
| 322 | |
| 323 | func dashPage[T any](v *View, r *http.Request, list []T) []T { |
| 324 | pages := (len(list) + dashPerPage - 1) / dashPerPage |
| 325 | if pages < 1 { |
| 326 | pages = 1 |
| 327 | } |
| 328 | page, _ := strconv.Atoi(r.URL.Query().Get("page")) |
| 329 | if page < 1 { |
| 330 | page = 1 |
| 331 | } |
| 332 | if page > pages { |
| 333 | page = pages |
| 334 | } |
| 335 | v.DashPage, v.DashPages = page, pages |
| 336 | if page > 1 { |
| 337 | v.DashPrev = page - 1 |
| 338 | } |
| 339 | if page < pages { |
| 340 | v.DashNext = page + 1 |
| 341 | } |
| 342 | from := (page - 1) * dashPerPage |
| 343 | to := from + dashPerPage |
| 344 | if to > len(list) { |
| 345 | to = len(list) |
| 346 | } |
| 347 | return list[from:to] |
| 348 | } |