gitea

Зеркало из https://github.com/go-gitea/gitea
Форк
0
406 строк · 11.5 Кб
1
// Copyright 2016 The Gogs Authors. All rights reserved.
2
// Copyright 2019 The Gitea Authors. All rights reserved.
3
// SPDX-License-Identifier: MIT
4

5
package context
6

7
import (
8
	"context"
9
	"fmt"
10
	"net/http"
11
	"net/url"
12
	"strings"
13

14
	"code.gitea.io/gitea/models/unit"
15
	user_model "code.gitea.io/gitea/models/user"
16
	"code.gitea.io/gitea/modules/cache"
17
	"code.gitea.io/gitea/modules/git"
18
	"code.gitea.io/gitea/modules/gitrepo"
19
	"code.gitea.io/gitea/modules/httpcache"
20
	"code.gitea.io/gitea/modules/log"
21
	"code.gitea.io/gitea/modules/setting"
22
	"code.gitea.io/gitea/modules/web"
23
	web_types "code.gitea.io/gitea/modules/web/types"
24
)
25

26
// APIContext is a specific context for API service
27
type APIContext struct {
28
	*Base
29

30
	Cache cache.StringCache
31

32
	Doer        *user_model.User // current signed-in user
33
	IsSigned    bool
34
	IsBasicAuth bool
35

36
	ContextUser *user_model.User // the user which is being visited, in most cases it differs from Doer
37

38
	Repo    *Repository
39
	Org     *APIOrganization
40
	Package *Package
41
}
42

43
func init() {
44
	web.RegisterResponseStatusProvider[*APIContext](func(req *http.Request) web_types.ResponseStatusProvider {
45
		return req.Context().Value(apiContextKey).(*APIContext)
46
	})
47
}
48

49
// Currently, we have the following common fields in error response:
50
// * message: the message for end users (it shouldn't be used for error type detection)
51
//            if we need to indicate some errors, we should introduce some new fields like ErrorCode or ErrorType
52
// * url:     the swagger document URL
53

54
// APIError is error format response
55
// swagger:response error
56
type APIError struct {
57
	Message string `json:"message"`
58
	URL     string `json:"url"`
59
}
60

61
// APIValidationError is error format response related to input validation
62
// swagger:response validationError
63
type APIValidationError struct {
64
	Message string `json:"message"`
65
	URL     string `json:"url"`
66
}
67

68
// APIInvalidTopicsError is error format response to invalid topics
69
// swagger:response invalidTopicsError
70
type APIInvalidTopicsError struct {
71
	Message       string   `json:"message"`
72
	InvalidTopics []string `json:"invalidTopics"`
73
}
74

75
// APIEmpty is an empty response
76
// swagger:response empty
77
type APIEmpty struct{}
78

79
// APIForbiddenError is a forbidden error response
80
// swagger:response forbidden
81
type APIForbiddenError struct {
82
	APIError
83
}
84

85
// APINotFound is a not found empty response
86
// swagger:response notFound
87
type APINotFound struct{}
88

89
// APIConflict is a conflict empty response
90
// swagger:response conflict
91
type APIConflict struct{}
92

93
// APIRedirect is a redirect response
94
// swagger:response redirect
95
type APIRedirect struct{}
96

97
// APIString is a string response
98
// swagger:response string
99
type APIString string
100

101
// APIRepoArchivedError is an error that is raised when an archived repo should be modified
102
// swagger:response repoArchivedError
103
type APIRepoArchivedError struct {
104
	APIError
105
}
106

107
// ServerError responds with error message, status is 500
108
func (ctx *APIContext) ServerError(title string, err error) {
109
	ctx.Error(http.StatusInternalServerError, title, err)
110
}
111

112
// Error responds with an error message to client with given obj as the message.
113
// If status is 500, also it prints error to log.
114
func (ctx *APIContext) Error(status int, title string, obj any) {
115
	var message string
116
	if err, ok := obj.(error); ok {
117
		message = err.Error()
118
	} else {
119
		message = fmt.Sprintf("%s", obj)
120
	}
121

122
	if status == http.StatusInternalServerError {
123
		log.ErrorWithSkip(1, "%s: %s", title, message)
124

125
		if setting.IsProd && !(ctx.Doer != nil && ctx.Doer.IsAdmin) {
126
			message = ""
127
		}
128
	}
129

130
	ctx.JSON(status, APIError{
131
		Message: message,
132
		URL:     setting.API.SwaggerURL,
133
	})
134
}
135

136
// InternalServerError responds with an error message to the client with the error as a message
137
// and the file and line of the caller.
138
func (ctx *APIContext) InternalServerError(err error) {
139
	log.ErrorWithSkip(1, "InternalServerError: %v", err)
140

141
	var message string
142
	if !setting.IsProd || (ctx.Doer != nil && ctx.Doer.IsAdmin) {
143
		message = err.Error()
144
	}
145

146
	ctx.JSON(http.StatusInternalServerError, APIError{
147
		Message: message,
148
		URL:     setting.API.SwaggerURL,
149
	})
150
}
151

152
type apiContextKeyType struct{}
153

154
var apiContextKey = apiContextKeyType{}
155

156
// GetAPIContext returns a context for API routes
157
func GetAPIContext(req *http.Request) *APIContext {
158
	return req.Context().Value(apiContextKey).(*APIContext)
159
}
160

161
func genAPILinks(curURL *url.URL, total, pageSize, curPage int) []string {
162
	page := NewPagination(total, pageSize, curPage, 0)
163
	paginater := page.Paginater
164
	links := make([]string, 0, 4)
165

166
	if paginater.HasNext() {
167
		u := *curURL
168
		queries := u.Query()
169
		queries.Set("page", fmt.Sprintf("%d", paginater.Next()))
170
		u.RawQuery = queries.Encode()
171

172
		links = append(links, fmt.Sprintf("<%s%s>; rel=\"next\"", setting.AppURL, u.RequestURI()[1:]))
173
	}
174
	if !paginater.IsLast() {
175
		u := *curURL
176
		queries := u.Query()
177
		queries.Set("page", fmt.Sprintf("%d", paginater.TotalPages()))
178
		u.RawQuery = queries.Encode()
179

180
		links = append(links, fmt.Sprintf("<%s%s>; rel=\"last\"", setting.AppURL, u.RequestURI()[1:]))
181
	}
182
	if !paginater.IsFirst() {
183
		u := *curURL
184
		queries := u.Query()
185
		queries.Set("page", "1")
186
		u.RawQuery = queries.Encode()
187

188
		links = append(links, fmt.Sprintf("<%s%s>; rel=\"first\"", setting.AppURL, u.RequestURI()[1:]))
189
	}
190
	if paginater.HasPrevious() {
191
		u := *curURL
192
		queries := u.Query()
193
		queries.Set("page", fmt.Sprintf("%d", paginater.Previous()))
194
		u.RawQuery = queries.Encode()
195

196
		links = append(links, fmt.Sprintf("<%s%s>; rel=\"prev\"", setting.AppURL, u.RequestURI()[1:]))
197
	}
198
	return links
199
}
200

201
// SetLinkHeader sets pagination link header by given total number and page size.
202
func (ctx *APIContext) SetLinkHeader(total, pageSize int) {
203
	links := genAPILinks(ctx.Req.URL, total, pageSize, ctx.FormInt("page"))
204

205
	if len(links) > 0 {
206
		ctx.RespHeader().Set("Link", strings.Join(links, ","))
207
		ctx.AppendAccessControlExposeHeaders("Link")
208
	}
209
}
210

211
// APIContexter returns apicontext as middleware
212
func APIContexter() func(http.Handler) http.Handler {
213
	return func(next http.Handler) http.Handler {
214
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
215
			base, baseCleanUp := NewBaseContext(w, req)
216
			ctx := &APIContext{
217
				Base:  base,
218
				Cache: cache.GetCache(),
219
				Repo:  &Repository{PullRequest: &PullRequest{}},
220
				Org:   &APIOrganization{},
221
			}
222
			defer baseCleanUp()
223

224
			ctx.Base.AppendContextValue(apiContextKey, ctx)
225
			ctx.Base.AppendContextValueFunc(gitrepo.RepositoryContextKey, func() any { return ctx.Repo.GitRepo })
226

227
			// If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
228
			if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
229
				if err := ctx.Req.ParseMultipartForm(setting.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
230
					ctx.InternalServerError(err)
231
					return
232
				}
233
			}
234

235
			httpcache.SetCacheControlInHeader(ctx.Resp.Header(), 0, "no-transform")
236
			ctx.Resp.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
237

238
			next.ServeHTTP(ctx.Resp, ctx.Req)
239
		})
240
	}
241
}
242

243
// NotFound handles 404s for APIContext
244
// String will replace message, errors will be added to a slice
245
func (ctx *APIContext) NotFound(objs ...any) {
246
	message := ctx.Locale.TrString("error.not_found")
247
	var errors []string
248
	for _, obj := range objs {
249
		// Ignore nil
250
		if obj == nil {
251
			continue
252
		}
253

254
		if err, ok := obj.(error); ok {
255
			errors = append(errors, err.Error())
256
		} else {
257
			message = obj.(string)
258
		}
259
	}
260

261
	ctx.JSON(http.StatusNotFound, map[string]any{
262
		"message": message,
263
		"url":     setting.API.SwaggerURL,
264
		"errors":  errors,
265
	})
266
}
267

268
// ReferencesGitRepo injects the GitRepo into the Context
269
// you can optional skip the IsEmpty check
270
func ReferencesGitRepo(allowEmpty ...bool) func(ctx *APIContext) (cancel context.CancelFunc) {
271
	return func(ctx *APIContext) (cancel context.CancelFunc) {
272
		// Empty repository does not have reference information.
273
		if ctx.Repo.Repository.IsEmpty && !(len(allowEmpty) != 0 && allowEmpty[0]) {
274
			return nil
275
		}
276

277
		// For API calls.
278
		if ctx.Repo.GitRepo == nil {
279
			gitRepo, err := gitrepo.OpenRepository(ctx, ctx.Repo.Repository)
280
			if err != nil {
281
				ctx.Error(http.StatusInternalServerError, fmt.Sprintf("Open Repository %v failed", ctx.Repo.Repository.FullName()), err)
282
				return cancel
283
			}
284
			ctx.Repo.GitRepo = gitRepo
285
			// We opened it, we should close it
286
			return func() {
287
				// If it's been set to nil then assume someone else has closed it.
288
				if ctx.Repo.GitRepo != nil {
289
					_ = ctx.Repo.GitRepo.Close()
290
				}
291
			}
292
		}
293

294
		return cancel
295
	}
296
}
297

298
// RepoRefForAPI handles repository reference names when the ref name is not explicitly given
299
func RepoRefForAPI(next http.Handler) http.Handler {
300
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
301
		ctx := GetAPIContext(req)
302

303
		if ctx.Repo.GitRepo == nil {
304
			ctx.InternalServerError(fmt.Errorf("no open git repo"))
305
			return
306
		}
307

308
		if ref := ctx.FormTrim("ref"); len(ref) > 0 {
309
			commit, err := ctx.Repo.GitRepo.GetCommit(ref)
310
			if err != nil {
311
				if git.IsErrNotExist(err) {
312
					ctx.NotFound()
313
				} else {
314
					ctx.Error(http.StatusInternalServerError, "GetCommit", err)
315
				}
316
				return
317
			}
318
			ctx.Repo.Commit = commit
319
			ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
320
			ctx.Repo.TreePath = ctx.PathParam("*")
321
			next.ServeHTTP(w, req)
322
			return
323
		}
324

325
		refName := getRefName(ctx.Base, ctx.Repo, RepoRefAny)
326
		var err error
327

328
		if ctx.Repo.GitRepo.IsBranchExist(refName) {
329
			ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
330
			if err != nil {
331
				ctx.InternalServerError(err)
332
				return
333
			}
334
			ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
335
		} else if ctx.Repo.GitRepo.IsTagExist(refName) {
336
			ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
337
			if err != nil {
338
				ctx.InternalServerError(err)
339
				return
340
			}
341
			ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
342
		} else if len(refName) == ctx.Repo.GetObjectFormat().FullLength() {
343
			ctx.Repo.CommitID = refName
344
			ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
345
			if err != nil {
346
				ctx.NotFound("GetCommit", err)
347
				return
348
			}
349
		} else {
350
			ctx.NotFound(fmt.Errorf("not exist: '%s'", ctx.PathParam("*")))
351
			return
352
		}
353

354
		next.ServeHTTP(w, req)
355
	})
356
}
357

358
// HasAPIError returns true if error occurs in form validation.
359
func (ctx *APIContext) HasAPIError() bool {
360
	hasErr, ok := ctx.Data["HasError"]
361
	if !ok {
362
		return false
363
	}
364
	return hasErr.(bool)
365
}
366

367
// GetErrMsg returns error message in form validation.
368
func (ctx *APIContext) GetErrMsg() string {
369
	msg, _ := ctx.Data["ErrorMsg"].(string)
370
	if msg == "" {
371
		msg = "invalid form data"
372
	}
373
	return msg
374
}
375

376
// NotFoundOrServerError use error check function to determine if the error
377
// is about not found. It responds with 404 status code for not found error,
378
// or error context description for logging purpose of 500 server error.
379
func (ctx *APIContext) NotFoundOrServerError(logMsg string, errCheck func(error) bool, logErr error) {
380
	if errCheck(logErr) {
381
		ctx.JSON(http.StatusNotFound, nil)
382
		return
383
	}
384
	ctx.Error(http.StatusInternalServerError, "NotFoundOrServerError", logMsg)
385
}
386

387
// IsUserSiteAdmin returns true if current user is a site admin
388
func (ctx *APIContext) IsUserSiteAdmin() bool {
389
	return ctx.IsSigned && ctx.Doer.IsAdmin
390
}
391

392
// IsUserRepoAdmin returns true if current user is admin in current repo
393
func (ctx *APIContext) IsUserRepoAdmin() bool {
394
	return ctx.Repo.IsAdmin()
395
}
396

397
// IsUserRepoWriter returns true if current user has write privilege in current repo
398
func (ctx *APIContext) IsUserRepoWriter(unitTypes []unit.Type) bool {
399
	for _, unitType := range unitTypes {
400
		if ctx.Repo.CanWrite(unitType) {
401
			return true
402
		}
403
	}
404

405
	return false
406
}
407

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.