func SettingsPasswordPost(ctx *context.Context, form auth.ChangePasswordForm) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsPassword"] = true if ctx.HasError() { ctx.HTML(200, SETTINGS_PASSWORD) return } if !ctx.User.ValidatePassword(form.OldPassword) { ctx.Flash.Error(ctx.Tr("settings.password_incorrect")) } else if form.Password != form.Retype { ctx.Flash.Error(ctx.Tr("form.password_not_match")) } else { ctx.User.Passwd = form.Password ctx.User.Salt = models.GetUserSalt() ctx.User.EncodePasswd() if err := models.UpdateUser(ctx.User); err != nil { ctx.Handle(500, "UpdateUser", err) return } log.Trace("User password updated: %s", ctx.User.Name) ctx.Flash.Success(ctx.Tr("settings.change_password_success")) } ctx.Redirect(setting.AppSubUrl + "/user/settings/password") }
func NewTeamPost(ctx *context.Context, form auth.CreateTeamForm) { ctx.Data["Title"] = ctx.Org.Organization.FullName ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeamsNew"] = true t := &models.Team{ OrgID: ctx.Org.Organization.Id, Name: form.TeamName, Description: form.Description, Authorize: models.ParseAccessMode(form.Permission), } ctx.Data["Team"] = t if ctx.HasError() { ctx.HTML(200, TEAM_NEW) return } if err := models.NewTeam(t); err != nil { ctx.Data["Err_TeamName"] = true switch { case models.IsErrTeamAlreadyExist(err): ctx.RenderWithErr(ctx.Tr("form.team_name_been_taken"), TEAM_NEW, &form) default: ctx.Handle(500, "NewTeam", err) } return } log.Trace("Team created: %s/%s", ctx.Org.Organization.Name, t.Name) ctx.Redirect(ctx.Org.OrgLink + "/teams/" + t.LowerName) }
func NewMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { ctx.Data["Title"] = ctx.Tr("repo.milestones.new") ctx.Data["PageIsIssueList"] = true ctx.Data["PageIsMilestones"] = true ctx.Data["RequireDatetimepicker"] = true ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language()) if ctx.HasError() { ctx.HTML(200, MILESTONE_NEW) return } if len(form.Deadline) == 0 { form.Deadline = "9999-12-31" } deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local) if err != nil { ctx.Data["Err_Deadline"] = true ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &form) return } if err = models.NewMilestone(&models.Milestone{ RepoID: ctx.Repo.Repository.ID, Name: form.Title, Content: form.Content, Deadline: deadline, }); err != nil { ctx.Handle(500, "NewMilestone", err) return } ctx.Flash.Success(ctx.Tr("repo.milestones.create_success", form.Title)) ctx.Redirect(ctx.Repo.RepoLink + "/milestones") }
func CreatePost(ctx *context.Context, form auth.CreateOrgForm) { ctx.Data["Title"] = ctx.Tr("new_org") if ctx.HasError() { ctx.HTML(200, CREATE) return } org := &models.User{ Name: form.OrgName, IsActive: true, Type: models.USER_TYPE_ORGANIZATION, } if err := models.CreateOrganization(org, ctx.User); err != nil { ctx.Data["Err_OrgName"] = true switch { case models.IsErrUserAlreadyExist(err): ctx.RenderWithErr(ctx.Tr("form.org_name_been_taken"), CREATE, &form) case models.IsErrNameReserved(err): ctx.RenderWithErr(ctx.Tr("org.form.name_reserved", err.(models.ErrNameReserved).Name), CREATE, &form) case models.IsErrNamePatternNotAllowed(err): ctx.RenderWithErr(ctx.Tr("org.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), CREATE, &form) default: ctx.Handle(500, "CreateOrganization", err) } return } log.Trace("Organization created: %s", org.Name) ctx.Redirect(setting.AppSubUrl + "/org/" + form.OrgName + "/dashboard") }
func SettingsApplicationsPost(ctx *context.Context, form auth.NewAccessTokenForm) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsApplications"] = true if ctx.HasError() { tokens, err := models.ListAccessTokens(ctx.User.Id) if err != nil { ctx.Handle(500, "ListAccessTokens", err) return } ctx.Data["Tokens"] = tokens ctx.HTML(200, SETTINGS_APPLICATIONS) return } t := &models.AccessToken{ UID: ctx.User.Id, Name: form.Name, } if err := models.NewAccessToken(t); err != nil { ctx.Handle(500, "NewAccessToken", err) return } ctx.Flash.Success(ctx.Tr("settings.generate_token_succees")) ctx.Flash.Info(t.Sha1) ctx.Redirect(setting.AppSubUrl + "/user/settings/applications") }
func SettingsPost(ctx *context.Context, form auth.UpdateProfileForm) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsProfile"] = true if ctx.HasError() { ctx.HTML(200, SETTINGS_PROFILE) return } handleUsernameChange(ctx, form.Name) if ctx.Written() { return } ctx.User.FullName = form.FullName ctx.User.Email = form.Email ctx.User.Website = form.Website ctx.User.Location = form.Location if len(form.Gravatar) > 0 { ctx.User.Avatar = base.EncodeMD5(form.Gravatar) ctx.User.AvatarEmail = form.Gravatar } if err := models.UpdateUser(ctx.User); err != nil { ctx.Handle(500, "UpdateUser", err) return } log.Trace("User settings updated: %s", ctx.User.Name) ctx.Flash.Success(ctx.Tr("settings.update_profile_success")) ctx.Redirect(setting.AppSubUrl + "/user/settings") }
func SettingsEmailPost(ctx *context.Context, form auth.AddEmailForm) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsEmails"] = true // Make emailaddress primary. if ctx.Query("_method") == "PRIMARY" { if err := models.MakeEmailPrimary(&models.EmailAddress{ID: ctx.QueryInt64("id")}); err != nil { ctx.Handle(500, "MakeEmailPrimary", err) return } log.Trace("Email made primary: %s", ctx.User.Name) ctx.Redirect(setting.AppSubUrl + "/user/settings/email") return } // Add Email address. emails, err := models.GetEmailAddresses(ctx.User.Id) if err != nil { ctx.Handle(500, "GetEmailAddresses", err) return } ctx.Data["Emails"] = emails if ctx.HasError() { ctx.HTML(200, SETTINGS_EMAILS) return } e := &models.EmailAddress{ UID: ctx.User.Id, Email: form.Email, IsActivated: !setting.Service.RegisterEmailConfirm, } if err := models.AddEmailAddress(e); err != nil { if models.IsErrEmailAlreadyUsed(err) { ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SETTINGS_EMAILS, &form) return } ctx.Handle(500, "AddEmailAddress", err) return } // Send confirmation e-mail if setting.Service.RegisterEmailConfirm { mailer.SendActivateEmailMail(ctx.Context, ctx.User, e) if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil { log.Error(4, "Set cache(MailResendLimit) fail: %v", err) } ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", e.Email, setting.Service.ActiveCodeLives/60)) } else { ctx.Flash.Success(ctx.Tr("settings.add_email_success")) } log.Trace("Email address added: %s", e.Email) ctx.Redirect(setting.AppSubUrl + "/user/settings/email") }
func EditUserPost(ctx *context.Context, form auth.AdminEditUserForm) { ctx.Data["Title"] = ctx.Tr("admin.users.edit_account") ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdminUsers"] = true u := prepareUserInfo(ctx) if ctx.Written() { return } if ctx.HasError() { ctx.HTML(200, USER_EDIT) return } fields := strings.Split(form.LoginType, "-") if len(fields) == 2 { loginType := models.LoginType(com.StrTo(fields[0]).MustInt()) loginSource := com.StrTo(fields[1]).MustInt64() if u.LoginSource != loginSource { u.LoginSource = loginSource u.LoginType = loginType } } if len(form.Password) > 0 { u.Passwd = form.Password u.Salt = models.GetUserSalt() u.EncodePasswd() } u.LoginName = form.LoginName u.FullName = form.FullName u.Email = form.Email u.Website = form.Website u.Location = form.Location u.MaxRepoCreation = form.MaxRepoCreation u.IsActive = form.Active u.IsAdmin = form.Admin u.AllowGitHook = form.AllowGitHook u.AllowImportLocal = form.AllowImportLocal if err := models.UpdateUser(u); err != nil { if models.IsErrEmailAlreadyUsed(err) { ctx.Data["Err_Email"] = true ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_EDIT, &form) } else { ctx.Handle(500, "UpdateUser", err) } return } log.Trace("Account profile updated by admin (%s): %s", ctx.User.Name, u.Name) ctx.Flash.Success(ctx.Tr("admin.users.update_profile_success")) ctx.Redirect(setting.AppSubUrl + "/admin/users/" + ctx.Params(":userid")) }
func SettingsPost(ctx *context.Context, form auth.UpdateOrgSettingForm) { ctx.Data["Title"] = ctx.Tr("org.settings") ctx.Data["PageIsSettingsOptions"] = true if ctx.HasError() { ctx.HTML(200, SETTINGS_OPTIONS) return } org := ctx.Org.Organization // Check if organization name has been changed. if org.LowerName != strings.ToLower(form.Name) { isExist, err := models.IsUserExist(org.Id, form.Name) if err != nil { ctx.Handle(500, "IsUserExist", err) return } else if isExist { ctx.Data["OrgName"] = true ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SETTINGS_OPTIONS, &form) return } else if err = models.ChangeUserName(org, form.Name); err != nil { if err == models.ErrUserNameIllegal { ctx.Data["OrgName"] = true ctx.RenderWithErr(ctx.Tr("form.illegal_username"), SETTINGS_OPTIONS, &form) } else { ctx.Handle(500, "ChangeUserName", err) } return } // reset ctx.org.OrgLink with new name ctx.Org.OrgLink = setting.AppSubUrl + "/org/" + form.Name log.Trace("Organization name changed: %s -> %s", org.Name, form.Name) } // In case it's just a case change. org.Name = form.Name org.LowerName = strings.ToLower(form.Name) if ctx.User.IsAdmin { org.MaxRepoCreation = form.MaxRepoCreation } org.FullName = form.FullName org.Description = form.Description org.Website = form.Website org.Location = form.Location if err := models.UpdateUser(org); err != nil { ctx.Handle(500, "UpdateUser", err) return } log.Trace("Organization setting updated: %s", org.Name) ctx.Flash.Success(ctx.Tr("org.settings.update_setting_success")) ctx.Redirect(ctx.Org.OrgLink + "/settings") }
func NewReleasePost(ctx *context.Context, form auth.NewReleaseForm) { ctx.Data["Title"] = ctx.Tr("repo.release.new_release") ctx.Data["PageIsReleaseList"] = true if ctx.HasError() { ctx.HTML(200, RELEASE_NEW) return } if !ctx.Repo.GitRepo.IsBranchExist(form.Target) { ctx.RenderWithErr(ctx.Tr("form.target_branch_not_exist"), RELEASE_NEW, &form) return } commit, err := ctx.Repo.GitRepo.GetBranchCommit(form.Target) if err != nil { ctx.Handle(500, "GetBranchCommit", err) return } commitsCount, err := commit.CommitsCount() if err != nil { ctx.Handle(500, "CommitsCount", err) return } rel := &models.Release{ RepoID: ctx.Repo.Repository.ID, PublisherID: ctx.User.Id, Title: form.Title, TagName: form.TagName, Target: form.Target, Sha1: commit.ID.String(), NumCommits: commitsCount, Note: form.Content, IsDraft: len(form.Draft) > 0, IsPrerelease: form.Prerelease, } if err = models.CreateRelease(ctx.Repo.GitRepo, rel); err != nil { if models.IsErrReleaseAlreadyExist(err) { ctx.Data["Err_TagName"] = true ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_already_exist"), RELEASE_NEW, &form) } else { ctx.Handle(500, "CreateRelease", err) } return } log.Trace("Release created: %s/%s:%s", ctx.User.LowerName, ctx.Repo.Repository.Name, form.TagName) ctx.Redirect(ctx.Repo.RepoLink + "/releases") }
func ForkPost(ctx *context.Context, form auth.CreateRepoForm) { ctx.Data["Title"] = ctx.Tr("new_fork") forkRepo := getForkRepository(ctx) if ctx.Written() { return } ctxUser := checkContextUser(ctx, form.Uid) if ctx.Written() { return } ctx.Data["ContextUser"] = ctxUser if ctx.HasError() { ctx.HTML(200, FORK) return } repo, has := models.HasForkedRepo(ctxUser.Id, forkRepo.ID) if has { ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + repo.Name) return } // Check ownership of organization. if ctxUser.IsOrganization() { if !ctxUser.IsOwnedBy(ctx.User.Id) { ctx.Error(403) return } } repo, err := models.ForkRepository(ctxUser, forkRepo, form.RepoName, form.Description) if err != nil { ctx.Data["Err_RepoName"] = true switch { case models.IsErrRepoAlreadyExist(err): ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), FORK, &form) case models.IsErrNameReserved(err): ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), FORK, &form) case models.IsErrNamePatternNotAllowed(err): ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), FORK, &form) default: ctx.Handle(500, "ForkPost", err) } return } log.Trace("Repository forked[%d]: %s/%s", forkRepo.ID, ctxUser.Name, repo.Name) ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + repo.Name) }
func DeployKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) { ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys") ctx.Data["PageIsSettingsKeys"] = true keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID) if err != nil { ctx.Handle(500, "ListDeployKeys", err) return } ctx.Data["Deploykeys"] = keys if ctx.HasError() { ctx.HTML(200, DEPLOY_KEYS) return } content, err := models.CheckPublicKeyString(form.Content) if err != nil { if models.IsErrKeyUnableVerify(err) { ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key")) } else { ctx.Data["HasError"] = true ctx.Data["Err_Content"] = true ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error())) ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys") 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.Data["Err_Content"] = true ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), DEPLOY_KEYS, &form) case models.IsErrKeyNameAlreadyUsed(err): ctx.Data["Err_Title"] = true ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), DEPLOY_KEYS, &form) default: ctx.Handle(500, "AddDeployKey", err) } return } log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID) ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", key.Name)) ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys") }
func SlackHooksNewPost(ctx *context.Context, form auth.NewSlackHookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksNew"] = true ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}} orCtx, err := getOrgRepoCtx(ctx) if err != nil { ctx.Handle(500, "getOrgRepoCtx", err) return } if ctx.HasError() { ctx.HTML(200, orCtx.NewTemplate) return } meta, err := json.Marshal(&models.SlackMeta{ Channel: form.Channel, Username: form.Username, IconURL: form.IconURL, Color: form.Color, }) if err != nil { ctx.Handle(500, "Marshal", err) return } w := &models.Webhook{ RepoID: orCtx.RepoID, URL: form.PayloadURL, ContentType: models.JSON, HookEvent: ParseHookEvent(form.WebhookForm), IsActive: form.Active, HookTaskType: models.SLACK, Meta: string(meta), OrgID: orCtx.OrgID, } if err := w.UpdateEvent(); err != nil { ctx.Handle(500, "UpdateEvent", err) return } else if err := models.CreateWebhook(w); err != nil { ctx.Handle(500, "CreateWebhook", err) return } ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success")) ctx.Redirect(orCtx.Link + "/settings/hooks") }
func EditAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) { ctx.Data["Title"] = ctx.Tr("admin.auths.edit") ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdminAuthentications"] = true ctx.Data["SMTPAuths"] = models.SMTPAuths source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid")) if err != nil { ctx.Handle(500, "GetLoginSourceByID", err) return } ctx.Data["Source"] = source if ctx.HasError() { ctx.HTML(200, AUTH_EDIT) return } var config core.Conversion switch models.LoginType(form.Type) { case models.LOGIN_LDAP, models.LOGIN_DLDAP: config = parseLDAPConfig(form) case models.LOGIN_SMTP: config = parseSMTPConfig(form) case models.LOGIN_PAM: config = &models.PAMConfig{ ServiceName: form.PAMServiceName, } default: ctx.Error(400) return } source.Name = form.Name source.IsActived = form.IsActive source.Cfg = config if err := models.UpdateSource(source); err != nil { ctx.Handle(500, "UpdateSource", err) return } log.Trace("Authentication changed by admin(%s): %s", ctx.User.Name, source.ID) ctx.Flash.Success(ctx.Tr("admin.auths.update_success")) ctx.Redirect(setting.AppSubUrl + "/admin/auths/" + com.ToStr(form.ID)) }
func EditTeamPost(ctx *context.Context, form auth.CreateTeamForm) { t := ctx.Org.Team ctx.Data["Title"] = ctx.Org.Organization.FullName ctx.Data["PageIsOrgTeams"] = true ctx.Data["Team"] = t if ctx.HasError() { ctx.HTML(200, TEAM_NEW) return } isAuthChanged := false if !t.IsOwnerTeam() { // Validate permission level. var auth models.AccessMode switch form.Permission { case "read": auth = models.ACCESS_MODE_READ case "write": auth = models.ACCESS_MODE_WRITE case "admin": auth = models.ACCESS_MODE_ADMIN default: ctx.Error(401) return } t.Name = form.TeamName if t.Authorize != auth { isAuthChanged = true t.Authorize = auth } } t.Description = form.Description if err := models.UpdateTeam(t, isAuthChanged); err != nil { ctx.Data["Err_TeamName"] = true switch { case models.IsErrTeamAlreadyExist(err): ctx.RenderWithErr(ctx.Tr("form.team_name_been_taken"), TEAM_NEW, &form) default: ctx.Handle(500, "UpdateTeam", err) } return } ctx.Redirect(ctx.Org.OrgLink + "/teams/" + t.LowerName) }
func EditWikiPost(ctx *context.Context, form auth.NewWikiForm) { ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page") ctx.Data["PageIsWiki"] = true ctx.Data["RequireSimpleMDE"] = true if ctx.HasError() { ctx.HTML(200, WIKI_NEW) return } if err := ctx.Repo.Repository.EditWikiPage(ctx.User, form.OldTitle, form.Title, form.Content, form.Message); err != nil { ctx.Handle(500, "EditWikiPage", err) return } ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + models.ToWikiPageURL(form.Title)) }
func SettingsSSHKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSSHKeys"] = true keys, err := models.ListPublicKeys(ctx.User.Id) if err != nil { ctx.Handle(500, "ListPublicKeys", err) return } ctx.Data["Keys"] = keys if ctx.HasError() { ctx.HTML(200, SETTINGS_SSH_KEYS) return } content, err := models.CheckPublicKeyString(form.Content) if err != nil { if models.IsErrKeyUnableVerify(err) { ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key")) } else { ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error())) ctx.Redirect(setting.AppSubUrl + "/user/settings/ssh") return } } if _, err = models.AddPublicKey(ctx.User.Id, form.Title, content); err != nil { ctx.Data["HasError"] = true switch { case models.IsErrKeyAlreadyExist(err): ctx.Data["Err_Content"] = true ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), SETTINGS_SSH_KEYS, &form) case models.IsErrKeyNameAlreadyUsed(err): ctx.Data["Err_Title"] = true ctx.RenderWithErr(ctx.Tr("settings.ssh_key_name_used"), SETTINGS_SSH_KEYS, &form) default: ctx.Handle(500, "AddPublicKey", err) } return } ctx.Flash.Success(ctx.Tr("settings.add_key_success", form.Title)) ctx.Redirect(setting.AppSubUrl + "/user/settings/ssh") }
func WebHooksNewPost(ctx *context.Context, form auth.NewWebhookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksNew"] = true ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}} ctx.Data["HookType"] = "gogs" orCtx, err := getOrgRepoCtx(ctx) if err != nil { ctx.Handle(500, "getOrgRepoCtx", err) return } ctx.Data["BaseLink"] = orCtx.Link if ctx.HasError() { ctx.HTML(200, orCtx.NewTemplate) return } contentType := models.JSON if models.HookContentType(form.ContentType) == models.FORM { contentType = models.FORM } w := &models.Webhook{ RepoID: orCtx.RepoID, URL: form.PayloadURL, ContentType: contentType, Secret: form.Secret, HookEvent: ParseHookEvent(form.WebhookForm), IsActive: form.Active, HookTaskType: models.GOGS, OrgID: orCtx.OrgID, } if err := w.UpdateEvent(); err != nil { ctx.Handle(500, "UpdateEvent", err) return } else if err := models.CreateWebhook(w); err != nil { ctx.Handle(500, "CreateWebhook", err) return } ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success")) ctx.Redirect(orCtx.Link + "/settings/hooks") }
func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) { ctx.Data["Title"] = ctx.Tr("repo.issues.new") ctx.Data["PageIsIssueList"] = true renderAttachmentSettings(ctx) var ( repo = ctx.Repo.Repository attachments []string ) labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, form) if ctx.Written() { return } if setting.AttachmentEnabled { attachments = form.Attachments } if ctx.HasError() { ctx.HTML(200, ISSUE_NEW) return } issue := &models.Issue{ RepoID: repo.ID, Name: form.Title, PosterID: ctx.User.Id, Poster: ctx.User, MilestoneID: milestoneID, AssigneeID: assigneeID, Content: form.Content, } if err := models.NewIssue(repo, issue, labelIDs, attachments); err != nil { ctx.Handle(500, "NewIssue", err) return } else if err := MailWatchersAndMentions(ctx, issue); err != nil { ctx.Handle(500, "MailWatchersAndMentions", err) return } log.Trace("Issue created: %d/%d", repo.ID, issue.ID) ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index)) }
func NewAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) { ctx.Data["Title"] = ctx.Tr("admin.auths.new") ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdminAuthentications"] = true ctx.Data["CurTypeName"] = models.LoginNames[models.LoginType(form.Type)] ctx.Data["AuthSources"] = authSources ctx.Data["SMTPAuths"] = models.SMTPAuths if ctx.HasError() { ctx.HTML(200, AUTH_NEW) return } var config core.Conversion switch models.LoginType(form.Type) { case models.LOGIN_LDAP, models.LOGIN_DLDAP: config = parseLDAPConfig(form) case models.LOGIN_SMTP: config = parseSMTPConfig(form) case models.LOGIN_PAM: config = &models.PAMConfig{ ServiceName: form.PAMServiceName, } default: ctx.Error(400) return } if err := models.CreateSource(&models.LoginSource{ Type: models.LoginType(form.Type), Name: form.Name, IsActived: form.IsActive, Cfg: config, }); err != nil { ctx.Handle(500, "CreateSource", err) return } log.Trace("Authentication created by admin(%s): %s", ctx.User.Name, form.Name) ctx.Flash.Success(ctx.Tr("admin.auths.new_success", form.Name)) ctx.Redirect(setting.AppSubUrl + "/admin/auths") }
func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { ctx.Data["Title"] = ctx.Tr("repo.milestones.edit") ctx.Data["PageIsMilestones"] = true ctx.Data["PageIsEditMilestone"] = true ctx.Data["RequireDatetimepicker"] = true ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language()) if ctx.HasError() { ctx.HTML(200, MILESTONE_NEW) return } if len(form.Deadline) == 0 { form.Deadline = "9999-12-31" } deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local) if err != nil { ctx.Data["Err_Deadline"] = true ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &form) return } m, err := models.GetMilestoneByID(ctx.ParamsInt64(":id")) if err != nil { if models.IsErrMilestoneNotExist(err) { ctx.Handle(404, "GetMilestoneByID", nil) } else { ctx.Handle(500, "GetMilestoneByID", err) } return } m.Name = form.Title m.Content = form.Content m.Deadline = deadline if err = models.UpdateMilestone(m); err != nil { ctx.Handle(500, "UpdateMilestone", err) return } ctx.Flash.Success(ctx.Tr("repo.milestones.edit_success", m.Name)) ctx.Redirect(ctx.Repo.RepoLink + "/milestones") }
func SlackHooksEditPost(ctx *context.Context, form auth.NewSlackHookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksEdit"] = true orCtx, w := checkWebhook(ctx) if ctx.Written() { return } ctx.Data["Webhook"] = w if ctx.HasError() { ctx.HTML(200, orCtx.NewTemplate) return } meta, err := json.Marshal(&models.SlackMeta{ Channel: form.Channel, Username: form.Username, IconURL: form.IconURL, Color: form.Color, }) if err != nil { ctx.Handle(500, "Marshal", err) return } w.URL = form.PayloadURL w.Meta = string(meta) w.HookEvent = ParseHookEvent(form.WebhookForm) w.IsActive = form.Active if err := w.UpdateEvent(); err != nil { ctx.Handle(500, "UpdateEvent", err) return } else if err := models.UpdateWebhook(w); err != nil { ctx.Handle(500, "UpdateWebhook", err) return } ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success")) ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) }
func CreatePost(ctx *context.Context, form auth.CreateRepoForm) { ctx.Data["Title"] = ctx.Tr("new_repo") ctx.Data["Gitignores"] = models.Gitignores ctx.Data["Licenses"] = models.Licenses ctx.Data["Readmes"] = models.Readmes ctxUser := checkContextUser(ctx, form.Uid) if ctx.Written() { return } ctx.Data["ContextUser"] = ctxUser if ctx.HasError() { ctx.HTML(200, CREATE) return } repo, err := models.CreateRepository(ctxUser, models.CreateRepoOptions{ Name: form.RepoName, Description: form.Description, Gitignores: form.Gitignores, License: form.License, Readme: form.Readme, IsPrivate: form.Private || setting.Repository.ForcePrivate, AutoInit: form.AutoInit, }) if err == nil { log.Trace("Repository created[%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name) ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + repo.Name) return } if repo != nil { if errDelete := models.DeleteRepository(ctxUser.Id, repo.ID); errDelete != nil { log.Error(4, "DeleteRepository: %v", errDelete) } } handleCreateError(ctx, ctxUser, err, "CreatePost", CREATE, &form) }
func NewLabel(ctx *context.Context, form auth.CreateLabelForm) { ctx.Data["Title"] = ctx.Tr("repo.labels") ctx.Data["PageIsLabels"] = true if ctx.HasError() { ctx.Flash.Error(ctx.Data["ErrorMsg"].(string)) ctx.Redirect(ctx.Repo.RepoLink + "/labels") return } l := &models.Label{ RepoID: ctx.Repo.Repository.ID, Name: form.Title, Color: form.Color, } if err := models.NewLabel(l); err != nil { ctx.Handle(500, "NewLabel", err) return } ctx.Redirect(ctx.Repo.RepoLink + "/labels") }
func SignInPost(ctx *context.Context, form auth.SignInForm) { ctx.Data["Title"] = ctx.Tr("sign_in") if ctx.HasError() { ctx.HTML(200, SIGNIN) return } u, err := models.UserSignIn(form.UserName, form.Password) if err != nil { if models.IsErrUserNotExist(err) { ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), SIGNIN, &form) } else { ctx.Handle(500, "UserSignIn", err) } return } if form.Remember { days := 86400 * setting.LogInRememberDays ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubUrl) ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd), setting.CookieRememberName, u.Name, days, setting.AppSubUrl) } ctx.Session.Set("uid", u.Id) ctx.Session.Set("uname", u.Name) // Clear whatever CSRF has right now, force to generate a new one ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubUrl) if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 { ctx.SetCookie("redirect_to", "", -1, setting.AppSubUrl) ctx.Redirect(redirectTo) return } ctx.Redirect(setting.AppSubUrl + "/") }
func NewWikiPost(ctx *context.Context, form auth.NewWikiForm) { ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page") ctx.Data["PageIsWiki"] = true ctx.Data["RequireSimpleMDE"] = true if ctx.HasError() { ctx.HTML(200, WIKI_NEW) return } if err := ctx.Repo.Repository.AddWikiPage(ctx.User, form.Title, form.Content, form.Message); err != nil { if models.IsErrWikiAlreadyExist(err) { ctx.Data["Err_Title"] = true ctx.RenderWithErr(ctx.Tr("repo.wiki.page_already_exists"), WIKI_NEW, &form) } else { ctx.Handle(500, "AddWikiPage", err) } return } ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + models.ToWikiPageURL(form.Title)) }
func WebHooksEditPost(ctx *context.Context, form auth.NewWebhookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksEdit"] = true orCtx, w := checkWebhook(ctx) if ctx.Written() { return } ctx.Data["Webhook"] = w if ctx.HasError() { ctx.HTML(200, orCtx.NewTemplate) return } contentType := models.JSON if models.HookContentType(form.ContentType) == models.FORM { contentType = models.FORM } w.URL = form.PayloadURL w.ContentType = contentType w.Secret = form.Secret w.HookEvent = ParseHookEvent(form.WebhookForm) w.IsActive = form.Active if err := w.UpdateEvent(); err != nil { ctx.Handle(500, "UpdateEvent", err) return } else if err := models.UpdateWebhook(w); err != nil { ctx.Handle(500, "WebHooksEditPost", err) return } ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success")) ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) }
func EditReleasePost(ctx *context.Context, form auth.EditReleaseForm) { ctx.Data["Title"] = ctx.Tr("repo.release.edit_release") ctx.Data["PageIsReleaseList"] = true ctx.Data["PageIsEditRelease"] = true tagName := ctx.Params(":tagname") rel, err := models.GetRelease(ctx.Repo.Repository.ID, tagName) if err != nil { if models.IsErrReleaseNotExist(err) { ctx.Handle(404, "GetRelease", err) } else { ctx.Handle(500, "GetRelease", err) } return } ctx.Data["tag_name"] = rel.TagName ctx.Data["tag_target"] = rel.Target ctx.Data["title"] = rel.Title ctx.Data["content"] = rel.Note ctx.Data["prerelease"] = rel.IsPrerelease if ctx.HasError() { ctx.HTML(200, RELEASE_NEW) return } rel.Title = form.Title rel.Note = form.Content rel.IsDraft = len(form.Draft) > 0 rel.IsPrerelease = form.Prerelease if err = models.UpdateRelease(ctx.Repo.GitRepo, rel); err != nil { ctx.Handle(500, "UpdateRelease", err) return } ctx.Redirect(ctx.Repo.RepoLink + "/releases") }
func InstallPost(ctx *context.Context, form auth.InstallForm) { ctx.Data["CurDbOption"] = form.DbType if ctx.HasError() { if ctx.HasValue("Err_SMTPEmail") { ctx.Data["Err_SMTP"] = true } if ctx.HasValue("Err_AdminName") || ctx.HasValue("Err_AdminPasswd") || ctx.HasValue("Err_AdminEmail") { ctx.Data["Err_Admin"] = true } ctx.HTML(200, INSTALL) return } if _, err := exec.LookPath("git"); err != nil { ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), INSTALL, &form) return } // Pass basic check, now test configuration. // Test database setting. dbTypes := map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "SQLite3": "sqlite3", "TiDB": "tidb"} models.DbCfg.Type = dbTypes[form.DbType] models.DbCfg.Host = form.DbHost models.DbCfg.User = form.DbUser models.DbCfg.Passwd = form.DbPasswd models.DbCfg.Name = form.DbName models.DbCfg.SSLMode = form.SSLMode models.DbCfg.Path = form.DbPath if (models.DbCfg.Type == "sqlite3" || models.DbCfg.Type == "tidb") && len(models.DbCfg.Path) == 0 { ctx.Data["Err_DbPath"] = true ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), INSTALL, &form) return } else if models.DbCfg.Type == "tidb" && strings.ContainsAny(path.Base(models.DbCfg.Path), ".-") { ctx.Data["Err_DbPath"] = true ctx.RenderWithErr(ctx.Tr("install.err_invalid_tidb_name"), INSTALL, &form) return } // Set test engine. var x *xorm.Engine if err := models.NewTestEngine(x); err != nil { if strings.Contains(err.Error(), `Unknown database type: sqlite3`) { ctx.Data["Err_DbType"] = true ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "http://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &form) } else { ctx.Data["Err_DbSetting"] = true ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), INSTALL, &form) } return } // Test repository root path. form.RepoRootPath = strings.Replace(form.RepoRootPath, "\\", "/", -1) if err := os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil { ctx.Data["Err_RepoRootPath"] = true ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), INSTALL, &form) return } // Test log root path. form.LogRootPath = strings.Replace(form.LogRootPath, "\\", "/", -1) if err := os.MkdirAll(form.LogRootPath, os.ModePerm); err != nil { ctx.Data["Err_LogRootPath"] = true ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), INSTALL, &form) return } // Check run user. curUser := user.CurrentUsername() if form.RunUser != curUser { ctx.Data["Err_RunUser"] = true ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, curUser), INSTALL, &form) return } // Check logic loophole between disable self-registration and no admin account. if form.DisableRegistration && len(form.AdminName) == 0 { ctx.Data["Err_Services"] = true ctx.Data["Err_Admin"] = true ctx.RenderWithErr(ctx.Tr("install.no_admin_and_disable_registration"), INSTALL, form) return } // Check admin password. if len(form.AdminName) > 0 && len(form.AdminPasswd) == 0 { ctx.Data["Err_Admin"] = true ctx.Data["Err_AdminPasswd"] = true ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_password"), INSTALL, form) return } if form.AdminPasswd != form.AdminConfirmPasswd { ctx.Data["Err_Admin"] = true ctx.Data["Err_AdminPasswd"] = true ctx.RenderWithErr(ctx.Tr("form.password_not_match"), INSTALL, form) return } if form.AppUrl[len(form.AppUrl)-1] != '/' { form.AppUrl += "/" } // Save settings. cfg := ini.Empty() if com.IsFile(setting.CustomConf) { // Keeps custom settings if there is already something. if err := cfg.Append(setting.CustomConf); err != nil { log.Error(4, "Fail to load custom conf '%s': %v", setting.CustomConf, err) } } cfg.Section("database").Key("DB_TYPE").SetValue(models.DbCfg.Type) cfg.Section("database").Key("HOST").SetValue(models.DbCfg.Host) cfg.Section("database").Key("NAME").SetValue(models.DbCfg.Name) cfg.Section("database").Key("USER").SetValue(models.DbCfg.User) cfg.Section("database").Key("PASSWD").SetValue(models.DbCfg.Passwd) cfg.Section("database").Key("SSL_MODE").SetValue(models.DbCfg.SSLMode) cfg.Section("database").Key("PATH").SetValue(models.DbCfg.Path) cfg.Section("").Key("APP_NAME").SetValue(form.AppName) cfg.Section("repository").Key("ROOT").SetValue(form.RepoRootPath) cfg.Section("").Key("RUN_USER").SetValue(form.RunUser) cfg.Section("server").Key("DOMAIN").SetValue(form.Domain) cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort) cfg.Section("server").Key("ROOT_URL").SetValue(form.AppUrl) if form.SSHPort == 0 { cfg.Section("server").Key("DISABLE_SSH").SetValue("true") } else { cfg.Section("server").Key("DISABLE_SSH").SetValue("false") cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(form.SSHPort)) } if len(strings.TrimSpace(form.SMTPHost)) > 0 { cfg.Section("mailer").Key("ENABLED").SetValue("true") cfg.Section("mailer").Key("HOST").SetValue(form.SMTPHost) cfg.Section("mailer").Key("FROM").SetValue(form.SMTPFrom) cfg.Section("mailer").Key("USER").SetValue(form.SMTPEmail) cfg.Section("mailer").Key("PASSWD").SetValue(form.SMTPPasswd) } else { cfg.Section("mailer").Key("ENABLED").SetValue("false") } cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm)) cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify)) cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(form.OfflineMode)) cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(form.DisableGravatar)) cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(form.DisableRegistration)) cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(form.EnableCaptcha)) cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(form.RequireSignInView)) cfg.Section("").Key("RUN_MODE").SetValue("prod") cfg.Section("session").Key("PROVIDER").SetValue("file") cfg.Section("log").Key("MODE").SetValue("file") cfg.Section("log").Key("LEVEL").SetValue("Info") cfg.Section("log").Key("ROOT_PATH").SetValue(form.LogRootPath) cfg.Section("security").Key("INSTALL_LOCK").SetValue("true") cfg.Section("security").Key("SECRET_KEY").SetValue(base.GetRandomString(15)) os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm) if err := cfg.SaveTo(setting.CustomConf); err != nil { ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), INSTALL, &form) return } GlobalInit() // Create admin account if len(form.AdminName) > 0 { u := &models.User{ Name: form.AdminName, Email: form.AdminEmail, Passwd: form.AdminPasswd, IsAdmin: true, IsActive: true, } if err := models.CreateUser(u); err != nil { if !models.IsErrUserAlreadyExist(err) { setting.InstallLock = false ctx.Data["Err_AdminName"] = true ctx.Data["Err_AdminEmail"] = true ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), INSTALL, &form) return } log.Info("Admin account already exist") u, _ = models.GetUserByName(u.Name) } // Auto-login for admin ctx.Session.Set("uid", u.Id) ctx.Session.Set("uname", u.Name) } log.Info("First-time run install finished!") ctx.Flash.Success(ctx.Tr("install.install_success")) ctx.Redirect(form.AppUrl + "user/login") }
func NewComment(ctx *context.Context, form auth.CreateCommentForm) { issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { ctx.Handle(404, "GetIssueByIndex", err) } else { ctx.Handle(500, "GetIssueByIndex", err) } return } if issue.IsPull { if err = issue.GetPullRequest(); err != nil { ctx.Handle(500, "GetPullRequest", err) return } } var attachments []string if setting.AttachmentEnabled { attachments = form.Attachments } if ctx.HasError() { ctx.Flash.Error(ctx.Data["ErrorMsg"].(string)) ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index)) return } var comment *models.Comment defer func() { // Check if issue admin/poster changes the status of issue. if (ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.Id))) && (form.Status == "reopen" || form.Status == "close") && !(issue.IsPull && issue.HasMerged) { // Duplication and conflict check should apply to reopen pull request. var pr *models.PullRequest if form.Status == "reopen" && issue.IsPull { pull := issue.PullRequest pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch) if err != nil { if !models.IsErrPullRequestNotExist(err) { ctx.Handle(500, "GetUnmergedPullRequest", err) return } } // Regenerate patch and test conflict. if pr == nil { if err = issue.UpdatePatch(); err != nil { ctx.Handle(500, "UpdatePatch", err) return } issue.AddToTaskQueue() } } if pr != nil { ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index)) } else { if err = issue.ChangeStatus(ctx.User, ctx.Repo.Repository, form.Status == "close"); err != nil { log.Error(4, "ChangeStatus: %v", err) } else { log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed) } } } // Redirect to comment hashtag if there is any actual content. typeName := "issues" if issue.IsPull { typeName = "pulls" } if comment != nil { ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag())) } else { ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index)) } }() // Fix #321: Allow empty comments, as long as we have attachments. if len(form.Content) == 0 && len(attachments) == 0 { return } comment, err = models.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments) if err != nil { ctx.Handle(500, "CreateIssueComment", err) return } MailWatchersAndMentions(ctx, &models.Issue{ ID: issue.ID, Index: issue.Index, Name: issue.Name, Content: form.Content, }) if ctx.Written() { return } log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID) }