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