// GlobalInit is for global configuration reload-able. func GlobalInit() { setting.NewContext() log.Trace("Custom path: %s", setting.CustomPath) log.Trace("Log path: %s", setting.LogRootPath) models.LoadConfigs() NewServices() if setting.InstallLock { models.LoadRepoConfig() models.NewRepoContext() if err := models.NewEngine(); err != nil { log.Fatal(4, "Fail to initialize ORM engine: %v", err) } models.HasEngine = true cron.NewContext() models.InitDeliverHooks() log.NewGitLogger(path.Join(setting.LogRootPath, "http.log")) } if models.EnableSQLite3 { log.Info("SQLite3 Supported") } if models.EnableTidb { log.Info("TiDB Supported") } checkRunMode() }
func processMailQueue() { sender := &Sender{} for { select { case msg := <-mailQueue: log.Trace("New e-mail sending request %s: %s", msg.GetHeader("To"), msg.Info) if err := gomail.Send(sender, msg.Message); err != nil { log.Error(4, "Fail to send e-mails %s: %s - %v", msg.GetHeader("To"), msg.Info, err) } else { log.Trace("E-mails sent %s: %s", msg.GetHeader("To"), msg.Info) } } } }
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 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 Invitation(ctx *middleware.Context) { org := ctx.Org.Organization ctx.Data["Title"] = org.FullName ctx.Data["PageIsOrgMembers"] = true if ctx.Req.Method == "POST" { uname := ctx.Query("uname") u, err := models.GetUserByName(uname) if err != nil { if models.IsErrUserNotExist(err) { ctx.Flash.Error(ctx.Tr("form.user_not_exist")) ctx.Redirect(ctx.Org.OrgLink + "/invitations/new") } else { ctx.Handle(500, " GetUserByName", err) } return } if err = org.AddMember(u.Id); err != nil { ctx.Handle(500, " AddMember", err) return } log.Trace("New member added(%s): %s", org.Name, u.Name) ctx.Redirect(ctx.Org.OrgLink + "/members") return } ctx.HTML(200, MEMBER_INVITE) }
func DeleteUser(ctx *middleware.Context) { u, err := models.GetUserByID(ctx.ParamsInt64(":userid")) if err != nil { ctx.Handle(500, "GetUserByID", err) return } if err = models.DeleteUser(u); err != nil { switch { case models.IsErrUserOwnRepos(err): ctx.Flash.Error(ctx.Tr("admin.users.still_own_repo")) ctx.JSON(200, map[string]interface{}{ "redirect": setting.AppSubUrl + "/admin/users/" + ctx.Params(":userid"), }) case models.IsErrUserHasOrgs(err): ctx.Flash.Error(ctx.Tr("admin.users.still_has_org")) ctx.JSON(200, map[string]interface{}{ "redirect": setting.AppSubUrl + "/admin/users/" + ctx.Params(":userid"), }) default: ctx.Handle(500, "DeleteUser", err) } return } log.Trace("Account deleted by admin(%s): %s", ctx.User.Name, u.Name) ctx.Flash.Success(ctx.Tr("admin.users.deletion_success")) ctx.JSON(200, map[string]interface{}{ "redirect": setting.AppSubUrl + "/admin/users", }) }
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 DeleteRepo(ctx *middleware.Context) { user, err := models.GetUserByName(ctx.Params(":username")) if err != nil { if models.IsErrUserNotExist(err) { ctx.APIError(422, "", err) } else { ctx.APIError(500, "GetUserByName", err) } return } repo, err := models.GetRepositoryByName(user.Id, ctx.Params(":reponame")) if err != nil { if models.IsErrRepoNotExist(err) { ctx.Error(404) } else { ctx.APIError(500, "GetRepositoryByName", err) } return } if user.IsOrganization() && !user.IsOwnedBy(ctx.User.Id) { ctx.APIError(403, "", "Given user is not owner of organization.") return } if err := models.DeleteRepository(user.Id, repo.ID); err != nil { ctx.APIError(500, "DeleteRepository", err) return } log.Trace("Repository deleted: %s/%s", user.Name, repo.Name) ctx.Status(204) }
func (this *service) ServeHTTP(w http.ResponseWriter, r *http.Request) { urlPath := r.URL.Path hash := urlPath[strings.LastIndex(urlPath, "/")+1:] size := this.mustInt(r, 80, "s", "size") // default size = 80*80 avatar := New(hash, this.cacheDir) avatar.AlterImage = this.altImage if avatar.Expired() { if err := avatar.UpdateTimeout(time.Millisecond * 1000); err != nil { log.Trace("avatar update error: %v", err) return } } if modtime, err := avatar.Modtime(); err == nil { etag := fmt.Sprintf("size(%d)", size) if t, err := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); err == nil && modtime.Before(t.Add(1*time.Second)) && etag == r.Header.Get("If-None-Match") { h := w.Header() delete(h, "Content-Type") delete(h, "Content-Length") w.WriteHeader(http.StatusNotModified) return } w.Header().Set("Last-Modified", modtime.UTC().Format(http.TimeFormat)) w.Header().Set("ETag", etag) } w.Header().Set("Content-Type", "image/jpeg") if err := avatar.Encode(w, size); err != nil { log.Warn("avatar encode error: %v", err) w.WriteHeader(500) } }
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 (ls *Source) FindUserDN(name string) (string, bool) { l, err := ldapDial(ls) if err != nil { log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err) ls.Enabled = false return "", false } defer l.Close() log.Trace("Search for LDAP user: %s", name) if ls.BindDN != "" && ls.BindPassword != "" { err = l.Bind(ls.BindDN, ls.BindPassword) if err != nil { log.Debug("Failed to bind as BindDN[%s]: %v", ls.BindDN, err) return "", false } log.Trace("Bound as BindDN %s", ls.BindDN) } else { log.Trace("Proceeding with anonymous LDAP search.") } // A search for the user. userFilter := fmt.Sprintf(ls.Filter, name) log.Trace("Searching using filter %s", userFilter) search := ldap.NewSearchRequest( ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter, []string{}, nil) // Ensure we found a user sr, err := l.Search(search) if err != nil || len(sr.Entries) < 1 { log.Debug("Failed search using filter[%s]: %v", userFilter, err) return "", false } else if len(sr.Entries) > 1 { log.Debug("Filter '%s' returned more than one user.", userFilter) return "", false } userDN := sr.Entries[0].DN if userDN == "" { log.Error(4, "LDAP search was succesful, but found no DN!") return "", false } return userDN, true }
func DeleteNotice(ctx *middleware.Context) { id := ctx.ParamsInt64(":id") if err := models.DeleteNotice(id); err != nil { ctx.Handle(500, "DeleteNotice", err) return } log.Trace("System notice deleted by admin(%s): %d", ctx.User.Name, id) ctx.Flash.Success(ctx.Tr("admin.notices.delete_success")) ctx.Redirect("/admin/notices") }
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 Activate(ctx *middleware.Context) { code := ctx.Query("code") if len(code) == 0 { ctx.Data["IsActivatePage"] = true if ctx.User.IsActive { ctx.Error(404) return } // Resend confirmation e-mail. if setting.Service.RegisterEmailConfirm { if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) { ctx.Data["ResendLimited"] = true } else { ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60 mailer.SendActivateAccountMail(ctx.Context, ctx.User) if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil { log.Error(4, "Set cache(MailResendLimit) fail: %v", err) } } } else { ctx.Data["ServiceNotEnabled"] = true } ctx.HTML(200, ACTIVATE) return } // Verify code. if user := models.VerifyUserActiveCode(code); user != nil { user.IsActive = true user.Rands = models.GetUserSalt() if err := models.UpdateUser(user); err != nil { if models.IsErrUserNotExist(err) { ctx.Error(404) } else { ctx.Handle(500, "UpdateUser", err) } return } log.Trace("User activated: %s", user.Name) ctx.Session.Set("uid", user.Id) ctx.Session.Set("uname", user.Name) ctx.Redirect(setting.AppSubUrl + "/") return } ctx.Data["IsActivateFailed"] = true ctx.HTML(200, ACTIVATE) }
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 ActivateEmail(ctx *middleware.Context) { code := ctx.Query("code") email_string := ctx.Query("email") // Verify code. if email := models.VerifyActiveEmailCode(code, email_string); email != nil { if err := email.Activate(); err != nil { ctx.Handle(500, "ActivateEmail", err) } log.Trace("Email activated: %s", email.Email) ctx.Flash.Success(ctx.Tr("settings.add_email_successs")) } ctx.Redirect(setting.AppSubUrl + "/user/settings/email") return }
func EditAuthSourcePost(ctx *middleware.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.LDAP, models.DLDAP: config = parseLDAPConfig(form) case models.SMTP: config = parseSMTPConfig(form) case models.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 NewAuthSourcePost(ctx *middleware.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.LDAP, models.DLDAP: config = parseLDAPConfig(form) case models.SMTP: config = parseSMTPConfig(form) case models.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") }
// Note: get back time.Time from database Go sees it at UTC where they are really Local. // So this function makes correct timezone offset. func regulateTimeZone(t time.Time) time.Time { if !setting.UseMySQL { return t } zone := t.Local().Format("-0700") log.Trace("regulateTimeZone: %s - %s", t.Local(), zone) if len(zone) != 5 { return t } hour := com.StrTo(zone[2:3]).MustInt() minutes := com.StrTo(zone[3:5]).MustInt() if zone[0] == '-' { return t.Add(time.Duration(hour) * time.Hour).Add(time.Duration(minutes) * time.Minute) } return t.Add(-1 * time.Duration(hour) * time.Hour).Add(-1 * time.Duration(minutes) * time.Minute) }
func CreatePost(ctx *middleware.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, AutoInit: form.AutoInit, }) if err == nil { log.Trace("Repository created: %s/%s", 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, err, "CreatePost", CREATE, &form) }
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) }
// AutoSignIn reads cookie and try to auto-login. func AutoSignIn(ctx *Context) (bool, error) { if !models.HasEngine { return false, nil } uname := ctx.GetCookie(setting.CookieUserName) if len(uname) == 0 { return false, nil } isSucceed := false defer func() { if !isSucceed { log.Trace("auto-login cookie cleared: %s", uname) ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubUrl) ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubUrl) } }() u, err := models.GetUserByName(uname) if err != nil { if !models.IsErrUserNotExist(err) { return false, fmt.Errorf("GetUserByName: %v", err) } return false, nil } if val, _ := ctx.GetSuperSecureCookie( base.EncodeMd5(u.Rands+u.Passwd), setting.CookieRememberName); val != u.Name { return false, nil } isSucceed = true ctx.Session.Set("uid", u.Id) ctx.Session.Set("uname", u.Name) return true, nil }
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("form.still_own_user") ctx.Redirect(setting.AppSubUrl + "/admin/auths/" + ctx.Params(":authid")) default: ctx.Handle(500, "DeleteSource", err) } 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", }) }
func TestLogTrace(t *testing.T) { log.Trace("%v", errors.New("console log test")) }
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)) }
// searchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, string, string, bool, bool) { var userDN string if directBind { log.Trace("LDAP will bind directly via UserDN template: %s", ls.UserDN) userDN = fmt.Sprintf(ls.UserDN, name) } else { log.Trace("LDAP will use BindDN.") var found bool userDN, found = ls.FindUserDN(name) if !found { return "", "", "", false, false } } l, err := ldapDial(ls) if err != nil { log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err) ls.Enabled = false return "", "", "", false, false } defer l.Close() log.Trace("Binding with userDN: %s", userDN) err = l.Bind(userDN, passwd) if err != nil { log.Debug("LDAP auth. failed for %s, reason: %v", userDN, err) return "", "", "", false, false } log.Trace("Bound successfully with userDN: %s", userDN) userFilter := fmt.Sprintf(ls.Filter, name) search := ldap.NewSearchRequest( userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter, []string{ls.AttributeName, ls.AttributeSurname, ls.AttributeMail}, nil) sr, err := l.Search(search) if err != nil { log.Error(4, "LDAP Search failed unexpectedly! (%v)", err) return "", "", "", false, false } else if len(sr.Entries) < 1 { if directBind { log.Error(4, "User filter inhibited user login.") } else { log.Error(4, "LDAP Search failed unexpectedly! (0 entries)") } return "", "", "", false, false } name_attr := sr.Entries[0].GetAttributeValue(ls.AttributeName) sn_attr := sr.Entries[0].GetAttributeValue(ls.AttributeSurname) mail_attr := sr.Entries[0].GetAttributeValue(ls.AttributeMail) admin_attr := false if len(ls.AdminFilter) > 0 { search = ldap.NewSearchRequest( userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter, []string{ls.AttributeName}, nil) sr, err = l.Search(search) if err != nil { log.Error(4, "LDAP Admin Search failed unexpectedly! (%v)", err) } else if len(sr.Entries) < 1 { log.Error(4, "LDAP Admin Search failed") } else { admin_attr = true } } return name_attr, sn_attr, mail_attr, admin_attr, true }
func MigrateRepo(ctx *middleware.Context, form auth.MigrateRepoForm) { ctxUser := ctx.User // Not equal means current user is an organization. if form.Uid != ctxUser.Id { org, err := models.GetUserByID(form.Uid) if err != nil { if models.IsErrUserNotExist(err) { ctx.APIError(422, "", err) } else { ctx.APIError(500, "GetUserByID", err) } return } ctxUser = org } if ctx.HasError() { ctx.APIError(422, "", ctx.GetErrMsg()) return } if ctxUser.IsOrganization() { // Check ownership of organization. if !ctxUser.IsOwnedBy(ctx.User.Id) { ctx.APIError(403, "", "Given user is not owner of organization.") return } } // Remote address can be HTTP/HTTPS/Git URL or local path. 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.APIError(422, "", err) 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.APIError(422, "", "Invalid local path, it does not exist or not a directory.") return } repo, err := models.MigrateRepository(ctxUser, form.RepoName, form.Description, form.Private, form.Mirror, remoteAddr) if err != nil { if repo != nil { if errDelete := models.DeleteRepository(ctxUser.Id, repo.ID); errDelete != nil { log.Error(4, "DeleteRepository: %v", errDelete) } } ctx.APIError(500, "MigrateRepository", err) return } log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName) ctx.JSON(201, ToApiRepository(ctxUser, repo, api.Permission{true, true, true})) }