routes/api/v1: codemod

This commit is contained in:
unknwon 2019-08-08 23:53:43 -07:00
parent 04de977855
commit c7ba519af2
No known key found for this signature in database
GPG Key ID: 25B575AE3213B2B3
16 changed files with 234 additions and 250 deletions

View File

@ -199,7 +199,7 @@ func runServ(c *cli.Context) error {
fail("Internal error", "Fail to get user by key ID '%d': %v", key.ID, err) fail("Internal error", "Fail to get user by key ID '%d': %v", key.ID, err)
} }
mode, err := models.AccessLevel(user.ID, repo) mode, err := models.UserAccessMode(user.ID, repo)
if err != nil { if err != nil {
fail("Internal error", "Fail to check access: %v", err) fail("Internal error", "Fail to check access: %v", err)
} }

View File

@ -16,17 +16,17 @@ import (
"github.com/gogs/gogs/pkg/setting" "github.com/gogs/gogs/pkg/setting"
) )
const APP_VER = "0.11.90.0801" const Version = "0.11.91.0808"
func init() { func init() {
setting.AppVer = APP_VER setting.AppVer = Version
} }
func main() { func main() {
app := cli.NewApp() app := cli.NewApp()
app.Name = "Gogs" app.Name = "Gogs"
app.Usage = "A painless self-hosted Git service" app.Usage = "A painless self-hosted Git service"
app.Version = APP_VER app.Version = Version
app.Commands = []cli.Command{ app.Commands = []cli.Command{
cmd.Web, cmd.Web,
cmd.Serv, cmd.Serv,

View File

@ -59,7 +59,7 @@ type Access struct {
Mode AccessMode Mode AccessMode
} }
func accessLevel(e Engine, userID int64, repo *Repository) (AccessMode, error) { func userAccessMode(e Engine, userID int64, repo *Repository) (AccessMode, error) {
mode := ACCESS_MODE_NONE mode := ACCESS_MODE_NONE
// Everyone has read access to public repository // Everyone has read access to public repository
if !repo.IsPrivate { if !repo.IsPrivate {
@ -84,14 +84,13 @@ func accessLevel(e Engine, userID int64, repo *Repository) (AccessMode, error) {
return access.Mode, nil return access.Mode, nil
} }
// AccessLevel returns the Access a user has to a repository. Will return NoneAccess if the // UserAccessMode returns the access mode of given user to the repository.
// user does not have access. func UserAccessMode(userID int64, repo *Repository) (AccessMode, error) {
func AccessLevel(userID int64, repo *Repository) (AccessMode, error) { return userAccessMode(x, userID, repo)
return accessLevel(x, userID, repo)
} }
func hasAccess(e Engine, userID int64, repo *Repository, testMode AccessMode) (bool, error) { func hasAccess(e Engine, userID int64, repo *Repository, testMode AccessMode) (bool, error) {
mode, err := accessLevel(e, userID, repo) mode, err := userAccessMode(e, userID, repo)
return mode >= testMode, err return mode >= testMode, err
} }

View File

@ -3297,7 +3297,7 @@ func confGitignoreUnrealengine() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/gitignore/UnrealEngine", size: 948, mode: os.FileMode(420), modTime: time.Unix(1550387700, 0)} info := bindataFileInfo{name: "conf/gitignore/UnrealEngine", size: 948, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4437,7 +4437,7 @@ func confLocaleLocale_deDeIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_de-DE.ini", size: 70946, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_de-DE.ini", size: 70946, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4577,7 +4577,7 @@ func confLocaleLocale_glEsIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_gl-ES.ini", size: 69688, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_gl-ES.ini", size: 69688, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4597,7 +4597,7 @@ func confLocaleLocale_huHuIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_hu-HU.ini", size: 70953, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_hu-HU.ini", size: 70953, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4617,7 +4617,7 @@ func confLocaleLocale_idIdIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_id-ID.ini", size: 66136, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_id-ID.ini", size: 66136, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4637,7 +4637,7 @@ func confLocaleLocale_itItIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_it-IT.ini", size: 68517, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_it-IT.ini", size: 68517, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4657,7 +4657,7 @@ func confLocaleLocale_jaJpIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_ja-JP.ini", size: 80912, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_ja-JP.ini", size: 80912, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4677,7 +4677,7 @@ func confLocaleLocale_koKrIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_ko-KR.ini", size: 71072, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_ko-KR.ini", size: 71072, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4697,7 +4697,7 @@ func confLocaleLocale_lvLvIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_lv-LV.ini", size: 70985, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_lv-LV.ini", size: 70985, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4777,7 +4777,7 @@ func confLocaleLocale_ptPtIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_pt-PT.ini", size: 70206, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_pt-PT.ini", size: 70206, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4797,7 +4797,7 @@ func confLocaleLocale_ruRuIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_ru-RU.ini", size: 101120, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_ru-RU.ini", size: 101120, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4817,7 +4817,7 @@ func confLocaleLocale_skSkIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_sk-SK.ini", size: 70503, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_sk-SK.ini", size: 70503, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4837,7 +4837,7 @@ func confLocaleLocale_srSpIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_sr-SP.ini", size: 93140, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_sr-SP.ini", size: 93140, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }
@ -4877,7 +4877,7 @@ func confLocaleLocale_trTrIni() (*asset, error) {
return nil, err return nil, err
} }
info := bindataFileInfo{name: "conf/locale/locale_tr-TR.ini", size: 69699, mode: os.FileMode(420), modTime: time.Unix(1561638673, 0)} info := bindataFileInfo{name: "conf/locale/locale_tr-TR.ini", size: 69699, mode: os.FileMode(420), modTime: time.Unix(1564372605, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info}
return a, nil return a, nil
} }

View File

@ -25,8 +25,8 @@ type APIContext struct {
Org *APIOrganization Org *APIOrganization
} }
// FIXME: move to github.com/gogs/go-gogs-client // FIXME: move this constant to github.com/gogs/go-gogs-client
const DOC_URL = "https://github.com/gogs/docs-api" const DocURL = "https://github.com/gogs/docs-api"
// Error responses error message to client with given message. // Error responses error message to client with given message.
// If status is 500, also it prints error to log. // If status is 500, also it prints error to log.
@ -44,7 +44,7 @@ func (c *APIContext) Error(status int, title string, obj interface{}) {
c.JSON(status, map[string]string{ c.JSON(status, map[string]string{
"message": message, "message": message,
"url": DOC_URL, "url": DocURL,
}) })
} }

View File

@ -160,9 +160,9 @@ func RepoAssignment(pages ...bool) macaron.Handler {
if c.IsLogged && c.User.IsAdmin { if c.IsLogged && c.User.IsAdmin {
c.Repo.AccessMode = models.ACCESS_MODE_OWNER c.Repo.AccessMode = models.ACCESS_MODE_OWNER
} else { } else {
mode, err := models.AccessLevel(c.UserID(), repo) mode, err := models.UserAccessMode(c.UserID(), repo)
if err != nil { if err != nil {
c.ServerError("AccessLevel", err) c.ServerError("UserAccessMode", err)
return return
} }
c.Repo.AccessMode = mode c.Repo.AccessMode = mode

View File

@ -24,21 +24,21 @@ import (
"github.com/gogs/gogs/routes/api/v1/user" "github.com/gogs/gogs/routes/api/v1/user"
) )
// repoAssignment extracts information from URL parameters to retrieve the repository,
// and makes sure the context user has at least the read access to the repository.
func repoAssignment() macaron.Handler { func repoAssignment() macaron.Handler {
return func(c *context.APIContext) { return func(c *context.APIContext) {
userName := c.Params(":username") username := c.Params(":username")
repoName := c.Params(":reponame") reponame := c.Params(":reponame")
var ( var err error
owner *models.User var owner *models.User
err error
)
// Check if the user is the same as the repository owner. // Check if the context user is the repository owner.
if c.IsLogged && c.User.LowerName == strings.ToLower(userName) { if c.IsLogged && c.User.LowerName == strings.ToLower(username) {
owner = c.User owner = c.User
} else { } else {
owner, err = models.GetUserByName(userName) owner, err = models.GetUserByName(username)
if err != nil { if err != nil {
c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return return
@ -46,11 +46,11 @@ func repoAssignment() macaron.Handler {
} }
c.Repo.Owner = owner c.Repo.Owner = owner
repo, err := models.GetRepositoryByName(owner.ID, repoName) r, err := models.GetRepositoryByName(owner.ID, reponame)
if err != nil { if err != nil {
c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err) c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
return return
} else if err = repo.GetOwner(); err != nil { } else if err = r.GetOwner(); err != nil {
c.ServerError("GetOwner", err) c.ServerError("GetOwner", err)
return return
} }
@ -58,9 +58,9 @@ func repoAssignment() macaron.Handler {
if c.IsTokenAuth && c.User.IsAdmin { if c.IsTokenAuth && c.User.IsAdmin {
c.Repo.AccessMode = models.ACCESS_MODE_OWNER c.Repo.AccessMode = models.ACCESS_MODE_OWNER
} else { } else {
mode, err := models.AccessLevel(c.UserID(), repo) mode, err := models.UserAccessMode(c.UserID(), r)
if err != nil { if err != nil {
c.ServerError("AccessLevel", err) c.ServerError("UserAccessMode", err)
return return
} }
c.Repo.AccessMode = mode c.Repo.AccessMode = mode
@ -71,56 +71,11 @@ func repoAssignment() macaron.Handler {
return return
} }
c.Repo.Repository = repo c.Repo.Repository = r
}
}
// Contexter middleware already checks token for user sign in process.
func reqToken() macaron.Handler {
return func(c *context.Context) {
if !c.IsTokenAuth {
c.Error(http.StatusUnauthorized)
return
}
}
}
func reqBasicAuth() macaron.Handler {
return func(c *context.Context) {
if !c.IsBasicAuth {
c.Error(http.StatusUnauthorized)
return
}
}
}
func reqAdmin() macaron.Handler {
return func(c *context.Context) {
if !c.IsLogged || !c.User.IsAdmin {
c.Error(http.StatusForbidden)
return
}
}
}
func reqRepoWriter() macaron.Handler {
return func(c *context.Context) {
if !c.Repo.IsWriter() {
c.Error(http.StatusForbidden)
return
}
}
}
func reqRepoAdmin() macaron.Handler {
return func(c *context.Context) {
if !c.Repo.IsAdmin() {
c.Error(http.StatusForbidden)
return
}
} }
} }
// orgAssignment extracts information from URL parameters to retrieve the organization or team.
func orgAssignment(args ...bool) macaron.Handler { func orgAssignment(args ...bool) macaron.Handler {
var ( var (
assignOrg bool assignOrg bool
@ -154,6 +109,56 @@ func orgAssignment(args ...bool) macaron.Handler {
} }
} }
// reqToken makes sure the context user is authorized via access token.
func reqToken() macaron.Handler {
return func(c *context.Context) {
if !c.IsTokenAuth {
c.Error(http.StatusUnauthorized)
return
}
}
}
// reqBasicAuth makes sure the context user is authorized via HTTP Basic Auth.
func reqBasicAuth() macaron.Handler {
return func(c *context.Context) {
if !c.IsBasicAuth {
c.Error(http.StatusUnauthorized)
return
}
}
}
// reqAdmin makes sure the context user is a site admin.
func reqAdmin() macaron.Handler {
return func(c *context.Context) {
if !c.IsLogged || !c.User.IsAdmin {
c.Error(http.StatusForbidden)
return
}
}
}
// reqRepoWriter makes sure the context user has at least write access to the repository.
func reqRepoWriter() macaron.Handler {
return func(c *context.Context) {
if !c.Repo.IsWriter() {
c.Error(http.StatusForbidden)
return
}
}
}
// reqRepoWriter makes sure the context user has at least admin access to the repository.
func reqRepoAdmin() macaron.Handler {
return func(c *context.Context) {
if !c.Repo.IsAdmin() {
c.Error(http.StatusForbidden)
return
}
}
}
func mustEnableIssues(c *context.APIContext) { func mustEnableIssues(c *context.APIContext) {
if !c.Repo.Repository.EnableIssues || c.Repo.Repository.EnableExternalTracker { if !c.Repo.Repository.EnableIssues || c.Repo.Repository.EnableExternalTracker {
c.NotFound() c.NotFound()
@ -161,7 +166,7 @@ func mustEnableIssues(c *context.APIContext) {
} }
} }
// RegisterRoutes registers all v1 APIs routes to web application. // RegisterRoutes registers all routes in API v1 to the web application.
// FIXME: custom form error response // FIXME: custom form error response
func RegisterRoutes(m *macaron.Macaron) { func RegisterRoutes(m *macaron.Macaron) {
bind := binding.Bind bind := binding.Bind
@ -182,7 +187,8 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Get("", user.GetInfo) m.Get("", user.GetInfo)
m.Group("/tokens", func() { m.Group("/tokens", func() {
m.Combo("").Get(user.ListAccessTokens). m.Combo("").
Get(user.ListAccessTokens).
Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken) Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken)
}, reqBasicAuth()) }, reqBasicAuth())
}) })
@ -202,7 +208,8 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Group("/user", func() { m.Group("/user", func() {
m.Get("", user.GetAuthenticatedUser) m.Get("", user.GetAuthenticatedUser)
m.Combo("/emails").Get(user.ListEmails). m.Combo("/emails").
Get(user.ListEmails).
Post(bind(api.CreateEmailOption{}), user.AddEmail). Post(bind(api.CreateEmailOption{}), user.AddEmail).
Delete(bind(api.CreateEmailOption{}), user.DeleteEmail) Delete(bind(api.CreateEmailOption{}), user.DeleteEmail)
@ -213,9 +220,11 @@ func RegisterRoutes(m *macaron.Macaron) {
}) })
m.Group("/keys", func() { m.Group("/keys", func() {
m.Combo("").Get(user.ListMyPublicKeys). m.Combo("").
Get(user.ListMyPublicKeys).
Post(bind(api.CreateKeyOption{}), user.CreatePublicKey) Post(bind(api.CreateKeyOption{}), user.CreatePublicKey)
m.Combo("/:id").Get(user.GetPublicKey). m.Combo("/:id").
Get(user.GetPublicKey).
Delete(user.DeletePublicKey) Delete(user.DeletePublicKey)
}) })
@ -225,7 +234,8 @@ func RegisterRoutes(m *macaron.Macaron) {
// Repositories // Repositories
m.Get("/users/:username/repos", reqToken(), repo.ListUserRepositories) m.Get("/users/:username/repos", reqToken(), repo.ListUserRepositories)
m.Get("/orgs/:org/repos", reqToken(), repo.ListOrgRepositories) m.Get("/orgs/:org/repos", reqToken(), repo.ListOrgRepositories)
m.Combo("/user/repos", reqToken()).Get(repo.ListMyRepos). m.Combo("/user/repos", reqToken()).
Get(repo.ListMyRepos).
Post(bind(api.CreateRepoOption{}), repo.Create) Post(bind(api.CreateRepoOption{}), repo.Create)
m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo)
@ -241,16 +251,22 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Group("/:username/:reponame", func() { m.Group("/:username/:reponame", func() {
m.Group("/hooks", func() { m.Group("/hooks", func() {
m.Combo("").Get(repo.ListHooks). m.Combo("").
Get(repo.ListHooks).
Post(bind(api.CreateHookOption{}), repo.CreateHook) Post(bind(api.CreateHookOption{}), repo.CreateHook)
m.Combo("/:id").Patch(bind(api.EditHookOption{}), repo.EditHook). m.Combo("/:id").
Patch(bind(api.EditHookOption{}), repo.EditHook).
Delete(repo.DeleteHook) Delete(repo.DeleteHook)
}, reqRepoAdmin()) }, reqRepoAdmin())
m.Group("/collaborators", func() { m.Group("/collaborators", func() {
m.Get("", repo.ListCollaborators) m.Get("", repo.ListCollaborators)
m.Combo("/:collaborator").Get(repo.IsCollaborator).Put(bind(api.AddCollaboratorOption{}), repo.AddCollaborator). m.Combo("/:collaborator").
Get(repo.IsCollaborator).
Put(bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
Delete(repo.DeleteCollaborator) Delete(repo.DeleteCollaborator)
}, reqRepoAdmin()) }, reqRepoAdmin())
m.Get("/raw/*", context.RepoRef(), repo.GetRawFile) m.Get("/raw/*", context.RepoRef(), repo.GetRawFile)
m.Get("/archive/*", repo.GetArchive) m.Get("/archive/*", repo.GetArchive)
m.Get("/forks", repo.ListForks) m.Get("/forks", repo.ListForks)
@ -258,20 +274,24 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Get("", repo.ListBranches) m.Get("", repo.ListBranches)
m.Get("/*", repo.GetBranch) m.Get("/*", repo.GetBranch)
}) })
m.Group("/commits", func() { m.Group("/commits", func() {
m.Get("/:sha", repo.GetSingleCommit) m.Get("/:sha", repo.GetSingleCommit)
m.Get("/*", repo.GetReferenceSHA) m.Get("/*", repo.GetReferenceSHA)
}) })
m.Group("/keys", func() { m.Group("/keys", func() {
m.Combo("").Get(repo.ListDeployKeys). m.Combo("").
Get(repo.ListDeployKeys).
Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey) Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey)
m.Combo("/:id").Get(repo.GetDeployKey). m.Combo("/:id").
Get(repo.GetDeployKey).
Delete(repo.DeleteDeploykey) Delete(repo.DeleteDeploykey)
}, reqRepoAdmin()) }, reqRepoAdmin())
m.Group("/issues", func() { m.Group("/issues", func() {
m.Combo("").Get(repo.ListIssues).Post(bind(api.CreateIssueOption{}), repo.CreateIssue) m.Combo("").
Get(repo.ListIssues).
Post(bind(api.CreateIssueOption{}), repo.CreateIssue)
m.Group("/comments", func() { m.Group("/comments", func() {
m.Get("", repo.ListRepoIssueComments) m.Get("", repo.ListRepoIssueComments)
m.Combo("/:id").Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueComment) m.Combo("/:id").Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueComment)

View File

@ -5,16 +5,17 @@
package misc package misc
import ( import (
"net/http"
api "github.com/gogs/go-gogs-client" api "github.com/gogs/go-gogs-client"
"github.com/gogs/gogs/pkg/context" "github.com/gogs/gogs/pkg/context"
"github.com/gogs/gogs/pkg/markup" "github.com/gogs/gogs/pkg/markup"
) )
// https://github.com/gogs/go-gogs-client/wiki/Miscellaneous#render-an-arbitrary-markdown-document
func Markdown(c *context.APIContext, form api.MarkdownOption) { func Markdown(c *context.APIContext, form api.MarkdownOption) {
if c.HasApiError() { if c.HasApiError() {
c.Error(422, "", c.GetErrMsg()) c.Error(http.StatusUnprocessableEntity, "", c.GetErrMsg())
return return
} }
@ -31,11 +32,10 @@ func Markdown(c *context.APIContext, form api.MarkdownOption) {
} }
} }
// https://github.com/gogs/go-gogs-client/wiki/Miscellaneous#render-a-markdown-document-in-raw-mode
func MarkdownRaw(c *context.APIContext) { func MarkdownRaw(c *context.APIContext) {
body, err := c.Req.Body().Bytes() body, err := c.Req.Body().Bytes()
if err != nil { if err != nil {
c.Error(422, "", err) c.Error(http.StatusUnprocessableEntity, "", err)
return return
} }
c.Write(markup.RawMarkdown(body, "")) c.Write(markup.RawMarkdown(body, ""))

View File

@ -6,6 +6,7 @@ package repo
import ( import (
"fmt" "fmt"
"net/http"
"strings" "strings"
api "github.com/gogs/go-gogs-client" api "github.com/gogs/go-gogs-client"
@ -19,13 +20,13 @@ import (
func listIssues(c *context.APIContext, opts *models.IssuesOptions) { func listIssues(c *context.APIContext, opts *models.IssuesOptions) {
issues, err := models.Issues(opts) issues, err := models.Issues(opts)
if err != nil { if err != nil {
c.Error(500, "Issues", err) c.ServerError("Issues", err)
return return
} }
count, err := models.IssuesCount(opts) count, err := models.IssuesCount(opts)
if err != nil { if err != nil {
c.Error(500, "IssuesCount", err) c.ServerError("IssuesCount", err)
return return
} }
@ -33,14 +34,14 @@ func listIssues(c *context.APIContext, opts *models.IssuesOptions) {
apiIssues := make([]*api.Issue, len(issues)) apiIssues := make([]*api.Issue, len(issues))
for i := range issues { for i := range issues {
if err = issues[i].LoadAttributes(); err != nil { if err = issues[i].LoadAttributes(); err != nil {
c.Error(500, "LoadAttributes", err) c.ServerError("LoadAttributes", err)
return return
} }
apiIssues[i] = issues[i].APIFormat() apiIssues[i] = issues[i].APIFormat()
} }
c.SetLinkHeader(int(count), setting.UI.IssuePagingNum) c.SetLinkHeader(int(count), setting.UI.IssuePagingNum)
c.JSON(200, &apiIssues) c.JSONSuccess(&apiIssues)
} }
func ListUserIssues(c *context.APIContext) { func ListUserIssues(c *context.APIContext) {
@ -66,14 +67,10 @@ func ListIssues(c *context.APIContext) {
func GetIssue(c *context.APIContext) { func GetIssue(c *context.APIContext) {
issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index"))
if err != nil { if err != nil {
if errors.IsIssueNotExist(err) { c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
c.Status(404)
} else {
c.Error(500, "GetIssueByIndex", err)
}
return return
} }
c.JSON(200, issue.APIFormat()) c.JSONSuccess(issue.APIFormat())
} }
func CreateIssue(c *context.APIContext, form api.CreateIssueOption) { func CreateIssue(c *context.APIContext, form api.CreateIssueOption) {
@ -90,9 +87,9 @@ func CreateIssue(c *context.APIContext, form api.CreateIssueOption) {
assignee, err := models.GetUserByName(form.Assignee) assignee, err := models.GetUserByName(form.Assignee)
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
c.Error(422, "", fmt.Sprintf("Assignee does not exist: [name: %s]", form.Assignee)) c.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("assignee does not exist: [name: %s]", form.Assignee))
} else { } else {
c.Error(500, "GetUserByName", err) c.ServerError("GetUserByName", err)
} }
return return
} }
@ -104,13 +101,13 @@ func CreateIssue(c *context.APIContext, form api.CreateIssueOption) {
} }
if err := models.NewIssue(c.Repo.Repository, issue, form.Labels, nil); err != nil { if err := models.NewIssue(c.Repo.Repository, issue, form.Labels, nil); err != nil {
c.Error(500, "NewIssue", err) c.ServerError("NewIssue", err)
return return
} }
if form.Closed { if form.Closed {
if err := issue.ChangeStatus(c.User, c.Repo.Repository, true); err != nil { if err := issue.ChangeStatus(c.User, c.Repo.Repository, true); err != nil {
c.Error(500, "ChangeStatus", err) c.ServerError("ChangeStatus", err)
return return
} }
} }
@ -119,25 +116,21 @@ func CreateIssue(c *context.APIContext, form api.CreateIssueOption) {
var err error var err error
issue, err = models.GetIssueByID(issue.ID) issue, err = models.GetIssueByID(issue.ID)
if err != nil { if err != nil {
c.Error(500, "GetIssueByID", err) c.ServerError("GetIssueByID", err)
return return
} }
c.JSON(201, issue.APIFormat()) c.JSON(http.StatusCreated, issue.APIFormat())
} }
func EditIssue(c *context.APIContext, form api.EditIssueOption) { func EditIssue(c *context.APIContext, form api.EditIssueOption) {
issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index"))
if err != nil { if err != nil {
if errors.IsIssueNotExist(err) { c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
c.Status(404)
} else {
c.Error(500, "GetIssueByIndex", err)
}
return return
} }
if !issue.IsPoster(c.User.ID) && !c.Repo.IsWriter() { if !issue.IsPoster(c.User.ID) && !c.Repo.IsWriter() {
c.Status(403) c.Status(http.StatusForbidden)
return return
} }
@ -156,9 +149,9 @@ func EditIssue(c *context.APIContext, form api.EditIssueOption) {
assignee, err := models.GetUserByName(*form.Assignee) assignee, err := models.GetUserByName(*form.Assignee)
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
c.Error(422, "", fmt.Sprintf("assignee does not exist: [name: %s]", *form.Assignee)) c.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("assignee does not exist: [name: %s]", *form.Assignee))
} else { } else {
c.Error(500, "GetUserByName", err) c.ServerError("GetUserByName", err)
} }
return return
} }
@ -166,7 +159,7 @@ func EditIssue(c *context.APIContext, form api.EditIssueOption) {
} }
if err = models.UpdateIssueUserByAssignee(issue); err != nil { if err = models.UpdateIssueUserByAssignee(issue); err != nil {
c.Error(500, "UpdateIssueUserByAssignee", err) c.ServerError("UpdateIssueUserByAssignee", err)
return return
} }
} }
@ -175,18 +168,18 @@ func EditIssue(c *context.APIContext, form api.EditIssueOption) {
oldMilestoneID := issue.MilestoneID oldMilestoneID := issue.MilestoneID
issue.MilestoneID = *form.Milestone issue.MilestoneID = *form.Milestone
if err = models.ChangeMilestoneAssign(c.User, issue, oldMilestoneID); err != nil { if err = models.ChangeMilestoneAssign(c.User, issue, oldMilestoneID); err != nil {
c.Error(500, "ChangeMilestoneAssign", err) c.ServerError("ChangeMilestoneAssign", err)
return return
} }
} }
if err = models.UpdateIssue(issue); err != nil { if err = models.UpdateIssue(issue); err != nil {
c.Error(500, "UpdateIssue", err) c.ServerError("UpdateIssue", err)
return return
} }
if form.State != nil { if form.State != nil {
if err = issue.ChangeStatus(c.User, c.Repo.Repository, api.STATE_CLOSED == api.StateType(*form.State)); err != nil { if err = issue.ChangeStatus(c.User, c.Repo.Repository, api.STATE_CLOSED == api.StateType(*form.State)); err != nil {
c.Error(500, "ChangeStatus", err) c.ServerError("ChangeStatus", err)
return return
} }
} }
@ -194,8 +187,8 @@ func EditIssue(c *context.APIContext, form api.EditIssueOption) {
// Refetch from database to assign some automatic values // Refetch from database to assign some automatic values
issue, err = models.GetIssueByID(issue.ID) issue, err = models.GetIssueByID(issue.ID)
if err != nil { if err != nil {
c.Error(500, "GetIssueByID", err) c.ServerError("GetIssueByID", err)
return return
} }
c.JSON(201, issue.APIFormat()) c.JSON(http.StatusCreated, issue.APIFormat())
} }

View File

@ -5,6 +5,8 @@
package repo package repo
import ( import (
"fmt"
"net/http"
"path" "path"
log "gopkg.in/clog.v1" log "gopkg.in/clog.v1"
@ -19,7 +21,6 @@ import (
"github.com/gogs/gogs/routes/api/v1/convert" "github.com/gogs/gogs/routes/api/v1/convert"
) )
// https://github.com/gogs/go-gogs-client/wiki/Repositories#search-repositories
func Search(c *context.APIContext) { func Search(c *context.APIContext) {
opts := &models.SearchRepoOptions{ opts := &models.SearchRepoOptions{
Keyword: path.Base(c.Query("q")), Keyword: path.Base(c.Query("q")),
@ -35,7 +36,7 @@ func Search(c *context.APIContext) {
} else { } else {
u, err := models.GetUserByID(opts.OwnerID) u, err := models.GetUserByID(opts.OwnerID)
if err != nil { if err != nil {
c.JSON(500, map[string]interface{}{ c.JSON(http.StatusInternalServerError, map[string]interface{}{
"ok": false, "ok": false,
"error": err.Error(), "error": err.Error(),
}) })
@ -50,7 +51,7 @@ func Search(c *context.APIContext) {
repos, count, err := models.SearchRepositoryByName(opts) repos, count, err := models.SearchRepositoryByName(opts)
if err != nil { if err != nil {
c.JSON(500, map[string]interface{}{ c.JSON(http.StatusInternalServerError, map[string]interface{}{
"ok": false, "ok": false,
"error": err.Error(), "error": err.Error(),
}) })
@ -58,7 +59,7 @@ func Search(c *context.APIContext) {
} }
if err = models.RepositoryList(repos).LoadAttributes(); err != nil { if err = models.RepositoryList(repos).LoadAttributes(); err != nil {
c.JSON(500, map[string]interface{}{ c.JSON(http.StatusInternalServerError, map[string]interface{}{
"ok": false, "ok": false,
"error": err.Error(), "error": err.Error(),
}) })
@ -71,7 +72,7 @@ func Search(c *context.APIContext) {
} }
c.SetLinkHeader(int(count), opts.PageSize) c.SetLinkHeader(int(count), opts.PageSize)
c.JSON(200, map[string]interface{}{ c.JSONSuccess(map[string]interface{}{
"ok": true, "ok": true,
"data": results, "data": results,
}) })
@ -98,12 +99,12 @@ func listUserRepositories(c *context.APIContext, username string) {
}) })
} }
if err != nil { if err != nil {
c.Error(500, "GetUserRepositories", err) c.ServerError("GetUserRepositories", err)
return return
} }
if err = models.RepositoryList(ownRepos).LoadAttributes(); err != nil { if err = models.RepositoryList(ownRepos).LoadAttributes(); err != nil {
c.Error(500, "LoadAttributes(ownRepos)", err) c.ServerError("LoadAttributes(ownRepos)", err)
return return
} }
@ -113,13 +114,13 @@ func listUserRepositories(c *context.APIContext, username string) {
for i := range ownRepos { for i := range ownRepos {
repos[i] = ownRepos[i].APIFormat(&api.Permission{true, true, true}) repos[i] = ownRepos[i].APIFormat(&api.Permission{true, true, true})
} }
c.JSON(200, &repos) c.JSONSuccess(&repos)
return return
} }
accessibleRepos, err := user.GetRepositoryAccesses() accessibleRepos, err := user.GetRepositoryAccesses()
if err != nil { if err != nil {
c.Error(500, "GetRepositoryAccesses", err) c.ServerError("GetRepositoryAccesses", err)
return return
} }
@ -139,7 +140,7 @@ func listUserRepositories(c *context.APIContext, username string) {
i++ i++
} }
c.JSON(200, &repos) c.JSONSuccess(&repos)
} }
func ListMyRepos(c *context.APIContext) { func ListMyRepos(c *context.APIContext) {
@ -168,14 +169,14 @@ func CreateUserRepo(c *context.APIContext, owner *models.User, opt api.CreateRep
if models.IsErrRepoAlreadyExist(err) || if models.IsErrRepoAlreadyExist(err) ||
models.IsErrNameReserved(err) || models.IsErrNameReserved(err) ||
models.IsErrNamePatternNotAllowed(err) { models.IsErrNamePatternNotAllowed(err) {
c.Error(422, "", err) c.Error(http.StatusUnprocessableEntity, "", err)
} else { } else {
if repo != nil { if repo != nil {
if err = models.DeleteRepository(c.User.ID, repo.ID); err != nil { if err = models.DeleteRepository(c.User.ID, repo.ID); err != nil {
log.Error(2, "DeleteRepository: %v", err) log.Error(2, "DeleteRepository: %v", err)
} }
} }
c.Error(500, "CreateRepository", err) c.ServerError("CreateRepository", err)
} }
return return
} }
@ -183,11 +184,10 @@ func CreateUserRepo(c *context.APIContext, owner *models.User, opt api.CreateRep
c.JSON(201, repo.APIFormat(&api.Permission{true, true, true})) c.JSON(201, repo.APIFormat(&api.Permission{true, true, true}))
} }
// https://github.com/gogs/go-gogs-client/wiki/Repositories#create
func Create(c *context.APIContext, opt api.CreateRepoOption) { func Create(c *context.APIContext, opt api.CreateRepoOption) {
// Shouldn't reach this condition, but just in case. // Shouldn't reach this condition, but just in case.
if c.User.IsOrganization() { if c.User.IsOrganization() {
c.Error(422, "", "not allowed creating repository for organization") c.Error(http.StatusUnprocessableEntity, "", "not allowed creating repository for organization")
return return
} }
CreateUserRepo(c, c.User, opt) CreateUserRepo(c, c.User, opt)
@ -196,22 +196,17 @@ func Create(c *context.APIContext, opt api.CreateRepoOption) {
func CreateOrgRepo(c *context.APIContext, opt api.CreateRepoOption) { func CreateOrgRepo(c *context.APIContext, opt api.CreateRepoOption) {
org, err := models.GetOrgByName(c.Params(":org")) org, err := models.GetOrgByName(c.Params(":org"))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { c.NotFoundOrServerError("GetOrgByName", errors.IsUserNotExist, err)
c.Error(422, "", err)
} else {
c.Error(500, "GetOrgByName", err)
}
return return
} }
if !org.IsOwnedBy(c.User.ID) { if !org.IsOwnedBy(c.User.ID) {
c.Error(403, "", "Given user is not owner of organization.") c.Error(http.StatusForbidden, "", "given user is not owner of organization")
return return
} }
CreateUserRepo(c, org, opt) CreateUserRepo(c, org, opt)
} }
// https://github.com/gogs/go-gogs-client/wiki/Repositories#migrate
func Migrate(c *context.APIContext, f form.MigrateRepo) { func Migrate(c *context.APIContext, f form.MigrateRepo) {
ctxUser := c.User ctxUser := c.User
// Not equal means context user is an organization, // Not equal means context user is an organization,
@ -220,27 +215,27 @@ func Migrate(c *context.APIContext, f form.MigrateRepo) {
org, err := models.GetUserByID(f.Uid) org, err := models.GetUserByID(f.Uid)
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
c.Error(422, "", err) c.Error(http.StatusUnprocessableEntity, "", err)
} else { } else {
c.Error(500, "GetUserByID", err) c.Error(http.StatusInternalServerError, "GetUserByID", err)
} }
return return
} else if !org.IsOrganization() && !c.User.IsAdmin { } else if !org.IsOrganization() && !c.User.IsAdmin {
c.Error(403, "", "Given user is not an organization") c.Error(http.StatusForbidden, "", "given user is not an organization")
return return
} }
ctxUser = org ctxUser = org
} }
if c.HasError() { if c.HasError() {
c.Error(422, "", c.GetErrMsg()) c.Error(http.StatusUnprocessableEntity, "", c.GetErrMsg())
return return
} }
if ctxUser.IsOrganization() && !c.User.IsAdmin { if ctxUser.IsOrganization() && !c.User.IsAdmin {
// Check ownership of organization. // Check ownership of organization.
if !ctxUser.IsOwnedBy(c.User.ID) { if !ctxUser.IsOwnedBy(c.User.ID) {
c.Error(403, "", "Given user is not owner of organization") c.Error(http.StatusForbidden, "", "Given user is not owner of organization")
return return
} }
} }
@ -251,16 +246,16 @@ func Migrate(c *context.APIContext, f form.MigrateRepo) {
addrErr := err.(models.ErrInvalidCloneAddr) addrErr := err.(models.ErrInvalidCloneAddr)
switch { switch {
case addrErr.IsURLError: case addrErr.IsURLError:
c.Error(422, "", err) c.Error(http.StatusUnprocessableEntity, "", err)
case addrErr.IsPermissionDenied: case addrErr.IsPermissionDenied:
c.Error(422, "", "You are not allowed to import local repositories") c.Error(http.StatusUnprocessableEntity, "", "you are not allowed to import local repositories")
case addrErr.IsInvalidPath: case addrErr.IsInvalidPath:
c.Error(422, "", "Invalid local path, it does not exist or not a directory") c.Error(http.StatusUnprocessableEntity, "", "invalid local path, it does not exist or not a directory")
default: default:
c.Error(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error()) c.ServerError("ParseRemoteAddr", fmt.Errorf("unknown error type (ErrInvalidCloneAddr): %v", err))
} }
} else { } else {
c.Error(500, "ParseRemoteAddr", err) c.ServerError("ParseRemoteAddr", err)
} }
return return
} }
@ -280,9 +275,9 @@ func Migrate(c *context.APIContext, f form.MigrateRepo) {
} }
if errors.IsReachLimitOfRepo(err) { if errors.IsReachLimitOfRepo(err) {
c.Error(422, "", err) c.Error(http.StatusUnprocessableEntity, "", err)
} else { } else {
c.Error(500, "MigrateRepository", models.HandleMirrorCredentials(err.Error(), true)) c.ServerError("MigrateRepository", errors.New(models.HandleMirrorCredentials(err.Error(), true)))
} }
return return
} }
@ -291,46 +286,40 @@ func Migrate(c *context.APIContext, f form.MigrateRepo) {
c.JSON(201, repo.APIFormat(&api.Permission{true, true, true})) c.JSON(201, repo.APIFormat(&api.Permission{true, true, true}))
} }
// FIXME: Inject to *context.APIContext // FIXME: inject in the handler chain
func parseOwnerAndRepo(c *context.APIContext) (*models.User, *models.Repository) { func parseOwnerAndRepo(c *context.APIContext) (*models.User, *models.Repository) {
owner, err := models.GetUserByName(c.Params(":username")) owner, err := models.GetUserByName(c.Params(":username"))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
c.Error(422, "", err) c.Error(http.StatusUnprocessableEntity, "", err)
} else { } else {
c.Error(500, "GetUserByName", err) c.ServerError("GetUserByName", err)
} }
return nil, nil return nil, nil
} }
repo, err := models.GetRepositoryByName(owner.ID, c.Params(":reponame")) repo, err := models.GetRepositoryByName(owner.ID, c.Params(":reponame"))
if err != nil { if err != nil {
if errors.IsRepoNotExist(err) { c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
c.Status(404)
} else {
c.Error(500, "GetRepositoryByName", err)
}
return nil, nil return nil, nil
} }
return owner, repo return owner, repo
} }
// https://github.com/gogs/go-gogs-client/wiki/Repositories#get
func Get(c *context.APIContext) { func Get(c *context.APIContext) {
_, repo := parseOwnerAndRepo(c) _, repo := parseOwnerAndRepo(c)
if c.Written() { if c.Written() {
return return
} }
c.JSON(200, repo.APIFormat(&api.Permission{ c.JSONSuccess(repo.APIFormat(&api.Permission{
Admin: c.Repo.IsAdmin(), Admin: c.Repo.IsAdmin(),
Push: c.Repo.IsWriter(), Push: c.Repo.IsWriter(),
Pull: true, Pull: true,
})) }))
} }
// https://github.com/gogs/go-gogs-client/wiki/Repositories#delete
func Delete(c *context.APIContext) { func Delete(c *context.APIContext) {
owner, repo := parseOwnerAndRepo(c) owner, repo := parseOwnerAndRepo(c)
if c.Written() { if c.Written() {
@ -338,30 +327,30 @@ func Delete(c *context.APIContext) {
} }
if owner.IsOrganization() && !owner.IsOwnedBy(c.User.ID) { if owner.IsOrganization() && !owner.IsOwnedBy(c.User.ID) {
c.Error(403, "", "Given user is not owner of organization.") c.Error(http.StatusForbidden, "", "given user is not owner of organization")
return return
} }
if err := models.DeleteRepository(owner.ID, repo.ID); err != nil { if err := models.DeleteRepository(owner.ID, repo.ID); err != nil {
c.Error(500, "DeleteRepository", err) c.ServerError("DeleteRepository", err)
return return
} }
log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name) log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name)
c.Status(204) c.NoContent()
} }
func ListForks(c *context.APIContext) { func ListForks(c *context.APIContext) {
forks, err := c.Repo.Repository.GetForks() forks, err := c.Repo.Repository.GetForks()
if err != nil { if err != nil {
c.Error(500, "GetForks", err) c.ServerError("GetForks", err)
return return
} }
apiForks := make([]*api.Repository, len(forks)) apiForks := make([]*api.Repository, len(forks))
for i := range forks { for i := range forks {
if err := forks[i].GetOwner(); err != nil { if err := forks[i].GetOwner(); err != nil {
c.Error(500, "GetOwner", err) c.ServerError("GetOwner", err)
return return
} }
apiForks[i] = forks[i].APIFormat(&api.Permission{ apiForks[i] = forks[i].APIFormat(&api.Permission{
@ -371,7 +360,7 @@ func ListForks(c *context.APIContext) {
}) })
} }
c.JSON(200, &apiForks) c.JSONSuccess(&apiForks)
} }
func IssueTracker(c *context.APIContext, form api.EditIssueTrackerOption) { func IssueTracker(c *context.APIContext, form api.EditIssueTrackerOption) {
@ -409,10 +398,10 @@ func MirrorSync(c *context.APIContext) {
if c.Written() { if c.Written() {
return return
} else if !repo.IsMirror { } else if !repo.IsMirror {
c.Status(404) c.NotFound()
return return
} }
go models.MirrorQueue.Add(repo.ID) go models.MirrorQueue.Add(repo.ID)
c.Status(202) c.Status(http.StatusAccepted)
} }

View File

@ -5,17 +5,18 @@
package user package user
import ( import (
"net/http"
api "github.com/gogs/go-gogs-client" api "github.com/gogs/go-gogs-client"
"github.com/gogs/gogs/models" "github.com/gogs/gogs/models"
"github.com/gogs/gogs/pkg/context" "github.com/gogs/gogs/pkg/context"
) )
// https://github.com/gogs/go-gogs-client/wiki/Users#list-access-tokens-for-a-user
func ListAccessTokens(c *context.APIContext) { func ListAccessTokens(c *context.APIContext) {
tokens, err := models.ListAccessTokens(c.User.ID) tokens, err := models.ListAccessTokens(c.User.ID)
if err != nil { if err != nil {
c.Error(500, "ListAccessTokens", err) c.ServerError("ListAccessTokens", err)
return return
} }
@ -23,18 +24,17 @@ func ListAccessTokens(c *context.APIContext) {
for i := range tokens { for i := range tokens {
apiTokens[i] = &api.AccessToken{tokens[i].Name, tokens[i].Sha1} apiTokens[i] = &api.AccessToken{tokens[i].Name, tokens[i].Sha1}
} }
c.JSON(200, &apiTokens) c.JSONSuccess(&apiTokens)
} }
// https://github.com/gogs/go-gogs-client/wiki/Users#create-a-access-token
func CreateAccessToken(c *context.APIContext, form api.CreateAccessTokenOption) { func CreateAccessToken(c *context.APIContext, form api.CreateAccessTokenOption) {
t := &models.AccessToken{ t := &models.AccessToken{
UID: c.User.ID, UID: c.User.ID,
Name: form.Name, Name: form.Name,
} }
if err := models.NewAccessToken(t); err != nil { if err := models.NewAccessToken(t); err != nil {
c.Error(500, "NewAccessToken", err) c.ServerError("NewAccessToken", err)
return return
} }
c.JSON(201, &api.AccessToken{t.Name, t.Sha1}) c.JSON(http.StatusCreated, &api.AccessToken{t.Name, t.Sha1})
} }

View File

@ -5,6 +5,8 @@
package user package user
import ( import (
"net/http"
api "github.com/gogs/go-gogs-client" api "github.com/gogs/go-gogs-client"
"github.com/gogs/gogs/models" "github.com/gogs/gogs/models"
@ -13,24 +15,22 @@ import (
"github.com/gogs/gogs/routes/api/v1/convert" "github.com/gogs/gogs/routes/api/v1/convert"
) )
// https://github.com/gogs/go-gogs-client/wiki/Users-Emails#list-email-addresses-for-a-user
func ListEmails(c *context.APIContext) { func ListEmails(c *context.APIContext) {
emails, err := models.GetEmailAddresses(c.User.ID) emails, err := models.GetEmailAddresses(c.User.ID)
if err != nil { if err != nil {
c.Error(500, "GetEmailAddresses", err) c.ServerError("GetEmailAddresses", err)
return return
} }
apiEmails := make([]*api.Email, len(emails)) apiEmails := make([]*api.Email, len(emails))
for i := range emails { for i := range emails {
apiEmails[i] = convert.ToEmail(emails[i]) apiEmails[i] = convert.ToEmail(emails[i])
} }
c.JSON(200, &apiEmails) c.JSONSuccess(&apiEmails)
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Emails#add-email-addresses
func AddEmail(c *context.APIContext, form api.CreateEmailOption) { func AddEmail(c *context.APIContext, form api.CreateEmailOption) {
if len(form.Emails) == 0 { if len(form.Emails) == 0 {
c.Status(422) c.Status(http.StatusUnprocessableEntity)
return return
} }
@ -45,9 +45,9 @@ func AddEmail(c *context.APIContext, form api.CreateEmailOption) {
if err := models.AddEmailAddresses(emails); err != nil { if err := models.AddEmailAddresses(emails); err != nil {
if models.IsErrEmailAlreadyUsed(err) { if models.IsErrEmailAlreadyUsed(err) {
c.Error(422, "", "Email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email) c.Error(http.StatusUnprocessableEntity, "", "email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email)
} else { } else {
c.Error(500, "AddEmailAddresses", err) c.Error(http.StatusInternalServerError, "AddEmailAddresses", err)
} }
return return
} }
@ -56,13 +56,12 @@ func AddEmail(c *context.APIContext, form api.CreateEmailOption) {
for i := range emails { for i := range emails {
apiEmails[i] = convert.ToEmail(emails[i]) apiEmails[i] = convert.ToEmail(emails[i])
} }
c.JSON(201, &apiEmails) c.JSON(http.StatusCreated, &apiEmails)
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Emails#delete-email-addresses
func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) { func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) {
if len(form.Emails) == 0 { if len(form.Emails) == 0 {
c.Status(204) c.NoContent()
return return
} }
@ -75,8 +74,8 @@ func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) {
} }
if err := models.DeleteEmailAddresses(emails); err != nil { if err := models.DeleteEmailAddresses(emails); err != nil {
c.Error(500, "DeleteEmailAddresses", err) c.Error(http.StatusInternalServerError, "DeleteEmailAddresses", err)
return return
} }
c.Status(204) c.NoContent()
} }

View File

@ -16,13 +16,13 @@ func responseApiUsers(c *context.APIContext, users []*models.User) {
for i := range users { for i := range users {
apiUsers[i] = users[i].APIFormat() apiUsers[i] = users[i].APIFormat()
} }
c.JSON(200, &apiUsers) c.JSONSuccess(&apiUsers)
} }
func listUserFollowers(c *context.APIContext, u *models.User) { func listUserFollowers(c *context.APIContext, u *models.User) {
users, err := u.GetFollowers(c.QueryInt("page")) users, err := u.GetFollowers(c.QueryInt("page"))
if err != nil { if err != nil {
c.Error(500, "GetUserFollowers", err) c.ServerError("GetUserFollowers", err)
return return
} }
responseApiUsers(c, users) responseApiUsers(c, users)
@ -32,7 +32,6 @@ func ListMyFollowers(c *context.APIContext) {
listUserFollowers(c, c.User) listUserFollowers(c, c.User)
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Followers#list-followers-of-a-user
func ListFollowers(c *context.APIContext) { func ListFollowers(c *context.APIContext) {
u := GetUserByParams(c) u := GetUserByParams(c)
if c.Written() { if c.Written() {
@ -44,7 +43,7 @@ func ListFollowers(c *context.APIContext) {
func listUserFollowing(c *context.APIContext, u *models.User) { func listUserFollowing(c *context.APIContext, u *models.User) {
users, err := u.GetFollowing(c.QueryInt("page")) users, err := u.GetFollowing(c.QueryInt("page"))
if err != nil { if err != nil {
c.Error(500, "GetFollowing", err) c.ServerError("GetFollowing", err)
return return
} }
responseApiUsers(c, users) responseApiUsers(c, users)
@ -54,7 +53,6 @@ func ListMyFollowing(c *context.APIContext) {
listUserFollowing(c, c.User) listUserFollowing(c, c.User)
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Followers#list-users-followed-by-another-user
func ListFollowing(c *context.APIContext) { func ListFollowing(c *context.APIContext) {
u := GetUserByParams(c) u := GetUserByParams(c)
if c.Written() { if c.Written() {
@ -65,13 +63,12 @@ func ListFollowing(c *context.APIContext) {
func checkUserFollowing(c *context.APIContext, u *models.User, followID int64) { func checkUserFollowing(c *context.APIContext, u *models.User, followID int64) {
if u.IsFollowing(followID) { if u.IsFollowing(followID) {
c.Status(204) c.NotFound()
} else { } else {
c.Status(404) c.NotFound()
} }
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Followers#check-if-you-are-following-a-user
func CheckMyFollowing(c *context.APIContext) { func CheckMyFollowing(c *context.APIContext) {
target := GetUserByParams(c) target := GetUserByParams(c)
if c.Written() { if c.Written() {
@ -80,7 +77,6 @@ func CheckMyFollowing(c *context.APIContext) {
checkUserFollowing(c, c.User, target.ID) checkUserFollowing(c, c.User, target.ID)
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Followers#check-if-one-user-follows-another
func CheckFollowing(c *context.APIContext) { func CheckFollowing(c *context.APIContext) {
u := GetUserByParams(c) u := GetUserByParams(c)
if c.Written() { if c.Written() {
@ -93,28 +89,26 @@ func CheckFollowing(c *context.APIContext) {
checkUserFollowing(c, u, target.ID) checkUserFollowing(c, u, target.ID)
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Followers#follow-a-user
func Follow(c *context.APIContext) { func Follow(c *context.APIContext) {
target := GetUserByParams(c) target := GetUserByParams(c)
if c.Written() { if c.Written() {
return return
} }
if err := models.FollowUser(c.User.ID, target.ID); err != nil { if err := models.FollowUser(c.User.ID, target.ID); err != nil {
c.Error(500, "FollowUser", err) c.ServerError("FollowUser", err)
return return
} }
c.Status(204) c.NoContent()
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Followers#unfollow-a-user
func Unfollow(c *context.APIContext) { func Unfollow(c *context.APIContext) {
target := GetUserByParams(c) target := GetUserByParams(c)
if c.Written() { if c.Written() {
return return
} }
if err := models.UnfollowUser(c.User.ID, target.ID); err != nil { if err := models.UnfollowUser(c.User.ID, target.ID); err != nil {
c.Error(500, "UnfollowUser", err) c.ServerError("UnfollowUser", err)
return return
} }
c.Status(204) c.NoContent()
} }

View File

@ -6,6 +6,7 @@ package user
import ( import (
api "github.com/gogs/go-gogs-client" api "github.com/gogs/go-gogs-client"
"net/http"
"github.com/gogs/gogs/models" "github.com/gogs/gogs/models"
"github.com/gogs/gogs/models/errors" "github.com/gogs/gogs/models/errors"
@ -18,11 +19,7 @@ import (
func GetUserByParamsName(c *context.APIContext, name string) *models.User { func GetUserByParamsName(c *context.APIContext, name string) *models.User {
user, err := models.GetUserByName(c.Params(name)) user, err := models.GetUserByName(c.Params(name))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
c.Status(404)
} else {
c.Error(500, "GetUserByName", err)
}
return nil return nil
} }
return user return user
@ -40,7 +37,7 @@ func composePublicKeysAPILink() string {
func listPublicKeys(c *context.APIContext, uid int64) { func listPublicKeys(c *context.APIContext, uid int64) {
keys, err := models.ListPublicKeys(uid) keys, err := models.ListPublicKeys(uid)
if err != nil { if err != nil {
c.Error(500, "ListPublicKeys", err) c.ServerError("ListPublicKeys", err)
return return
} }
@ -50,15 +47,13 @@ func listPublicKeys(c *context.APIContext, uid int64) {
apiKeys[i] = convert.ToPublicKey(apiLink, keys[i]) apiKeys[i] = convert.ToPublicKey(apiLink, keys[i])
} }
c.JSON(200, &apiKeys) c.JSONSuccess(&apiKeys)
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Public-Keys#list-your-public-keys
func ListMyPublicKeys(c *context.APIContext) { func ListMyPublicKeys(c *context.APIContext) {
listPublicKeys(c, c.User.ID) listPublicKeys(c, c.User.ID)
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Public-Keys#list-public-keys-for-a-user
func ListPublicKeys(c *context.APIContext) { func ListPublicKeys(c *context.APIContext) {
user := GetUserByParams(c) user := GetUserByParams(c)
if c.Written() { if c.Written() {
@ -67,20 +62,15 @@ func ListPublicKeys(c *context.APIContext) {
listPublicKeys(c, user.ID) listPublicKeys(c, user.ID)
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Public-Keys#get-a-single-public-key
func GetPublicKey(c *context.APIContext) { func GetPublicKey(c *context.APIContext) {
key, err := models.GetPublicKeyByID(c.ParamsInt64(":id")) key, err := models.GetPublicKeyByID(c.ParamsInt64(":id"))
if err != nil { if err != nil {
if models.IsErrKeyNotExist(err) { c.NotFoundOrServerError("GetPublicKeyByID", models.IsErrKeyNotExist, err)
c.Status(404)
} else {
c.Error(500, "GetPublicKeyByID", err)
}
return return
} }
apiLink := composePublicKeysAPILink() apiLink := composePublicKeysAPILink()
c.JSON(200, convert.ToPublicKey(apiLink, key)) c.JSONSuccess(convert.ToPublicKey(apiLink, key))
} }
// CreateUserPublicKey creates new public key to given user by ID. // CreateUserPublicKey creates new public key to given user by ID.
@ -97,24 +87,22 @@ func CreateUserPublicKey(c *context.APIContext, form api.CreateKeyOption, uid in
return return
} }
apiLink := composePublicKeysAPILink() apiLink := composePublicKeysAPILink()
c.JSON(201, convert.ToPublicKey(apiLink, key)) c.JSON(http.StatusCreated, convert.ToPublicKey(apiLink, key))
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Public-Keys#create-a-public-key
func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) { func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) {
CreateUserPublicKey(c, form, c.User.ID) CreateUserPublicKey(c, form, c.User.ID)
} }
// https://github.com/gogs/go-gogs-client/wiki/Users-Public-Keys#delete-a-public-key
func DeletePublicKey(c *context.APIContext) { func DeletePublicKey(c *context.APIContext) {
if err := models.DeletePublicKey(c.User, c.ParamsInt64(":id")); err != nil { if err := models.DeletePublicKey(c.User, c.ParamsInt64(":id")); err != nil {
if models.IsErrKeyAccessDenied(err) { if models.IsErrKeyAccessDenied(err) {
c.Error(403, "", "You do not have access to this key") c.Error(http.StatusForbidden, "", "you do not have access to this key")
} else { } else {
c.Error(500, "DeletePublicKey", err) c.Error(http.StatusInternalServerError, "DeletePublicKey", err)
} }
return return
} }
c.Status(204) c.NoContent()
} }

View File

@ -5,6 +5,8 @@
package user package user
import ( import (
"net/http"
"github.com/Unknwon/com" "github.com/Unknwon/com"
api "github.com/gogs/go-gogs-client" api "github.com/gogs/go-gogs-client"
@ -27,7 +29,7 @@ func Search(c *context.APIContext) {
users, _, err := models.SearchUserByName(opts) users, _, err := models.SearchUserByName(opts)
if err != nil { if err != nil {
c.JSON(500, map[string]interface{}{ c.JSON(http.StatusInternalServerError, map[string]interface{}{
"ok": false, "ok": false,
"error": err.Error(), "error": err.Error(),
}) })
@ -47,7 +49,7 @@ func Search(c *context.APIContext) {
} }
} }
c.JSON(200, map[string]interface{}{ c.JSONSuccess(map[string]interface{}{
"ok": true, "ok": true,
"data": results, "data": results,
}) })
@ -57,9 +59,9 @@ func GetInfo(c *context.APIContext) {
u, err := models.GetUserByName(c.Params(":username")) u, err := models.GetUserByName(c.Params(":username"))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
c.Status(404) c.NotFound()
} else { } else {
c.Error(500, "GetUserByName", err) c.ServerError("GetUserByName", err)
} }
return return
} }
@ -68,9 +70,9 @@ func GetInfo(c *context.APIContext) {
if !c.IsLogged { if !c.IsLogged {
u.Email = "" u.Email = ""
} }
c.JSON(200, u.APIFormat()) c.JSONSuccess(u.APIFormat())
} }
func GetAuthenticatedUser(c *context.APIContext) { func GetAuthenticatedUser(c *context.APIContext) {
c.JSON(200, c.User.APIFormat()) c.JSONSuccess(c.User.APIFormat())
} }

View File

@ -1 +1 @@
0.11.90.0801 0.11.91.0808