Example #1
0
// https://github.com/gogits/go-gogs-client/wiki/Users-Emails#add-email-addresses
func AddEmail(ctx *middleware.Context, form api.CreateEmailOption) {
	if len(form.Emails) == 0 {
		ctx.Status(422)
		return
	}

	emails := make([]*models.EmailAddress, len(form.Emails))
	for i := range form.Emails {
		emails[i] = &models.EmailAddress{
			UID:         ctx.User.Id,
			Email:       form.Emails[i],
			IsActivated: !setting.Service.RegisterEmailConfirm,
		}
	}

	if err := models.AddEmailAddresses(emails); err != nil {
		if models.IsErrEmailAlreadyUsed(err) {
			ctx.APIError(422, "", "Email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email)
		} else {
			ctx.APIError(500, "AddEmailAddresses", err)
		}
		return
	}

	apiEmails := make([]*api.Email, len(emails))
	for i := range emails {
		apiEmails[i] = convert.ToApiEmail(emails[i])
	}
	ctx.JSON(201, &apiEmails)
}
Example #2
0
// https://github.com/gogits/go-gogs-client/wiki/Repositories---Deploy-Keys#add-a-new-deploy-key
func CreateRepoDeployKey(ctx *middleware.Context, form api.CreateKeyOption) {
	content, err := models.CheckPublicKeyString(form.Key)
	if err != nil {
		if models.IsErrKeyUnableVerify(err) {
			ctx.APIError(422, "", "Unable to verify key content")
		} else {
			ctx.APIError(422, "", fmt.Errorf("Invalid key content: %v", err))
		}
		return
	}

	key, err := models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content)
	if err != nil {
		ctx.Data["HasError"] = true
		switch {
		case models.IsErrKeyAlreadyExist(err):
			ctx.APIError(422, "", "Key content has been used as non-deploy key")
		case models.IsErrKeyNameAlreadyUsed(err):
			ctx.APIError(422, "", "Key title has been used")
		default:
			ctx.APIError(500, "AddDeployKey", err)
		}
		return
	}

	key.Content = content
	apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name)
	ctx.JSON(201, ToApiDeployKey(apiLink, key))
}
Example #3
0
func responseApiUsers(ctx *middleware.Context, users []*models.User) {
	apiUsers := make([]*api.User, len(users))
	for i := range users {
		apiUsers[i] = convert.ToApiUser(users[i])
	}
	ctx.JSON(200, &apiUsers)
}
Example #4
0
func TeamsRepoAction(ctx *middleware.Context) {
	if !ctx.Org.IsOwner {
		ctx.Error(404)
		return
	}

	var err error
	switch ctx.Params(":action") {
	case "add":
		repoName := path.Base(ctx.Query("repo-name"))
		var repo *models.Repository
		repo, err = models.GetRepositoryByName(ctx.Org.Organization.Id, repoName)
		if err != nil {
			ctx.Handle(500, "GetRepositoryByName", err)
			return
		}
		err = ctx.Org.Team.AddRepository(repo)
	case "remove":
		err = ctx.Org.Team.RemoveRepository(com.StrTo(ctx.Query("repoid")).MustInt64())
	}

	if err != nil {
		log.Error(3, "Action(%s): %v", ctx.Params(":action"), err)
		ctx.JSON(200, map[string]interface{}{
			"ok":  false,
			"err": err.Error(),
		})
		return
	}
	ctx.Redirect(ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName + "/repositories")
}
Example #5
0
// https://github.com/gogits/go-gogs-client/wiki/Administration-Organizations#create-a-new-organization
func CreateOrg(ctx *middleware.Context, form api.CreateOrgOption) {
	u := user.GetUserByParams(ctx)
	if ctx.Written() {
		return
	}

	org := &models.User{
		Name:        form.UserName,
		FullName:    form.FullName,
		Description: form.Description,
		Website:     form.Website,
		Location:    form.Location,
		IsActive:    true,
		Type:        models.ORGANIZATION,
	}
	if err := models.CreateOrganization(org, u); err != nil {
		if models.IsErrUserAlreadyExist(err) ||
			models.IsErrNameReserved(err) ||
			models.IsErrNamePatternNotAllowed(err) {
			ctx.APIError(422, "CreateOrganization", err)
		} else {
			ctx.APIError(500, "CreateOrganization", err)
		}
		return
	}

	ctx.JSON(201, convert.ToApiOrganization(org))
}
Example #6
0
func UpdateCommentContent(ctx *middleware.Context) {
	comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
	if err != nil {
		if models.IsErrCommentNotExist(err) {
			ctx.Error(404, "GetCommentByID")
		} else {
			ctx.Handle(500, "GetCommentByID", err)
		}
		return
	}

	if !ctx.IsSigned || (ctx.User.Id != comment.PosterID && !ctx.Repo.IsAdmin()) {
		ctx.Error(403)
		return
	} else if comment.Type != models.COMMENT_TYPE_COMMENT {
		ctx.Error(204)
		return
	}

	comment.Content = ctx.Query("content")
	if len(comment.Content) == 0 {
		ctx.JSON(200, map[string]interface{}{
			"content": "",
		})
		return
	}
	if err := models.UpdateComment(comment); err != nil {
		ctx.Handle(500, "UpdateComment", err)
		return
	}

	ctx.JSON(200, map[string]interface{}{
		"content": string(base.RenderMarkdown([]byte(comment.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
	})
}
Example #7
0
File: repo.go Project: kiliit/gogs
// https://github.com/kiliit/go-gogs-client/wiki/Repositories#list-your-repositories
func ListMyRepos(ctx *middleware.Context) {
	ownRepos, err := models.GetRepositories(ctx.User.Id, true)
	if err != nil {
		ctx.APIError(500, "GetRepositories", err)
		return
	}
	numOwnRepos := len(ownRepos)

	accessibleRepos, err := ctx.User.GetRepositoryAccesses()
	if err != nil {
		ctx.APIError(500, "GetRepositoryAccesses", err)
		return
	}

	repos := make([]*api.Repository, numOwnRepos+len(accessibleRepos))
	for i := range ownRepos {
		repos[i] = ToApiRepository(ctx.User, ownRepos[i], api.Permission{true, true, true})
	}
	i := numOwnRepos

	for repo, access := range accessibleRepos {
		repos[i] = ToApiRepository(repo.Owner, repo, api.Permission{
			Admin: access >= models.ACCESS_MODE_ADMIN,
			Push:  access >= models.ACCESS_MODE_WRITE,
			Pull:  true,
		})
		i++
	}

	ctx.JSON(200, &repos)
}
Example #8
0
File: repo.go Project: kiliit/gogs
func createRepo(ctx *middleware.Context, owner *models.User, opt api.CreateRepoOption) {
	repo, err := models.CreateRepository(owner, models.CreateRepoOptions{
		Name:        opt.Name,
		Description: opt.Description,
		Gitignores:  opt.Gitignores,
		License:     opt.License,
		Readme:      opt.Readme,
		IsPrivate:   opt.Private,
		AutoInit:    opt.AutoInit,
	})
	if err != nil {
		if models.IsErrRepoAlreadyExist(err) ||
			models.IsErrNameReserved(err) ||
			models.IsErrNamePatternNotAllowed(err) {
			ctx.APIError(422, "", err)
		} else {
			if repo != nil {
				if err = models.DeleteRepository(ctx.User.Id, repo.ID); err != nil {
					log.Error(4, "DeleteRepository: %v", err)
				}
			}
			ctx.APIError(500, "CreateRepository", err)
		}
		return
	}

	ctx.JSON(201, ToApiRepository(owner, repo, api.Permission{true, true, true}))
}
Example #9
0
// GET /repos/:username/:reponame/hooks
// https://developer.github.com/v3/repos/hooks/#list-hooks
func ListRepoHooks(ctx *middleware.Context) {
	hooks, err := models.GetWebhooksByRepoId(ctx.Repo.Repository.Id)
	if err != nil {
		ctx.JSON(500, &base.ApiJsonErr{"GetWebhooksByRepoId: " + err.Error(), base.DOC_URL})
		return
	}

	apiHooks := make([]*api.Hook, len(hooks))
	for i := range hooks {
		h := &api.Hook{
			Id:     hooks[i].Id,
			Type:   hooks[i].HookTaskType.Name(),
			Active: hooks[i].IsActive,
			Config: make(map[string]string),
		}

		// Currently, onle have push event.
		h.Events = []string{"push"}

		h.Config["url"] = hooks[i].Url
		h.Config["content_type"] = hooks[i].ContentType.Name()
		if hooks[i].HookTaskType == models.SLACK {
			s := hooks[i].GetSlackHook()
			h.Config["channel"] = s.Channel
		}

		apiHooks[i] = h
	}

	ctx.JSON(200, &apiHooks)
}
Example #10
0
func SearchUsers(ctx *middleware.Context) {
	opt := models.SearchOption{
		Keyword: ctx.Query("q"),
		Limit:   com.StrTo(ctx.Query("limit")).MustInt(),
	}
	if opt.Limit == 0 {
		opt.Limit = 10
	}

	us, err := models.SearchUserByName(opt)
	if err != nil {
		ctx.JSON(500, map[string]interface{}{
			"ok":    false,
			"error": err.Error(),
		})
		return
	}

	results := make([]*api.User, len(us))
	for i := range us {
		results[i] = &api.User{
			UserName:  us[i].Name,
			AvatarUrl: us[i].AvatarLink(),
			FullName:  us[i].FullName,
		}
	}

	ctx.Render.JSON(200, map[string]interface{}{
		"ok":   true,
		"data": results,
	})
}
Example #11
0
func UpdateIssueTitle(ctx *middleware.Context) {
	issue := getActionIssue(ctx)
	if ctx.Written() {
		return
	}

	if !ctx.IsSigned || (ctx.User.Id != issue.PosterID && !ctx.Repo.IsAdmin()) {
		ctx.Error(403)
		return
	}

	issue.Name = ctx.QueryTrim("title")
	if len(issue.Name) == 0 {
		ctx.Error(204)
		return
	}

	if err := models.UpdateIssue(issue); err != nil {
		ctx.Handle(500, "UpdateIssue", err)
		return
	}

	ctx.JSON(200, map[string]interface{}{
		"title": issue.Name,
	})
}
Example #12
0
func Action(ctx *middleware.Context, params martini.Params) {
	var err error
	switch params["action"] {
	case "watch":
		err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.Id, true)
	case "unwatch":
		err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.Id, false)
	case "desc":
		if !ctx.Repo.IsOwner {
			ctx.Error(404)
			return
		}

		ctx.Repo.Repository.Description = ctx.Query("desc")
		ctx.Repo.Repository.Website = ctx.Query("site")
		err = models.UpdateRepository(ctx.Repo.Repository)
	}

	if err != nil {
		log.Error("repo.Action(%s): %v", params["action"], err)
		ctx.JSON(200, map[string]interface{}{
			"ok":  false,
			"err": err.Error(),
		})
		return
	}
	ctx.JSON(200, map[string]interface{}{
		"ok": true,
	})
}
Example #13
0
func UpdateIssueAssignee(ctx *middleware.Context) {
	issue := getActionIssue(ctx)
	if ctx.Written() {
		return
	}

	aid := ctx.QueryInt64("id")
	if issue.AssigneeID == aid {
		ctx.JSON(200, map[string]interface{}{
			"ok": true,
		})
		return
	}

	// Not check for invalid assignee id and give responsibility to owners.
	issue.AssigneeID = aid
	if err := models.UpdateIssueUserByAssignee(issue); err != nil {
		ctx.Handle(500, "UpdateIssueUserByAssignee: %v", err)
		return
	}

	ctx.JSON(200, map[string]interface{}{
		"ok": true,
	})
}
Example #14
0
func UpdateIssueMilestone(ctx *middleware.Context) {
	issue := getActionIssue(ctx)
	if ctx.Written() {
		return
	}

	oldMid := issue.MilestoneID
	mid := ctx.QueryInt64("id")
	if oldMid == mid {
		ctx.JSON(200, map[string]interface{}{
			"ok": true,
		})
		return
	}

	// Not check for invalid milestone id and give responsibility to owners.
	issue.MilestoneID = mid
	if err := models.ChangeMilestoneAssign(oldMid, issue); err != nil {
		ctx.Handle(500, "ChangeMilestoneAssign", err)
		return
	}

	ctx.JSON(200, map[string]interface{}{
		"ok": true,
	})
}
Example #15
0
func DeleteAuthSource(ctx *middleware.Context) {
	source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid"))
	if err != nil {
		ctx.Handle(500, "GetLoginSourceByID", err)
		return
	}

	if err = models.DeleteSource(source); err != nil {
		switch err {
		case models.ErrAuthenticationUserUsed:
			ctx.Flash.Error(ctx.Tr("admin.auths.still_in_used"))
		default:
			ctx.Flash.Error(fmt.Sprintf("DeleteSource: %v", err))
		}
		ctx.JSON(200, map[string]interface{}{
			"redirect": setting.AppSubUrl + "/admin/auths/" + ctx.Params(":authid"),
		})
		return
	}
	log.Trace("Authentication deleted by admin(%s): %d", ctx.User.Name, source.ID)

	ctx.Flash.Success(ctx.Tr("admin.auths.deletion_success"))
	ctx.JSON(200, map[string]interface{}{
		"redirect": setting.AppSubUrl + "/admin/auths",
	})
}
Example #16
0
// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-new-user
func CreateUser(ctx *middleware.Context, form api.CreateUserOption) {
	u := &models.User{
		Name:      form.Username,
		Email:     form.Email,
		Passwd:    form.Password,
		IsActive:  true,
		LoginType: models.LOGIN_PLAIN,
	}

	parseLoginSource(ctx, u, form.SourceID, form.LoginName)
	if ctx.Written() {
		return
	}

	if err := models.CreateUser(u); err != nil {
		if models.IsErrUserAlreadyExist(err) ||
			models.IsErrEmailAlreadyUsed(err) ||
			models.IsErrNameReserved(err) ||
			models.IsErrNamePatternNotAllowed(err) {
			ctx.APIError(422, "", err)
		} else {
			ctx.APIError(500, "CreateUser", err)
		}
		return
	}
	log.Trace("Account created by admin (%s): %s", ctx.User.Name, u.Name)

	// Send e-mail notification.
	if form.SendNotify && setting.MailService != nil {
		mailer.SendRegisterNotifyMail(ctx.Context, u)
	}

	ctx.JSON(201, convert.ToApiUser(u))
}
Example #17
0
// https://github.com/gogits/go-gogs-client/wiki/Organizations#get-an-organization
func Get(ctx *middleware.Context) {
	org := user.GetUserByParamsName(ctx, ":orgname")
	if ctx.Written() {
		return
	}
	ctx.JSON(200, convert.ToApiOrganization(org))
}
Example #18
0
// POST /user/repos
// https://developer.github.com/v3/repos/#create
func CreateRepo(ctx *middleware.Context, opt api.CreateRepoOption) {
	// Shouldn't reach this condition, but just in case.
	if ctx.User.IsOrganization() {
		ctx.JSON(422, "not allowed creating repository for organization")
		return
	}
	createRepo(ctx, ctx.User, opt)
}
Example #19
0
// Render a Markdown document in raw mode.
func MarkdownRaw(ctx *middleware.Context) {
	body, err := ioutil.ReadAll(ctx.Req.Body)
	if err != nil {
		ctx.JSON(422, base.ApiJsonErr{err.Error(), DOC_URL})
		return
	}
	ctx.Write(base.RenderRawMarkdown(body, ""))
}
Example #20
0
File: repo.go Project: kiliit/gogs
func GetRepo(ctx *middleware.Context) {
	owner, repo := parseOwnerAndRepo(ctx)
	if ctx.Written() {
		return
	}

	ctx.JSON(200, ToApiRepository(owner, repo, api.Permission{true, true, true}))
}
Example #21
0
func MembersAction(ctx *middleware.Context) {
	uid := com.StrTo(ctx.Query("uid")).MustInt64()
	if uid == 0 {
		ctx.Redirect(ctx.Org.OrgLink + "/members")
		return
	}

	org := ctx.Org.Organization
	var err error
	switch ctx.Params(":action") {
	case "private":
		if ctx.User.Id != uid && !ctx.Org.IsOwner {
			ctx.Error(404)
			return
		}
		err = models.ChangeOrgUserStatus(org.Id, uid, false)
	case "public":
		if ctx.User.Id != uid {
			ctx.Error(404)
			return
		}
		err = models.ChangeOrgUserStatus(org.Id, uid, true)
	case "remove":
		if !ctx.Org.IsOwner {
			ctx.Error(404)
			return
		}
		err = org.RemoveMember(uid)
		if models.IsErrLastOrgOwner(err) {
			ctx.Flash.Error(ctx.Tr("form.last_org_owner"))
			ctx.Redirect(ctx.Org.OrgLink + "/members")
			return
		}
	case "leave":
		err = org.RemoveMember(ctx.User.Id)
		if models.IsErrLastOrgOwner(err) {
			ctx.Flash.Error(ctx.Tr("form.last_org_owner"))
			ctx.Redirect(ctx.Org.OrgLink + "/members")
			return
		}
	}

	if err != nil {
		log.Error(4, "Action(%s): %v", ctx.Params(":action"), err)
		ctx.JSON(200, map[string]interface{}{
			"ok":  false,
			"err": err.Error(),
		})
		return
	}

	if ctx.Params(":action") != "leave" {
		ctx.Redirect(ctx.Org.OrgLink + "/members")
	} else {
		ctx.Redirect(setting.AppSubUrl + "/")
	}
}
Example #22
0
func CommitByID(ctx *middleware.Context) {
	commit, err := ctx.Repo.GitRepo.GetCommit(ctx.Params(":commitid"))
	if err != nil {
		log.Error(4, "GetCommit: %v", err)
		ctx.APIError(500, "GetCommit", err.Error())
		return
	}

	ctx.JSON(200, ToApiCommit(commit))
}
Example #23
0
func SettingsDeleteApplication(ctx *middleware.Context) {
	if err := models.DeleteAccessTokenByID(ctx.QueryInt64("id")); err != nil {
		ctx.Flash.Error("DeleteAccessTokenByID: " + err.Error())
	} else {
		ctx.Flash.Success(ctx.Tr("settings.delete_token_success"))
	}

	ctx.JSON(200, map[string]interface{}{
		"redirect": setting.AppSubUrl + "/user/settings/applications",
	})
}
Example #24
0
func DeleteTeam(ctx *middleware.Context) {
	if err := models.DeleteTeam(ctx.Org.Team); err != nil {
		ctx.Flash.Error("DeleteTeam: " + err.Error())
	} else {
		ctx.Flash.Success(ctx.Tr("org.teams.delete_team_success"))
	}

	ctx.JSON(200, map[string]interface{}{
		"redirect": ctx.Org.OrgLink + "/teams",
	})
}
Example #25
0
// POST /users/:username/tokens
func CreateAccessToken(ctx *middleware.Context, form CreateAccessTokenForm) {
	t := &models.AccessToken{
		UID:  ctx.User.Id,
		Name: form.Name,
	}
	if err := models.NewAccessToken(t); err != nil {
		ctx.APIError(500, "NewAccessToken", err)
		return
	}
	ctx.JSON(201, &api.AccessToken{t.Name, t.Sha1})
}
Example #26
0
func DeleteWebhook(ctx *middleware.Context) {
	if err := models.DeleteWebhook(ctx.QueryInt64("id")); err != nil {
		ctx.Flash.Error("DeleteWebhook: " + err.Error())
	} else {
		ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
	}

	ctx.JSON(200, map[string]interface{}{
		"redirect": ctx.Org.OrgLink + "/settings/hooks",
	})
}
Example #27
0
func DeleteMilestone(ctx *middleware.Context) {
	if err := models.DeleteMilestoneByID(ctx.QueryInt64("id")); err != nil {
		ctx.Flash.Error("DeleteMilestoneByID: " + err.Error())
	} else {
		ctx.Flash.Success(ctx.Tr("repo.milestones.deletion_success"))
	}

	ctx.JSON(200, map[string]interface{}{
		"redirect": ctx.Repo.RepoLink + "/milestones",
	})
}
Example #28
0
// POST /users/:username/tokens
func CreateAccessToken(ctx *middleware.Context, form CreateAccessTokenForm) {
	t := &models.AccessToken{
		UID:  ctx.User.Id,
		Name: form.Name,
	}
	if err := models.NewAccessToken(t); err != nil {
		ctx.JSON(500, &base.ApiJsonErr{"NewAccessToken: " + err.Error(), base.DOC_URL})
		return
	}
	ctx.JSON(201, &api.AccessToken{t.Name, t.Sha1})
}
Example #29
0
func DeleteDeployKey(ctx *middleware.Context) {
	if err := models.DeleteDeployKey(ctx.QueryInt64("id")); err != nil {
		ctx.Flash.Error("DeleteDeployKey: " + err.Error())
	} else {
		ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success"))
	}

	ctx.JSON(200, map[string]interface{}{
		"redirect": ctx.Repo.RepoLink + "/settings/keys",
	})
}
Example #30
0
func DeleteSSHKey(ctx *middleware.Context) {
	if err := models.DeletePublicKey(ctx.QueryInt64("id")); err != nil {
		ctx.Flash.Error("DeletePublicKey: " + err.Error())
	} else {
		ctx.Flash.Success(ctx.Tr("settings.ssh_key_deletion_success"))
	}

	ctx.JSON(200, map[string]interface{}{
		"redirect": setting.AppSubUrl + "/user/settings/ssh",
	})
}