1// Copyright 2014 The Gogs Authors. All rights reserved.
2// Copyright 2018 The Gitea Authors. All rights reserved.
3// Use of this source code is governed by a MIT-style
4// license that can be found in the LICENSE file.
5
6package org
7
8import (
9	"errors"
10	"net/http"
11
12	"code.gitea.io/gitea/models"
13	"code.gitea.io/gitea/models/db"
14	user_model "code.gitea.io/gitea/models/user"
15	"code.gitea.io/gitea/modules/base"
16	"code.gitea.io/gitea/modules/context"
17	"code.gitea.io/gitea/modules/log"
18	"code.gitea.io/gitea/modules/setting"
19	"code.gitea.io/gitea/modules/web"
20	"code.gitea.io/gitea/services/forms"
21)
22
23const (
24	// tplCreateOrg template path for create organization
25	tplCreateOrg base.TplName = "org/create"
26)
27
28// Create render the page for create organization
29func Create(ctx *context.Context) {
30	ctx.Data["Title"] = ctx.Tr("new_org")
31	ctx.Data["DefaultOrgVisibilityMode"] = setting.Service.DefaultOrgVisibilityMode
32	if !ctx.User.CanCreateOrganization() {
33		ctx.ServerError("Not allowed", errors.New(ctx.Tr("org.form.create_org_not_allowed")))
34		return
35	}
36	ctx.HTML(http.StatusOK, tplCreateOrg)
37}
38
39// CreatePost response for create organization
40func CreatePost(ctx *context.Context) {
41	form := *web.GetForm(ctx).(*forms.CreateOrgForm)
42	ctx.Data["Title"] = ctx.Tr("new_org")
43
44	if !ctx.User.CanCreateOrganization() {
45		ctx.ServerError("Not allowed", errors.New(ctx.Tr("org.form.create_org_not_allowed")))
46		return
47	}
48
49	if ctx.HasError() {
50		ctx.HTML(http.StatusOK, tplCreateOrg)
51		return
52	}
53
54	org := &models.Organization{
55		Name:                      form.OrgName,
56		IsActive:                  true,
57		Type:                      user_model.UserTypeOrganization,
58		Visibility:                form.Visibility,
59		RepoAdminChangeTeamAccess: form.RepoAdminChangeTeamAccess,
60	}
61
62	if err := models.CreateOrganization(org, ctx.User); err != nil {
63		ctx.Data["Err_OrgName"] = true
64		switch {
65		case user_model.IsErrUserAlreadyExist(err):
66			ctx.RenderWithErr(ctx.Tr("form.org_name_been_taken"), tplCreateOrg, &form)
67		case db.IsErrNameReserved(err):
68			ctx.RenderWithErr(ctx.Tr("org.form.name_reserved", err.(db.ErrNameReserved).Name), tplCreateOrg, &form)
69		case db.IsErrNamePatternNotAllowed(err):
70			ctx.RenderWithErr(ctx.Tr("org.form.name_pattern_not_allowed", err.(db.ErrNamePatternNotAllowed).Pattern), tplCreateOrg, &form)
71		case models.IsErrUserNotAllowedCreateOrg(err):
72			ctx.RenderWithErr(ctx.Tr("org.form.create_org_not_allowed"), tplCreateOrg, &form)
73		default:
74			ctx.ServerError("CreateOrganization", err)
75		}
76		return
77	}
78	log.Trace("Organization created: %s", org.Name)
79
80	ctx.Redirect(org.AsUser().DashboardLink())
81}
82