func SignInPost(ctx *middleware.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) 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 SettingsDelete(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("org.settings") ctx.Data["PageIsSettingsDelete"] = true org := ctx.Org.Organization if ctx.Req.Method == "POST" { if _, err := models.UserSignIn(ctx.User.Name, ctx.Query("password")); err != nil { if models.IsErrUserNotExist(err) { ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_password"), SETTINGS_DELETE, nil) } else { ctx.Handle(500, "UserSignIn", err) } return } if err := models.DeleteOrganization(org); err != nil { if models.IsErrUserOwnRepos(err) { ctx.Flash.Error(ctx.Tr("form.org_still_own_repo")) ctx.Redirect(org.HomeLink() + "/settings/delete") } else { ctx.Handle(500, "DeleteOrganization", err) } } else { log.Trace("Organization deleted: %s", org.Name) ctx.Redirect(setting.AppSubUrl + "/") } return } ctx.HTML(200, SETTINGS_DELETE) }
func EditUserPost(ctx *middleware.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.IsActive = form.Active u.IsAdmin = form.Admin u.AllowGitHook = form.AllowGitHook 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 NewTeamPost(ctx *middleware.Context, form auth.CreateTeamForm) { ctx.Data["Title"] = ctx.Org.Organization.FullName ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeamsNew"] = true ctx.Data["Team"] = &models.Team{} if ctx.HasError() { ctx.HTML(200, TEAM_NEW) return } // 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 } org := ctx.Org.Organization t := &models.Team{ OrgID: org.Id, Name: form.TeamName, Description: form.Description, Authorize: auth, } if err := models.NewTeam(t); err != nil { switch err { case models.ErrTeamNameIllegal: ctx.Data["Err_TeamName"] = true ctx.RenderWithErr(ctx.Tr("form.illegal_team_name"), TEAM_NEW, &form) case models.ErrTeamAlreadyExist: ctx.Data["Err_TeamName"] = true 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", org.Name, t.Name) ctx.Redirect(ctx.Org.OrgLink + "/teams/" + t.LowerName) }
func DeployKeysPost(ctx *middleware.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 err == models.ErrKeyUnableVerify { 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 } } if err = models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content); 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", form.Title)) ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys") }
func SettingsPost(ctx *middleware.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 } 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) 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(org.HomeLink() + "/settings") }
func EditTeamPost(ctx *middleware.Context, form auth.CreateTeamForm) { t := ctx.Org.Team ctx.Data["Title"] = ctx.Org.Organization.FullName ctx.Data["PageIsOrgTeams"] = true ctx.Data["team_name"] = t.Name ctx.Data["desc"] = t.Description 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 { if err == models.ErrTeamNameIllegal { ctx.Data["Err_TeamName"] = true ctx.RenderWithErr(ctx.Tr("form.illegal_team_name"), TEAM_NEW, &form) } else { ctx.Handle(500, "UpdateTeam", err) } return } ctx.Redirect(ctx.Org.OrgLink + "/teams/" + t.LowerName) }
func MigratePost(ctx *middleware.Context, form auth.MigrateRepoForm) { ctx.Data["Title"] = ctx.Tr("new_migrate") ctxUser := checkContextUser(ctx, form.Uid) if ctx.Written() { return } ctx.Data["ContextUser"] = ctxUser if ctx.HasError() { ctx.HTML(200, MIGRATE) return } // Remote address can be HTTP/HTTPS/Git URL or local path. // Note: remember to change api/v1/repo.go: MigrateRepo // FIXME: merge these two functions with better error handling remoteAddr := form.CloneAddr if strings.HasPrefix(form.CloneAddr, "http://") || strings.HasPrefix(form.CloneAddr, "https://") || strings.HasPrefix(form.CloneAddr, "git://") { u, err := url.Parse(form.CloneAddr) if err != nil { ctx.Data["Err_CloneAddr"] = true ctx.RenderWithErr(ctx.Tr("form.url_error"), MIGRATE, &form) return } if len(form.AuthUsername) > 0 || len(form.AuthPassword) > 0 { u.User = url.UserPassword(form.AuthUsername, form.AuthPassword) } remoteAddr = u.String() } else if !com.IsDir(remoteAddr) { ctx.Data["Err_CloneAddr"] = true ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), MIGRATE, &form) return } repo, err := models.MigrateRepository(ctxUser, form.RepoName, form.Description, form.Private, form.Mirror, remoteAddr) if err == nil { log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName) ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + form.RepoName) return } if repo != nil { if errDelete := models.DeleteRepository(ctxUser.Id, repo.ID); errDelete != nil { log.Error(4, "DeleteRepository: %v", errDelete) } } if strings.Contains(err.Error(), "Authentication failed") || strings.Contains(err.Error(), " not found") || strings.Contains(err.Error(), "could not read Username") { ctx.Data["Err_Auth"] = true ctx.RenderWithErr(ctx.Tr("form.auth_failed", strings.Replace(err.Error(), ":"+form.AuthPassword+"@", ":<password>@", 1)), MIGRATE, &form) return } handleCreateError(ctx, err, "MigratePost", MIGRATE, &form) }
func CreatePost(ctx *middleware.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.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 ForgotPasswdPost(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("auth.forgot_password") if setting.MailService == nil { ctx.Handle(403, "ForgotPasswdPost", nil) return } ctx.Data["IsResetRequest"] = true email := ctx.Query("email") ctx.Data["Email"] = email u, err := models.GetUserByEmail(email) if err != nil { if models.IsErrUserNotExist(err) { ctx.Data["Err_Email"] = true ctx.RenderWithErr(ctx.Tr("auth.email_not_associate"), FORGOT_PASSWORD, nil) } else { ctx.Handle(500, "user.ResetPasswd(check existence)", err) } return } if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) { ctx.Data["ResendLimited"] = true ctx.HTML(200, FORGOT_PASSWORD) return } mailer.SendResetPasswordMail(ctx.Context, u) if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { log.Error(4, "Set cache(MailResendLimit) fail: %v", err) } ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60 ctx.Data["IsResetSent"] = true ctx.HTML(200, FORGOT_PASSWORD) }
func ResetPasswdPost(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("auth.reset_password") code := ctx.Query("code") if len(code) == 0 { ctx.Error(404) return } ctx.Data["Code"] = code if u := models.VerifyUserActiveCode(code); u != nil { // Validate password length. passwd := ctx.Query("password") if len(passwd) < 6 { ctx.Data["IsResetForm"] = true ctx.Data["Err_Password"] = true ctx.RenderWithErr(ctx.Tr("auth.password_too_short"), RESET_PASSWORD, nil) return } u.Passwd = passwd u.Rands = models.GetUserSalt() u.Salt = models.GetUserSalt() u.EncodePasswd() if err := models.UpdateUser(u); err != nil { ctx.Handle(500, "UpdateUser", err) return } log.Trace("User password reset: %s", u.Name) ctx.Redirect(setting.AppSubUrl + "/user/login") return } ctx.Data["IsResetFailed"] = true ctx.HTML(200, RESET_PASSWORD) }
func handleCreateError(ctx *middleware.Context, err error, name string, tpl base.TplName, form interface{}) { switch { case models.IsErrRepoAlreadyExist(err): ctx.Data["Err_RepoName"] = true ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tpl, form) case models.IsErrNameReserved(err): ctx.Data["Err_RepoName"] = true ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form) case models.IsErrNamePatternNotAllowed(err): ctx.Data["Err_RepoName"] = true ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form) default: ctx.Handle(500, name, err) } }
func SignUpPost(ctx *middleware.Context, cpt *captcha.Captcha, form auth.RegisterForm) { ctx.Data["Title"] = ctx.Tr("sign_up") ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha if setting.Service.DisableRegistration { ctx.Error(403) return } if ctx.HasError() { ctx.HTML(200, SIGNUP) return } if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) { ctx.Data["Err_Captcha"] = true ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), SIGNUP, &form) return } if form.Password != form.Retype { ctx.Data["Err_Password"] = true ctx.RenderWithErr(ctx.Tr("form.password_not_match"), SIGNUP, &form) return } u := &models.User{ Name: form.UserName, Email: form.Email, Passwd: form.Password, IsActive: !setting.Service.RegisterEmailConfirm, } 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"), SIGNUP, &form) case models.IsErrEmailAlreadyUsed(err): ctx.Data["Err_Email"] = true ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SIGNUP, &form) case models.IsErrNameReserved(err): ctx.Data["Err_UserName"] = true ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &form) case models.IsErrNamePatternNotAllowed(err): ctx.Data["Err_UserName"] = true ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SIGNUP, &form) default: ctx.Handle(500, "CreateUser", err) } return } log.Trace("Account created: %s", u.Name) // Auto-set admin for the only user. if models.CountUsers() == 1 { u.IsAdmin = true u.IsActive = true if err := models.UpdateUser(u); err != nil { ctx.Handle(500, "UpdateUser", err) return } } // Send confirmation e-mail, no need for social account. if setting.Service.RegisterEmailConfirm && u.Id > 1 { mailer.SendActivateAccountMail(ctx.Context, u) ctx.Data["IsSendRegisterMail"] = true ctx.Data["Email"] = u.Email ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60 ctx.HTML(200, ACTIVATE) if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { log.Error(4, "Set cache(MailResendLimit) fail: %v", err) } return } ctx.Redirect(setting.AppSubUrl + "/user/login") }
func SettingsPost(ctx *middleware.Context, form auth.RepoSettingForm) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsOptions"] = true repo := ctx.Repo.Repository switch ctx.Query("action") { case "update": if ctx.HasError() { ctx.HTML(200, SETTINGS_OPTIONS) return } isNameChanged := false oldRepoName := repo.Name newRepoName := form.RepoName // Check if repository name has been changed. if repo.LowerName != strings.ToLower(newRepoName) { isNameChanged = true if err := models.ChangeRepositoryName(ctx.Repo.Owner, repo.Name, newRepoName); err != nil { ctx.Data["Err_RepoName"] = true switch { case models.IsErrRepoAlreadyExist(err): ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), SETTINGS_OPTIONS, &form) case models.IsErrNameReserved(err): ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), SETTINGS_OPTIONS, &form) case models.IsErrNamePatternNotAllowed(err): ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SETTINGS_OPTIONS, &form) default: ctx.Handle(500, "ChangeRepositoryName", err) } return } log.Trace("Repository name changed: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newRepoName) } // In case it's just a case change. repo.Name = newRepoName repo.LowerName = strings.ToLower(newRepoName) if ctx.Repo.GitRepo.IsBranchExist(form.Branch) { repo.DefaultBranch = form.Branch } repo.Description = form.Description repo.Website = form.Website visibilityChanged := repo.IsPrivate != form.Private repo.IsPrivate = form.Private if err := models.UpdateRepository(repo, visibilityChanged); err != nil { ctx.Handle(500, "UpdateRepository", err) return } log.Trace("Repository updated: %s/%s", ctx.Repo.Owner.Name, repo.Name) if isNameChanged { if err := models.RenameRepoAction(ctx.User, oldRepoName, repo); err != nil { log.Error(4, "RenameRepoAction: %v", err) } } if repo.IsMirror { if form.Interval > 0 { ctx.Repo.Mirror.Interval = form.Interval ctx.Repo.Mirror.NextUpdate = time.Now().Add(time.Duration(form.Interval) * time.Hour) if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil { log.Error(4, "UpdateMirror: %v", err) } } } ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success")) ctx.Redirect(fmt.Sprintf("%s/%s/%s/settings", setting.AppSubUrl, ctx.Repo.Owner.Name, repo.Name)) case "transfer": if repo.Name != form.RepoName { ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) return } if ctx.Repo.Owner.IsOrganization() { if !ctx.Repo.Owner.IsOwnedBy(ctx.User.Id) { ctx.Error(404) return } } newOwner := ctx.Query("new_owner_name") isExist, err := models.IsUserExist(0, newOwner) if err != nil { ctx.Handle(500, "IsUserExist", err) return } else if !isExist { ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), SETTINGS_OPTIONS, nil) return } if err = models.TransferOwnership(ctx.User, newOwner, repo); err != nil { if models.IsErrRepoAlreadyExist(err) { ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), SETTINGS_OPTIONS, nil) } else { ctx.Handle(500, "TransferOwnership", err) } return } log.Trace("Repository transfered: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner) ctx.Flash.Success(ctx.Tr("repo.settings.transfer_succeed")) ctx.Redirect(setting.AppSubUrl + "/" + newOwner + "/" + repo.Name) case "delete": if repo.Name != form.RepoName { ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) return } if ctx.Repo.Owner.IsOrganization() { if !ctx.Repo.Owner.IsOwnedBy(ctx.User.Id) { ctx.Error(404) return } } if err := models.DeleteRepository(ctx.Repo.Owner.Id, repo.ID); err != nil { ctx.Handle(500, "DeleteRepository", err) return } log.Trace("Repository deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name) ctx.Redirect(ctx.Repo.Owner.DashboardLink()) } }
func NewUserPost(ctx *middleware.Context, form auth.AdminCrateUserForm) { ctx.Data["Title"] = ctx.Tr("admin.users.new_account") ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdminUsers"] = true sources, err := models.LoginSources() if err != nil { ctx.Handle(500, "LoginSources", err) return } ctx.Data["Sources"] = sources ctx.Data["CanSendEmail"] = setting.MailService != nil if ctx.HasError() { ctx.HTML(200, USER_NEW) return } u := &models.User{ Name: form.UserName, Email: form.Email, Passwd: form.Password, IsActive: true, LoginType: models.PLAIN, } if len(form.LoginType) > 0 { fields := strings.Split(form.LoginType, "-") if len(fields) == 2 { u.LoginType = models.LoginType(com.StrTo(fields[0]).MustInt()) u.LoginSource = com.StrTo(fields[1]).MustInt64() u.LoginName = form.LoginName } } 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, &form) case models.IsErrEmailAlreadyUsed(err): ctx.Data["Err_Email"] = true ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_NEW, &form) case models.IsErrNameReserved(err): ctx.Data["Err_UserName"] = true ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), USER_NEW, &form) 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, &form) default: ctx.Handle(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.Flash.Success(ctx.Tr("admin.users.new_success", u.Name)) ctx.Redirect(setting.AppSubUrl + "/admin/users/" + com.ToStr(u.Id)) }
func InstallPost(ctx *middleware.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. 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 } // 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("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 { if err := models.CreateUser(&models.User{ Name: form.AdminName, Email: form.AdminEmail, Passwd: form.AdminPasswd, IsAdmin: true, IsActive: true, }); 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") } } log.Info("First-time run install finished!") ctx.Flash.Success(ctx.Tr("install.install_success")) ctx.Redirect(form.AppUrl + "user/login") }