context

package
v1.24.0-dev Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2024 License: MIT Imports: 67 Imported by: 4

Documentation

Index

Constants

View Source
const (
	CsrfHeaderName = "X-Csrf-Token"
	CsrfFormName   = "_csrf"
)
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 added in v1.22.0

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

APIContexter returns apicontext as middleware

func AccessLogger added in v1.22.0

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

AccessLogger returns a middleware to log access logger

func CanEnableEditor added in v1.22.0

func CanEnableEditor() func(ctx *Context)

CanEnableEditor checks if the user is allowed to write to the branch of the repo

func CheckRepoScopedToken added in v1.22.0

func CheckRepoScopedToken(ctx *Context, repo *repo_model.Repository, level auth_model.AccessTokenScopeLevel)

CheckRepoScopedToken check whether personal access token has repo scope

func ComposeGoGetImport added in v1.22.0

func ComposeGoGetImport(ctx context.Context, owner, repo string) string

ComposeGoGetImport returns go-get-import meta content.

func Contexter added in v1.22.0

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

Contexter initializes a classic context for a request.

func EarlyResponseForGoGetMeta added in v1.22.0

func EarlyResponseForGoGetMeta(ctx *Context)

EarlyResponseForGoGetMeta responses appropriate go-get meta with status 200 if user does not have actual access to the requested repository, or the owner or repository does not exist at all. This is particular a workaround for "go get" command which does not respect .netrc file.

func GenerateCsrfToken added in v1.22.0

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 added in v1.22.0

func GetImageCaptcha() *captcha.Captcha

GetImageCaptcha returns global image captcha

func GetOrganizationByParams added in v1.22.0

func GetOrganizationByParams(ctx *Context)

func GetQueryBeforeSince added in v1.22.0

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

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

func GitHookService added in v1.22.0

func GitHookService() func(ctx *Context)

GitHookService checks if repository Git hooks service has been enabled.

func HandleOrgAssignment added in v1.22.0

func HandleOrgAssignment(ctx *Context, args ...bool)

HandleOrgAssignment handles organization assignment

func OrgAssignment added in v1.22.0

func OrgAssignment(args ...bool) func(ctx *Context)

OrgAssignment returns a middleware to handle organization assignment

func OverrideContext added in v1.22.0

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 added in v1.22.0

func PackageAssignment() func(ctx *Context)

PackageAssignment returns a middleware to handle Context.Package assignment

func PackageAssignmentAPI added in v1.22.0

func PackageAssignmentAPI() func(ctx *APIContext)

PackageAssignmentAPI returns a middleware to handle Context.Package assignment

func PackageContexter added in v1.22.0

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

PackageContexter initializes a package context for a request.

func ParseCsrfToken added in v1.22.0

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

func PrivateContexter added in v1.22.0

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

PrivateContexter returns apicontext as middleware

func RedirectToRepo added in v1.22.0

func RedirectToRepo(ctx *Base, redirectRepoID int64)

RedirectToRepo redirect to a differently-named repository

func RedirectToUser added in v1.22.0

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

RedirectToUser redirect to a differently-named user

func ReferencesGitRepo added in v1.22.0

func ReferencesGitRepo(allowEmpty ...bool) func(ctx *APIContext) (cancel context.CancelFunc)

ReferencesGitRepo injects the GitRepo into the Context you can optional skip the IsEmpty check

func RepoAssignment added in v1.22.0

func RepoAssignment(ctx *Context) context.CancelFunc

RepoAssignment returns a middleware to handle repository assignment

func RepoMustNotBeArchived added in v1.22.0

func RepoMustNotBeArchived() func(ctx *Context)

RepoMustNotBeArchived checks if a repo is archived

func RepoRef added in v1.22.0

func RepoRef() func(*Context) context.CancelFunc

RepoRef handles repository reference names when the ref name is not explicitly given

func RepoRefByType added in v1.22.0

func RepoRefByType(detectRefType RepoRefType, opts ...RepoRefByTypeOptions) func(*Context) context.CancelFunc

RepoRefByType handles repository reference name for a specific type of repository reference

func RepoRefForAPI added in v1.22.0

func RepoRefForAPI(next http.Handler) http.Handler

RepoRefForAPI handles repository reference names when the ref name is not explicitly given

func RequireRepoAdmin added in v1.22.0

func RequireRepoAdmin() func(ctx *Context)

RequireRepoAdmin returns a middleware for requiring repository admin permission

func RequireRepoReader added in v1.22.0

func RequireRepoReader(unitType unit.Type) func(ctx *Context)

RequireRepoReader returns a middleware for requiring repository read to the specify unitType

func RequireRepoReaderOr added in v1.22.0

func RequireRepoReaderOr(unitTypes ...unit.Type) func(ctx *Context)

RequireRepoReaderOr returns a middleware for requiring repository write to one of the unit permission

func RequireRepoWriter added in v1.22.0

func RequireRepoWriter(unitType unit.Type) func(ctx *Context)

RequireRepoWriter returns a middleware for requiring repository write to the specify unitType

func RequireRepoWriterOr added in v1.22.0

func RequireRepoWriterOr(unitTypes ...unit.Type) func(ctx *Context)

RequireRepoWriterOr returns a middleware for requiring repository write to one of the unit permission

func RetrieveBaseRepo added in v1.22.0

func RetrieveBaseRepo(ctx *Context, repo *repo_model.Repository)

RetrieveBaseRepo retrieves base repository

func RetrieveTemplateRepo added in v1.22.0

func RetrieveTemplateRepo(ctx *Context, repo *repo_model.Repository)

RetrieveTemplateRepo retrieves template repository used to generate this repository

func SetCaptchaData added in v1.22.0

func SetCaptchaData(ctx *Context)

SetCaptchaData sets common captcha data

func UserAssignmentAPI

func UserAssignmentAPI() func(ctx *APIContext)

UserAssignmentAPI returns a middleware to handle context-user assignment for api routes

func UserAssignmentWeb

func UserAssignmentWeb() func(ctx *Context)

UserAssignmentWeb returns a middleware to handle context-user assignment for web routes

func UserIDAssignmentAPI added in v1.19.1

func UserIDAssignmentAPI() func(ctx *APIContext)

UserIDAssignmentAPI returns a middleware to handle context-user assignment for api routes

func ValidCsrfToken added in v1.22.0

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 added in v1.22.0

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

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

Types

type APIConflict added in v1.22.0

type APIConflict struct{}

APIConflict is a conflict empty response swagger:response conflict

type APIContext added in v1.22.0

type APIContext struct {
	*Base

	Cache cache.StringCache

	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
	PublicOnly bool // Whether the request is for a public endpoint
}

APIContext is a specific context for API service

func GetAPIContext added in v1.22.0

func GetAPIContext(req *http.Request) *APIContext

GetAPIContext returns a context for API routes

func (*APIContext) Error added in v1.22.0

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 added in v1.22.0

func (ctx *APIContext) GetErrMsg() string

GetErrMsg returns error message in form validation.

func (*APIContext) HasAPIError added in v1.22.0

func (ctx *APIContext) HasAPIError() bool

HasAPIError returns true if error occurs in form validation.

func (*APIContext) InternalServerError added in v1.22.0

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) IsUserRepoAdmin added in v1.22.0

func (ctx *APIContext) IsUserRepoAdmin() bool

IsUserRepoAdmin returns true if current user is admin in current repo

func (*APIContext) IsUserRepoWriter added in v1.22.0

func (ctx *APIContext) IsUserRepoWriter(unitTypes []unit.Type) bool

IsUserRepoWriter returns true if current user has write privilege in current repo

func (*APIContext) IsUserSiteAdmin added in v1.22.0

func (ctx *APIContext) IsUserSiteAdmin() bool

IsUserSiteAdmin returns true if current user is a site admin

func (*APIContext) NotFound added in v1.22.0

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 added in v1.22.0

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 added in v1.22.0

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

ServerError responds with error message, status is 500

func (*APIContext) SetLinkHeader added in v1.22.0

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

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

type APIEmpty added in v1.22.0

type APIEmpty struct{}

APIEmpty is an empty response swagger:response empty

type APIError added in v1.22.0

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

APIError is error format response swagger:response error

type APIForbiddenError added in v1.22.0

type APIForbiddenError struct {
	APIError
}

APIForbiddenError is a forbidden error response swagger:response forbidden

type APIInvalidTopicsError added in v1.22.0

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

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

type APINotFound added in v1.22.0

type APINotFound struct{}

APINotFound is a not found empty response swagger:response notFound

type APIOrganization added in v1.22.0

type APIOrganization struct {
	Organization *organization.Organization
	Team         *organization.Team
}

APIOrganization contains organization and team

type APIRedirect added in v1.22.0

type APIRedirect struct{}

APIRedirect is a redirect response swagger:response redirect

type APIRepoArchivedError added in v1.22.0

type APIRepoArchivedError struct {
	APIError
}

APIRepoArchivedError is an error that is raised when an archived repo should be modified swagger:response repoArchivedError

type APIString added in v1.22.0

type APIString string

APIString is a string response swagger:response string

type APIValidationError added in v1.22.0

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 added in v1.22.0

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 added in v1.22.0

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

func (*Base) AppendAccessControlExposeHeaders added in v1.22.0

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

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

func (*Base) AppendContextValue added in v1.22.0

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

func (*Base) AppendContextValueFunc added in v1.22.0

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

func (*Base) Deadline added in v1.22.0

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

func (*Base) Done added in v1.22.0

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

func (*Base) Err added in v1.22.0

func (b *Base) Err() error

func (*Base) Error added in v1.22.0

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

Error returned an error to web browser

func (*Base) FormBool added in v1.22.0

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 added in v1.22.0

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 added in v1.22.0

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 added in v1.22.0

func (b *Base) FormOptionalBool(key string) optional.Option[bool]

FormOptionalBool returns an optional.Some(true) or optional.Some(false) if the value for the provided key exists in the form else it returns optional.None[bool]()

func (*Base) FormString added in v1.22.0

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 added in v1.22.0

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

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

func (*Base) FormTrim added in v1.22.0

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 added in v1.22.0

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

func (*Base) JSON added in v1.22.0

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

JSON render content as JSON

func (*Base) PathParam

func (b *Base) PathParam(name string) string

PathParam returns the param in request path, eg: "/{var}" => "/a%2fb", then `var == "a/b"`

func (*Base) PathParamInt64

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

PathParamInt64 returns the param in request path as int64

func (*Base) PathParamRaw added in v1.22.0

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

PathParamRaw returns the raw param in request path, eg: "/{var}" => "/a%2fb", then `var == "a%2fb"`

func (*Base) PlainText added in v1.22.0

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

PlainText renders content as plain text

func (*Base) PlainTextBytes added in v1.22.0

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

PlainTextBytes renders bytes as plain text

func (*Base) Redirect added in v1.22.0

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

Redirect redirects the request

func (*Base) RemoteAddr added in v1.22.0

func (b *Base) RemoteAddr() string

RemoteAddr returns the client machine ip address

func (*Base) RespHeader added in v1.22.0

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

RespHeader returns the response header

func (*Base) ServeContent added in v1.22.0

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

ServeContent serves content to http request

func (*Base) SetFormString added in v1.22.0

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

func (*Base) SetPathParam

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

SetPathParam set request path params into routes

func (*Base) SetServeHeaders added in v1.22.0

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

func (*Base) SetTotalCountHeader added in v1.22.0

func (b *Base) SetTotalCountHeader(total int64)

SetTotalCountHeader set "X-Total-Count" header

func (*Base) Status added in v1.22.0

func (b *Base) Status(status int)

Status writes status code

func (*Base) Tr added in v1.22.0

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

func (*Base) TrN added in v1.22.0

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

func (*Base) Value added in v1.22.0

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

func (*Base) Write added in v1.22.0

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

Write writes data to web browser

func (*Base) Written added in v1.22.0

func (b *Base) Written() bool

Written returns true if there are something sent to web browser

func (*Base) WrittenStatus added in v1.22.0

func (b *Base) WrittenStatus() int

type BaseContextKeyType

type BaseContextKeyType struct{}
var BaseContextKey BaseContextKeyType

type CSRFProtector added in v1.22.0

type CSRFProtector interface {
	// PrepareForSessionUser prepares the csrf protector for the current session user.
	PrepareForSessionUser(ctx *Context)
	// Validate validates the csrf token in http context.
	Validate(ctx *Context)
	// DeleteCookie deletes the csrf cookie
	DeleteCookie(ctx *Context)
}

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

func NewCSRFProtector added in v1.22.3

func NewCSRFProtector(opt CsrfOptions) CSRFProtector

type CanCommitToBranchResults added in v1.22.0

type CanCommitToBranchResults struct {
	CanCommitToBranch bool
	EditorEnabled     bool
	UserCanPush       bool
	RequireSigned     bool
	WillSign          bool
	SigningKey        string
	WontSignReason    string
}

CanCommitToBranchResults represents the results of CanCommitToBranch

type Context added in v1.22.0

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.StringCache
	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
}

Context represents context of a request.

func GetWebContext added in v1.22.0

func GetWebContext(req *http.Request) *Context

func NewWebContext added in v1.22.0

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

func (*Context) DeleteSiteCookie added in v1.22.0

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 added in v1.22.0

func (ctx *Context) GetErrMsg() string

GetErrMsg returns error message in form validation.

func (*Context) GetSiteCookie added in v1.22.0

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

GetSiteCookie returns given cookie value from request header.

func (*Context) HTML added in v1.22.0

func (ctx *Context) HTML(status int, name base.TplName)

HTML calls Context.HTML and renders the template to HTTP response

func (*Context) HasError added in v1.22.0

func (ctx *Context) HasError() bool

HasError returns true if error occurs in form validation. Attention: this function changes ctx.Data and ctx.Flash If HasError is called, then before Redirect, the error message should be stored by ctx.Flash.Error(ctx.GetErrMsg()) again.

func (*Context) IsUserRepoAdmin added in v1.22.0

func (ctx *Context) IsUserRepoAdmin() bool

IsUserRepoAdmin returns true if current user is admin in current repo

func (*Context) IsUserRepoWriter added in v1.22.0

func (ctx *Context) IsUserRepoWriter(unitTypes []unit.Type) bool

IsUserRepoWriter returns true if current user has write privilege in current repo

func (*Context) IsUserSiteAdmin added in v1.22.0

func (ctx *Context) IsUserSiteAdmin() bool

IsUserSiteAdmin returns true if current user is a site admin

func (*Context) JSONError added in v1.22.0

func (ctx *Context) JSONError(msg any)

func (*Context) JSONOK added in v1.22.0

func (ctx *Context) JSONOK()

func (*Context) JSONRedirect added in v1.22.0

func (ctx *Context) JSONRedirect(redirect string)

func (*Context) JSONTemplate added in v1.22.0

func (ctx *Context) JSONTemplate(tmpl base.TplName)

JSONTemplate renders the template as JSON response keep in mind that the template is processed in HTML context, so JSON-things should be handled carefully, eg: by JSEscape

func (*Context) NotFound added in v1.22.0

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 added in v1.22.0

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) RedirectToCurrentSite added in v1.22.0

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

RedirectToCurrentSite redirects to first not empty URL which belongs to current site

func (*Context) RenderToHTML added in v1.22.0

func (ctx *Context) RenderToHTML(name base.TplName, data map[string]any) (template.HTML, error)

RenderToHTML renders the template content to a HTML string

func (*Context) RenderWithErr added in v1.22.0

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

RenderWithErr used for page has form validation but need to prompt error to users.

func (*Context) ServerError added in v1.22.0

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 added in v1.22.0

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) UploadStream added in v1.22.0

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 added in v1.22.0

type CsrfOptions struct {
	// The global secret value used to generate Tokens.
	Secret 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
	// Set the Secure flag to true on the cookie.
	Secure bool
	// contains filtered or unexported fields
}

CsrfOptions maintains options to manage behavior of Generate.

type Organization added in v1.22.0

type Organization struct {
	IsOwner          bool
	IsMember         bool
	IsTeamMember     bool // Is member of team.
	IsTeamAdmin      bool // In owner team or team that has admin permission level.
	Organization     *organization.Organization
	OrgLink          string
	CanCreateOrgRepo bool

	Team  *organization.Team
	Teams []*organization.Team
}

Organization contains organization context

func (*Organization) CanReadUnit added in v1.22.0

func (org *Organization) CanReadUnit(ctx *Context, unitType unit.Type) bool

func (*Organization) CanWriteUnit added in v1.22.0

func (org *Organization) CanWriteUnit(ctx *Context, unitType unit.Type) bool

type Package added in v1.22.0

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 added in v1.22.0

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 added in v1.22.0

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) AddParamFromRequest

func (p *Pagination) AddParamFromRequest(req *http.Request)

func (*Pagination) AddParamString added in v1.22.0

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

AddParamString adds a string parameter directly

func (*Pagination) GetParams added in v1.22.0

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

GetParams returns the configured URL params

func (*Pagination) SetDefaultParams added in v1.22.0

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

SetDefaultParams sets common pagination params that are often used

type PrivateContext added in v1.22.0

type PrivateContext struct {
	*Base
	Override context.Context

	Repo *Repository
}

PrivateContext represents a context for private routes

func GetPrivateContext added in v1.22.0

func GetPrivateContext(req *http.Request) *PrivateContext

GetPrivateContext returns a context for Private routes

func (*PrivateContext) Deadline added in v1.22.0

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 added in v1.22.0

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 added in v1.22.0

func (ctx *PrivateContext) Err() error

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

type PullRequest added in v1.22.0

type PullRequest struct {
	BaseRepo *repo_model.Repository
	Allowed  bool // it only used by the web tmpl: "PullRequestCtx.Allowed"
	SameRepo bool // it only used by the web tmpl: "PullRequestCtx.SameRepo"
}

PullRequest contains information to make a pull request

type Render added in v1.22.0

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
}

Render represents a template render

type RepoRefByTypeOptions

type RepoRefByTypeOptions struct {
	IgnoreNotExistErr bool
}

type RepoRefType added in v1.22.0

type RepoRefType int

RepoRefType type of repo reference

const (
	// RepoRefUnknown is for legacy support, makes the code to "guess" the ref type
	RepoRefUnknown RepoRefType = iota
	RepoRefBranch
	RepoRefTag
	RepoRefCommit
	RepoRefBlob
)

type Repository added in v1.22.0

type Repository struct {
	access_model.Permission
	IsWatching   bool
	IsViewBranch bool
	IsViewTag    bool
	IsViewCommit bool
	Repository   *repo_model.Repository
	Owner        *user_model.User
	Commit       *git.Commit
	Tag          *git.Tag
	GitRepo      *git.Repository
	RefName      string
	BranchName   string
	TagName      string
	TreePath     string
	CommitID     string
	RepoLink     string
	CloneLink    repo_model.CloneLink
	CommitsCount int64

	PullRequest *PullRequest
}

Repository contains information to operate a repository

func (*Repository) BranchNameSubURL added in v1.22.0

func (r *Repository) BranchNameSubURL() string

BranchNameSubURL sub-URL for the BranchName field

func (*Repository) CanCommitToBranch added in v1.22.0

func (r *Repository) CanCommitToBranch(ctx context.Context, doer *user_model.User) (CanCommitToBranchResults, error)

CanCommitToBranch returns true if repository is editable and user has proper access level

and branch is not protected for push

func (*Repository) CanCreateBranch added in v1.22.0

func (r *Repository) CanCreateBranch() bool

CanCreateBranch returns true if repository is editable and user has proper access level.

func (*Repository) CanCreateIssueDependencies added in v1.22.0

func (r *Repository) CanCreateIssueDependencies(ctx context.Context, user *user_model.User, isPull bool) bool

CanCreateIssueDependencies returns whether or not a user can create dependencies.

func (*Repository) CanEnableEditor added in v1.22.0

func (r *Repository) CanEnableEditor(ctx context.Context, user *user_model.User) bool

CanEnableEditor returns true if repository is editable and user has proper access level.

func (*Repository) CanUseTimetracker added in v1.22.0

func (r *Repository) CanUseTimetracker(ctx context.Context, issue *issues_model.Issue, user *user_model.User) bool

CanUseTimetracker returns whether or not a user can use the timetracker.

func (*Repository) CanWriteToBranch added in v1.22.0

func (r *Repository) CanWriteToBranch(ctx context.Context, user *user_model.User, branch string) bool

CanWriteToBranch checks if the branch is writable by the user

func (*Repository) FileExists added in v1.22.0

func (r *Repository) FileExists(path, branch string) (bool, error)

FileExists returns true if a file exists in the given repo branch

func (*Repository) GetCommitGraphsCount added in v1.22.0

func (r *Repository) GetCommitGraphsCount(ctx context.Context, hidePRRefs bool, branches, files []string) (int64, error)

GetCommitGraphsCount returns cached commit count for current view

func (*Repository) GetCommitsCount added in v1.22.0

func (r *Repository) GetCommitsCount() (int64, error)

GetCommitsCount returns cached commit count for current view

func (*Repository) GetEditorconfig added in v1.22.0

func (r *Repository) GetEditorconfig(optCommit ...*git.Commit) (cfg *editorconfig.Editorconfig, warning, err error)

GetEditorconfig returns the .editorconfig definition if found in the HEAD of the default repo branch.

func (*Repository) GetObjectFormat added in v1.22.0

func (r *Repository) GetObjectFormat() git.ObjectFormat

type Response added in v1.22.0

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

Response represents a response

func WrapResponseWriter added in v1.22.0

func WrapResponseWriter(resp http.ResponseWriter) *Response

func (*Response) Before added in v1.22.0

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 added in v1.22.0

func (r *Response) Flush()

Flush flushes cached data

func (*Response) Size added in v1.22.0

func (r *Response) Size() int

func (*Response) Status added in v1.22.0

func (r *Response) Status() int

func (*Response) Write added in v1.22.0

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

Write writes bytes to HTTP endpoint

func (*Response) WriteHeader added in v1.22.0

func (r *Response) WriteHeader(statusCode int)

WriteHeader write status code

func (*Response) WrittenStatus added in v1.22.0

func (r *Response) WrittenStatus() int

WrittenStatus returned status code written

type ResponseWriter added in v1.22.0

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 added in v1.22.0

type ServeHeaderOptions httplib.ServeHeaderOptions

type TemplateContext added in v1.22.0

type TemplateContext map[string]any

func NewTemplateContext added in v1.22.0

func NewTemplateContext(ctx context.Context) TemplateContext

func NewTemplateContextForWeb added in v1.22.0

func NewTemplateContextForWeb(ctx *Context) TemplateContext

func (TemplateContext) Deadline added in v1.22.0

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

func (TemplateContext) Done added in v1.22.0

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

func (TemplateContext) Err added in v1.22.0

func (c TemplateContext) Err() error

func (TemplateContext) Value added in v1.22.0

func (c TemplateContext) Value(key any) any

type ValidateContext added in v1.22.0

type ValidateContext struct {
	*Base
}

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

func GetValidateContext added in v1.22.0

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

GetValidateContext gets a context for middleware form validation

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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