context

package
v0.0.0-...-495e01f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 12, 2023 License: Apache-2.0 Imports: 48 Imported by: 0

Documentation

Index

Constants

View Source
const CookieNameFlash = "gitea_flash"
View Source
const CsrfTokenTimeout = 24 * time.Hour

CsrfTokenTimeout represents the duration that XSRF tokens are valid. It is exported so clients may set cookie timeouts that match generated tokens.

Variables

View Source
var CsrfTokenRegenerationInterval = 10 * time.Minute

CsrfTokenRegenerationInterval is the interval between token generations, old tokens are still valid before CsrfTokenTimeout

View Source
var WebContextKey = webContextKeyType{}

Functions

func APIContexter

func APIContexter() func(http.Handler) http.Handler

APIContexter returns apicontext as middleware

func AccessLogger

func AccessLogger() func(http.Handler) http.Handler

AccessLogger returns a middleware to log access logger

func Contexter

func Contexter() func(next http.Handler) http.Handler

Contexter initializes a classic context for a request.

func GenerateCsrfToken

func GenerateCsrfToken(key, userID, actionID string, now time.Time) string

GenerateCsrfToken returns a URL-safe secure XSRF token that expires in CsrfTokenTimeout hours. key is a secret key for your application. userID is a unique identifier for the user. actionID is the action the user is taking (e.g. POSTing to a particular path).

func GetImageCaptcha

func GetImageCaptcha() *captcha.Captcha

GetImageCaptcha returns global image captcha

func GetQueryBeforeSince

func GetQueryBeforeSince(ctx *Base) (before, since int64, err error)

GetQueryBeforeSince return parsed time (unix format) from URL query's before and since

func OverrideContext

func OverrideContext(ctx *PrivateContext) (cancel context.CancelFunc)

OverrideContext overrides the underlying request context for Done() etc. This function should be used when there is a need for work to continue even if the request has been cancelled. Primarily this affects hook/post-receive and hook/proc-receive both of which need to continue working even if the underlying request has timed out from the ssh/http push

func PackageAssignment

func PackageAssignment() func(ctx *Context)

PackageAssignment returns a middleware to handle Context.Package assignment

func PackageAssignmentAPI

func PackageAssignmentAPI() func(ctx *APIContext)

在 Gitea 中,PackageAssignmentAPI 是一个 API 中间件,用于处理上下文中的 Context.Package 赋值。让我们更详细地解释一下其作用。 在 Gitea 中,Context.Package 是一个表示软件包的数据结构。该结构包含有关软件包的各种信息,例如名称、版本、作者、依赖关系等。 PackageAssignmentAPI 中间件的作用是为每个 API 请求分配或填充适当的 Context.Package。

PackageAssignmentAPI returns a middleware to handle Context.Package assignment

func PackageContexter

func PackageContexter() func(next http.Handler) http.Handler

PackageContexter initializes a package context for a request.

func ParseCsrfToken

func ParseCsrfToken(token string) (issueTime time.Time, ok bool)

func PrivateContexter

func PrivateContexter() func(http.Handler) http.Handler

PrivateContexter returns apicontext as middleware

func RedirectToUser

func RedirectToUser(ctx *Base, userName string, redirectUserID int64)

RedirectToUser redirect to a differently-named user

func SetCaptchaData

func SetCaptchaData(ctx *Context)

SetCaptchaData sets common captcha data

func ValidCsrfToken

func ValidCsrfToken(token, key, userID, actionID string, now time.Time) bool

ValidCsrfToken returns true if token is a valid and unexpired token returned by Generate.

func VerifyCaptcha

func VerifyCaptcha(ctx *Context, tpl base.TplName, form any)

VerifyCaptcha verifies Captcha data No-op if captchas are not enabled

Types

type APIConflict

type APIConflict struct{}

APIConflict is a conflict empty response swagger:response conflict

type APIContext

type APIContext struct {
	*Base

	Cache cache.Cache

	Doer        *user_model.User // current signed-in user
	IsSigned    bool
	IsBasicAuth bool

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

	//Repo    *Repository
	//Org     *APIOrganization
	Package *Package
}

APIContext is a specific context for API service

func GetAPIContext

func GetAPIContext(req *http.Request) *APIContext

GetAPIContext returns a context for API routes

func (*APIContext) Error

func (ctx *APIContext) Error(status int, title string, obj any)

Error responds with an error message to client with given obj as the message. If status is 500, also it prints error to log.

func (*APIContext) GetErrMsg

func (ctx *APIContext) GetErrMsg() string

GetErrMsg returns error message in form validation.

func (*APIContext) HasAPIError

func (ctx *APIContext) HasAPIError() bool

HasAPIError returns true if error occurs in form validation.

func (*APIContext) InternalServerError

func (ctx *APIContext) InternalServerError(err error)

InternalServerError responds with an error message to the client with the error as a message and the file and line of the caller.

func (*APIContext) IsUserSiteAdmin

func (ctx *APIContext) IsUserSiteAdmin() bool

IsUserSiteAdmin returns true if current user is a site admin

func (*APIContext) NotFound

func (ctx *APIContext) NotFound(objs ...any)

NotFound handles 404s for APIContext String will replace message, errors will be added to a slice

func (*APIContext) NotFoundOrServerError

func (ctx *APIContext) NotFoundOrServerError(logMsg string, errCheck func(error) bool, logErr error)

NotFoundOrServerError use error check function to determine if the error is about not found. It responds with 404 status code for not found error, or error context description for logging purpose of 500 server error.

func (*APIContext) ServerError

func (ctx *APIContext) ServerError(title string, err error)

ServerError responds with error message, status is 500

func (*APIContext) SetLinkHeader

func (ctx *APIContext) SetLinkHeader(total, pageSize int)

SetLinkHeader sets pagination link header by given total number and page size.

type APIEmpty

type APIEmpty struct{}

APIEmpty is an empty response swagger:response empty

type APIError

type APIError struct {
	Message string `json:"message"`
	URL     string `json:"url"`
}

APIError is error format response swagger:response error

type APIForbiddenError

type APIForbiddenError struct {
	APIError
}

APIForbiddenError is a forbidden error response swagger:response forbidden

type APIInvalidTopicsError

type APIInvalidTopicsError struct {
	Message       string   `json:"message"`
	InvalidTopics []string `json:"invalidTopics"`
}

APIInvalidTopicsError is error format response to invalid topics swagger:response invalidTopicsError

type APINotFound

type APINotFound struct{}

APINotFound is a not found empty response swagger:response notFound

type APIRedirect

type APIRedirect struct{}

APIRedirect is a redirect response swagger:response redirect

type APIString

type APIString string

APIString is a string response swagger:response string

type APIValidationError

type APIValidationError struct {
	Message string `json:"message"`
	URL     string `json:"url"`
}

APIValidationError is error format response related to input validation swagger:response validationError

type Base

type Base struct {
	Resp ResponseWriter
	Req  *http.Request

	// Data is prepared by ContextDataStore middleware, this field only refers to the pre-created/prepared ContextData.
	// Although it's mainly used for MVC templates, sometimes it's also used to pass data between middlewares/handler
	Data middleware.ContextData

	// Locale is mainly for Web context, although the API context also uses it in some cases: message response, form validation
	Locale translation.Locale
	// contains filtered or unexported fields
}

func NewBaseContext

func NewBaseContext(resp http.ResponseWriter, req *http.Request) (b *Base, closeFunc func())

func (*Base) AppendAccessControlExposeHeaders

func (b *Base) AppendAccessControlExposeHeaders(names ...string)

AppendAccessControlExposeHeaders append headers by name to "Access-Control-Expose-Headers" header

func (*Base) AppendContextValue

func (b *Base) AppendContextValue(key, value any) any

func (*Base) AppendContextValueFunc

func (b *Base) AppendContextValueFunc(key any, valueFn func() any) any

func (*Base) Deadline

func (b *Base) Deadline() (deadline time.Time, ok bool)

func (*Base) Done

func (b *Base) Done() <-chan struct{}

func (*Base) Err

func (b *Base) Err() error

func (*Base) Error

func (b *Base) Error(status int, contents ...string)

Error returned an error to web browser

func (*Base) FormBool

func (b *Base) FormBool(key string) bool

FormBool returns true if the value for the provided key in the form is "1", "true" or "on"

func (*Base) FormInt

func (b *Base) FormInt(key string) int

FormInt returns the first value for the provided key in the form as an int

func (*Base) FormInt64

func (b *Base) FormInt64(key string) int64

FormInt64 returns the first value for the provided key in the form as an int64

func (*Base) FormOptionalBool

func (b *Base) FormOptionalBool(key string) util.OptionalBool

FormOptionalBool returns an OptionalBoolTrue or OptionalBoolFalse if the value for the provided key exists in the form else it returns OptionalBoolNone

func (*Base) FormString

func (b *Base) FormString(key string) string

FormString returns the first value matching the provided key in the form as a string

func (*Base) FormStrings

func (b *Base) FormStrings(key string) []string

FormStrings returns a string slice for the provided key from the form

func (*Base) FormTrim

func (b *Base) FormTrim(key string) string

FormTrim returns the first value for the provided key in the form as a space trimmed string

func (*Base) GetData

func (b *Base) GetData() middleware.ContextData

func (*Base) JSON

func (b *Base) JSON(status int, content any)

JSON render content as JSON

func (*Base) JSONContainer

func (b *Base) JSONContainer(status int, content any)

JSON render content as JSON

func (*Base) JSONWithDetail

func (b *Base) JSONWithDetail(status int, message string, content any)

JSON render content as JSON

func (*Base) Params

func (b *Base) Params(p string) string

Params returns the param on route

func (*Base) ParamsInt64

func (b *Base) ParamsInt64(p string) int64

ParamsInt64 returns the param on route as int64

func (*Base) PathParamRaw

func (b *Base) PathParamRaw(p string) string

func (*Base) PlainText

func (b *Base) PlainText(status int, text string)

PlainText renders content as plain text

func (*Base) PlainTextBytes

func (b *Base) PlainTextBytes(status int, bs []byte)

PlainTextBytes renders bytes as plain text

func (*Base) Redirect

func (b *Base) Redirect(location string, status ...int)

Redirect redirects the request

func (*Base) RemoteAddr

func (b *Base) RemoteAddr() string

RemoteAddr returns the client machine ip address

func (*Base) RespHeader

func (b *Base) RespHeader() http.Header

RespHeader returns the response header

func (*Base) ServeContent

func (b *Base) ServeContent(r io.ReadSeeker, opts *ServeHeaderOptions)

ServeContent serves content to http request

func (*Base) SetFormString

func (b *Base) SetFormString(key, value string)

func (*Base) SetParams

func (b *Base) SetParams(k, v string)

SetParams set params into routes

func (*Base) SetServeHeaders

func (b *Base) SetServeHeaders(opt *ServeHeaderOptions)

func (*Base) SetTotalCountHeader

func (b *Base) SetTotalCountHeader(total int64)

SetTotalCountHeader set "X-Total-Count" header

func (*Base) Status

func (b *Base) Status(status int)

Status writes status code

func (*Base) Tr

func (b *Base) Tr(msg string, args ...any) string

func (*Base) TrN

func (b *Base) TrN(cnt any, key1, keyN string, args ...any) string

func (*Base) Value

func (b *Base) Value(key any) any

func (*Base) Write

func (b *Base) Write(bs []byte) (int, error)

Write writes data to web browser

func (*Base) Written

func (b *Base) Written() bool

Written returns true if there are something sent to web browser

func (*Base) WrittenStatus

func (b *Base) WrittenStatus() int

type CSRFProtector

type CSRFProtector interface {
	// GetHeaderName returns HTTP header to search for token.
	GetHeaderName() string
	// GetFormName returns form value to search for token.
	GetFormName() string
	// GetToken returns the token.
	GetToken() string
	// Validate validates the token in http context.
	Validate(ctx *Context)
	// DeleteCookie deletes the cookie
	DeleteCookie(ctx *Context)
}

CSRFProtector represents a CSRF protector and is used to get the current token and validate the token.

func PrepareCSRFProtector

func PrepareCSRFProtector(opt CsrfOptions, ctx *Context) CSRFProtector

PrepareCSRFProtector returns a CSRFProtector to be used for every request. Additionally, depending on options set, generated tokens will be sent via Header and/or Cookie.

type Context

type Context struct {
	*Base

	TemplateContext TemplateContext

	//Render   Render
	PageData map[string]any // data used by JavaScript modules in one page, it's `window.config.pageData`

	Cache   cache.Cache
	Csrf    CSRFProtector
	Flash   *middleware.Flash
	Session session.Store

	Link string // current request URL (without query string)

	Doer        *user_model.User // current signed-in user
	IsSigned    bool
	IsBasicAuth bool

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

	//Repo    *Repository
	//Org     *Organization
	Package *Package
}

// Render represents a template render

type Render interface {
	TemplateLookup(tmpl string, templateCtx context.Context) (templates.TemplateExecutor, error)
	HTML(w io.Writer, status int, name string, data any, templateCtx context.Context) error
}

Context represents context of a request.

func GetWebContext

func GetWebContext(req *http.Request) *Context

func NewWebContext

func NewWebContext(base *Base, session session.Store) *Context

func (*Context) CookieDecrypt

func (ctx *Context) CookieDecrypt(secret, val string) (string, bool)

CookieDecrypt returns given value from with secret string.

func (*Context) CookieEncrypt

func (ctx *Context) CookieEncrypt(secret, value string) string

CookieEncrypt encrypts a given value using the provided secret

func (*Context) DeleteSiteCookie

func (ctx *Context) DeleteSiteCookie(name string)

DeleteSiteCookie convenience function to delete most cookies consistently CSRF and a few others are the exception here

func (*Context) GetErrMsg

func (ctx *Context) GetErrMsg() string

GetErrMsg returns error message in form validation.

func (*Context) GetSiteCookie

func (ctx *Context) GetSiteCookie(name string) string

GetSiteCookie returns given cookie value from request header.

func (*Context) GetSuperSecureCookie

func (ctx *Context) GetSuperSecureCookie(secret, name string) (string, bool)

GetSuperSecureCookie returns given cookie value from request header with secret string.

func (*Context) HasError

func (ctx *Context) HasError() bool

HasError returns true if error occurs in form validation. Attention: this function changes ctx.Data and ctx.Flash

func (*Context) IsUserSiteAdmin

func (ctx *Context) IsUserSiteAdmin() bool

IsUserSiteAdmin returns true if current user is a site admin

func (*Context) JSONError

func (ctx *Context) JSONError(msg string)

func (*Context) JSONOK

func (ctx *Context) JSONOK()

func (*Context) JSONRedirect

func (ctx *Context) JSONRedirect(redirect string)

func (*Context) NotFound

func (ctx *Context) NotFound(logMsg string, logErr error)

NotFound displays a 404 (Not Found) page and prints the given error, if any.

func (*Context) NotFoundOrServerError

func (ctx *Context) NotFoundOrServerError(logMsg string, errCheck func(error) bool, logErr error)

NotFoundOrServerError use error check function to determine if the error is about not found. It responds with 404 status code for not found error, or error context description for logging purpose of 500 server error. TODO: remove the "errCheck" and use util.ErrNotFound to check

func (*Context) RedirectToFirst

func (ctx *Context) RedirectToFirst(location ...string)

RedirectToFirst redirects to first not empty URL

func (*Context) ServerError

func (ctx *Context) ServerError(logMsg string, logErr error)

ServerError displays a 500 (Internal Server Error) page and prints the given error, if any.

func (*Context) SetSiteCookie

func (ctx *Context) SetSiteCookie(name, value string, maxAge int)

SetSiteCookie convenience function to set most cookies consistently CSRF and a few others are the exception here

func (*Context) SetSuperSecureCookie

func (ctx *Context) SetSuperSecureCookie(secret, name, value string, maxAge int)

SetSuperSecureCookie sets given cookie value to response header with secret string.

func (*Context) TrHTMLEscapeArgs

func (ctx *Context) TrHTMLEscapeArgs(msg string, args ...string) string

TrHTMLEscapeArgs runs ".Locale.Tr()" but pre-escapes all arguments with html.EscapeString. This is useful if the locale message is intended to only produce HTML content.

func (*Context) UploadStream

func (ctx *Context) UploadStream() (rd io.ReadCloser, needToClose bool, err error)

UploadStream returns the request body or the first form file Only form files need to get closed.

type CsrfOptions

type CsrfOptions struct {
	// The global secret value used to generate Tokens.
	Secret string
	// HTTP header used to set and get token.
	Header string
	// Form value used to set and get token.
	Form string
	// Cookie value used to set and get token.
	Cookie string
	// Cookie domain.
	CookieDomain string
	// Cookie path.
	CookiePath     string
	CookieHTTPOnly bool
	// SameSite set the cookie SameSite type
	SameSite http.SameSite
	// Key used for getting the unique ID per user.
	SessionKey string

	// If true, send token via X-Csrf-Token header.
	SetHeader bool
	// If true, send token via _csrf cookie.
	SetCookie bool
	// Set the Secure flag to true on the cookie.
	Secure bool
	// Disallow Origin appear in request header.
	Origin bool
	// Cookie lifetime. Default is 0
	CookieLifeTime int
	// contains filtered or unexported fields
}

CsrfOptions maintains options to manage behavior of Generate.

type Package

type Package struct {
	Owner      *user_model.User
	AccessMode perm.AccessMode
	Descriptor *packages_model.PackageDescriptor
}

Package contains owner, access mode and optional the package descriptor

type Pagination

type Pagination struct {
	Paginater *paginator.Paginator
	// contains filtered or unexported fields
}

Pagination provides a pagination via paginator.Paginator and additional configurations for the link params used in rendering

func NewPagination

func NewPagination(total, pagingNum, current, numPages int) *Pagination

NewPagination creates a new instance of the Pagination struct. "pagingNum" is "page size" or "limit", "current" is "page"

func (*Pagination) AddParam

func (p *Pagination) AddParam(ctx *Context, paramKey, ctxKey string)

AddParam adds a value from context identified by ctxKey as link param under a given paramKey

func (*Pagination) AddParamString

func (p *Pagination) AddParamString(key, value string)

AddParamString adds a string parameter directly

func (*Pagination) GetParams

func (p *Pagination) GetParams() template.URL

GetParams returns the configured URL params

func (*Pagination) SetDefaultParams

func (p *Pagination) SetDefaultParams(ctx *Context)

SetDefaultParams sets common pagination params that are often used

type PrivateContext

type PrivateContext struct {
	*Base
	Override context.Context
}

PrivateContext represents a context for private routes

func GetPrivateContext

func GetPrivateContext(req *http.Request) *PrivateContext

GetPrivateContext returns a context for Private routes

func (*PrivateContext) Deadline

func (ctx *PrivateContext) Deadline() (deadline time.Time, ok bool)

Deadline is part of the interface for context.Context and we pass this to the request context

func (*PrivateContext) Done

func (ctx *PrivateContext) Done() <-chan struct{}

Done is part of the interface for context.Context and we pass this to the request context

func (*PrivateContext) Err

func (ctx *PrivateContext) Err() error

Err is part of the interface for context.Context and we pass this to the request context

type Response

type Response struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

Response represents a response

func WrapResponseWriter

func WrapResponseWriter(resp http.ResponseWriter) *Response

func (*Response) Before

func (r *Response) Before(f func(ResponseWriter))

Before allows for a function to be called before the ResponseWriter has been written to. This is useful for setting headers or any other operations that must happen before a response has been written.

func (*Response) Flush

func (r *Response) Flush()

Flush flushes cached data

func (*Response) Size

func (r *Response) Size() int

func (*Response) Status

func (r *Response) Status() int

func (*Response) Write

func (r *Response) Write(bs []byte) (int, error)

Write writes bytes to HTTP endpoint

func (*Response) WriteHeader

func (r *Response) WriteHeader(statusCode int)

WriteHeader write status code

func (*Response) WrittenStatus

func (r *Response) WrittenStatus() int

WrittenStatus returned status code written

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	web_types.ResponseStatusProvider

	Before(func(ResponseWriter))

	Status() int // used by access logger template
	Size() int   // used by access logger template
}

ResponseWriter represents a response writer for HTTP

type ServeHeaderOptions

type ServeHeaderOptions httplib.ServeHeaderOptions

type TemplateContext

type TemplateContext map[string]any

func NewTemplateContext

func NewTemplateContext(ctx context.Context) TemplateContext

func NewTemplateContextForWeb

func NewTemplateContextForWeb(ctx *Context) TemplateContext

func (TemplateContext) DataRaceCheck

func (c TemplateContext) DataRaceCheck(dataCtx context.Context) (string, error)

DataRaceCheck checks whether the template context function "ctx()" returns the consistent context as the current template's rendering context (request context), to help to find data race issues as early as possible. When the code is proven to be correct and stable, this function should be removed.

func (TemplateContext) Deadline

func (c TemplateContext) Deadline() (deadline time.Time, ok bool)

func (TemplateContext) Done

func (c TemplateContext) Done() <-chan struct{}

func (TemplateContext) Err

func (c TemplateContext) Err() error

func (TemplateContext) Value

func (c TemplateContext) Value(key any) any

type ValidateContext

type ValidateContext struct {
	*Base
}

ValidateContext is a special context for form validation middleware. It may be different from other contexts.

func GetValidateContext

func GetValidateContext(req *http.Request) (ctx *ValidateContext)

GetValidateContext gets a context for middleware form validation

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL