From fe61b0a23ccdbab1835504347c650d06430e26de Mon Sep 17 00:00:00 2001 From: Kim Lindhardt Madsen Date: Wed, 21 Oct 2015 11:41:46 +0200 Subject: [PATCH] api: simple create user --- cmd/web.go | 2 ++ routers/api/v1/user.go | 45 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/cmd/web.go b/cmd/web.go index 5781872c6..778b3ac01 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -205,6 +205,8 @@ func runWeb(ctx *cli.Context) { // Users. m.Group("/users", func() { + m.Post("", bind(api.CreateUserOption{}), v1.CreateUser) + m.Get("/search", v1.SearchUsers) m.Group("/:username", func() { diff --git a/routers/api/v1/user.go b/routers/api/v1/user.go index f27cd3ae4..a9e6911dc 100644 --- a/routers/api/v1/user.go +++ b/routers/api/v1/user.go @@ -10,9 +10,16 @@ import ( api "github.com/gogits/go-gogs-client" "github.com/gogits/gogs/models" + "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/middleware" ) +const ( + USERS base.TplName = "admin/user/list" + USER_NEW base.TplName = "admin/user/new" + USER_EDIT base.TplName = "admin/user/edit" +) + // ToApiUser converts user to API format. func ToApiUser(u *models.User) *api.User { return &api.User{ @@ -79,3 +86,41 @@ func GetUserInfo(ctx *middleware.Context) { } ctx.JSON(200, &api.User{u.Id, u.Name, u.FullName, u.Email, u.AvatarLink()}) } + +// POST /users +func CreateUser(ctx *middleware.Context, opt api.CreateUserOption) { + if !ctx.User.IsAdmin { + ctx.Error(403) + return + } + + u := &models.User{ + Name: opt.Name, + Email: opt.Email, + Passwd: opt.Password, + IsActive: true, + LoginType: models.PLAIN, + } + + if err := models.CreateUser(u); err != nil { + switch { + case models.IsErrUserAlreadyExist(err): + ctx.Data["Err_UserName"] = true + ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), USER_NEW, &opt) + case models.IsErrEmailAlreadyUsed(err): + ctx.Data["Err_Email"] = true + ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_NEW, &opt) + case models.IsErrNameReserved(err): + ctx.Data["Err_UserName"] = true + ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), USER_NEW, &opt) + case models.IsErrNamePatternNotAllowed(err): + ctx.Data["Err_UserName"] = true + ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), USER_NEW, &opt) + default: + ctx.Handle(500, "CreateUser", err) + } + return + } + + ctx.JSON(201, &api.User{u.Id, u.Name, u.FullName, u.Email, u.AvatarLink()}) +}