Example #1
0
// create a time limit code for user active
func CreateUserActiveCode(user *models.User, startInf interface{}) string {
	minutes := base.Service.ActiveCodeLives
	data := base.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
	code := base.CreateTimeLimitCode(data, minutes, startInf)

	// add tail hex username
	code += hex.EncodeToString([]byte(user.LowerName))
	return code
}
Example #2
0
// verify active code when active account
func VerifyUserActiveCode(code string) (user *User) {
	minutes := base.Service.ActiveCodeLives

	if user = getVerifyUser(code); user != nil {
		// time limit code
		prefix := code[:base.TimeLimitCodeLength]
		data := base.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands

		if base.VerifyTimeLimitCode(data, minutes, prefix) {
			return user
		}
	}
	return nil
}
Example #3
0
File: issue.go Project: j20/gogs
// GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
	buf := bytes.NewBufferString("")
	for _, rid := range rids {
		buf.WriteString("repo_id=")
		buf.WriteString(base.ToStr(rid))
		buf.WriteString(" OR ")
	}
	cond := strings.TrimSuffix(buf.String(), " OR ")

	ius := make([]*IssueUser, 0, 10)
	sess := orm.Limit(20, (page-1)*20).Where("is_closed=?", isClosed)
	if len(cond) > 0 {
		sess.And(cond)
	}
	err := sess.Find(&ius)
	return ius, err
}
Example #4
0
// GetIssues returns a list of issues by given conditions.
func GetIssues(userId, repoId, posterId, milestoneId int64, page int, isClosed, isMention bool, labels, sortType string) ([]Issue, error) {
	sess := orm.Limit(20, (page-1)*20)

	if repoId > 0 {
		sess.Where("repo_id=?", repoId).And("is_closed=?", isClosed)
	} else {
		sess.Where("is_closed=?", isClosed)
	}

	if userId > 0 {
		sess.And("assignee_id=?", userId)
	} else if posterId > 0 {
		sess.And("poster_id=?", posterId)
	} else if isMention {
		sess.And("mentions like '%$" + base.ToStr(userId) + "|%'")
	}

	if milestoneId > 0 {
		sess.And("milestone_id=?", milestoneId)
	}

	if len(labels) > 0 {
		for _, label := range strings.Split(labels, ",") {
			sess.And("mentions like '%$" + label + "|%'")
		}
	}

	switch sortType {
	case "oldest":
		sess.Asc("created")
	case "recentupdate":
		sess.Desc("updated")
	case "leastupdate":
		sess.Asc("updated")
	case "mostcomment":
		sess.Desc("num_comments")
	case "leastcomment":
		sess.Asc("num_comments")
	default:
		sess.Desc("created")
	}

	var issues []Issue
	err := sess.Find(&issues)
	return issues, err
}
Example #5
0
func Install(ctx *middleware.Context, form auth.InstallForm) {
	if base.InstallLock {
		ctx.Handle(404, "install.Install", errors.New("Installation is prohibited"))
		return
	}

	ctx.Data["Title"] = "Install"
	ctx.Data["PageIsInstall"] = true

	if ctx.Req.Method == "GET" {
		// Get and assign value to install form.
		if len(form.Host) == 0 {
			form.Host = models.DbCfg.Host
		}
		if len(form.User) == 0 {
			form.User = models.DbCfg.User
		}
		if len(form.Passwd) == 0 {
			form.Passwd = models.DbCfg.Pwd
		}
		if len(form.DatabaseName) == 0 {
			form.DatabaseName = models.DbCfg.Name
		}
		if len(form.DatabasePath) == 0 {
			form.DatabasePath = models.DbCfg.Path
		}

		if len(form.RepoRootPath) == 0 {
			form.RepoRootPath = base.RepoRootPath
		}
		if len(form.RunUser) == 0 {
			form.RunUser = base.RunUser
		}
		if len(form.Domain) == 0 {
			form.Domain = base.Domain
		}
		if len(form.AppUrl) == 0 {
			form.AppUrl = base.AppUrl
		}

		auth.AssignForm(form, ctx.Data)
		ctx.HTML(200, "install")
		return
	}

	if ctx.HasError() {
		ctx.HTML(200, "install")
		return
	}

	// Pass basic check, now test configuration.
	// Test database setting.
	dbTypes := map[string]string{"mysql": "mysql", "pgsql": "postgres", "sqlite": "sqlite3"}
	models.DbCfg.Type = dbTypes[form.Database]
	models.DbCfg.Host = form.Host
	models.DbCfg.User = form.User
	models.DbCfg.Pwd = form.Passwd
	models.DbCfg.Name = form.DatabaseName
	models.DbCfg.SslMode = form.SslMode
	models.DbCfg.Path = form.DatabasePath

	// Set test engine.
	var x *xorm.Engine
	if err := models.NewTestEngine(x); err != nil {
		if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
			ctx.RenderWithErr("Your release version does not support SQLite3, please download the official binary version "+
				"from https://github.com/gogits/gogs/wiki/Install-from-binary, NOT the gobuild version.", "install", &form)
		} else {
			ctx.RenderWithErr("Database setting is not correct: "+err.Error(), "install", &form)
		}
		return
	}

	// Test repository root path.
	if err := os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
		ctx.RenderWithErr("Repository root path is invalid: "+err.Error(), "install", &form)
		return
	}

	// Check run user.
	curUser := os.Getenv("USERNAME")
	if len(curUser) == 0 {
		curUser = os.Getenv("USER")
	}
	// Does not check run user when the install lock is off.
	if form.RunUser != curUser {
		ctx.RenderWithErr("Run user isn't the current user: "******" -> "+curUser, "install", &form)
		return
	}

	// Save settings.
	base.Cfg.SetValue("database", "DB_TYPE", models.DbCfg.Type)
	base.Cfg.SetValue("database", "HOST", models.DbCfg.Host)
	base.Cfg.SetValue("database", "NAME", models.DbCfg.Name)
	base.Cfg.SetValue("database", "USER", models.DbCfg.User)
	base.Cfg.SetValue("database", "PASSWD", models.DbCfg.Pwd)
	base.Cfg.SetValue("database", "SSL_MODE", models.DbCfg.SslMode)
	base.Cfg.SetValue("database", "PATH", models.DbCfg.Path)

	base.Cfg.SetValue("repository", "ROOT", form.RepoRootPath)
	base.Cfg.SetValue("", "RUN_USER", form.RunUser)
	base.Cfg.SetValue("server", "DOMAIN", form.Domain)
	base.Cfg.SetValue("server", "ROOT_URL", form.AppUrl)

	if len(strings.TrimSpace(form.SmtpHost)) > 0 {
		base.Cfg.SetValue("mailer", "ENABLED", "true")
		base.Cfg.SetValue("mailer", "HOST", form.SmtpHost)
		base.Cfg.SetValue("mailer", "USER", form.SmtpEmail)
		base.Cfg.SetValue("mailer", "PASSWD", form.SmtpPasswd)

		base.Cfg.SetValue("service", "REGISTER_EMAIL_CONFIRM", base.ToStr(form.RegisterConfirm == "on"))
		base.Cfg.SetValue("service", "ENABLE_NOTIFY_MAIL", base.ToStr(form.MailNotify == "on"))
	}

	base.Cfg.SetValue("", "RUN_MODE", "prod")

	base.Cfg.SetValue("security", "INSTALL_LOCK", "true")

	os.MkdirAll("custom/conf", os.ModePerm)
	if err := goconfig.SaveConfigFile(base.Cfg, "custom/conf/app.ini"); err != nil {
		ctx.RenderWithErr("Fail to save configuration: "+err.Error(), "install", &form)
		return
	}

	GlobalInit()

	// Create admin account.
	if _, err := models.RegisterUser(&models.User{Name: form.AdminName, Email: form.AdminEmail, Passwd: form.AdminPasswd,
		IsAdmin: true, IsActive: true}); err != nil {
		if err != models.ErrUserAlreadyExist {
			ctx.RenderWithErr("Admin account setting is invalid: "+err.Error(), "install", &form)
			return
		}
		log.Info("Admin account already exist")
	}

	log.Info("First-time run install finished!")
	ctx.Redirect("/user/login")
}
Example #6
0
// SetRepoEnvs sets environment variables for command update.
func SetRepoEnvs(userId int64, userName, repoName string) {
	os.Setenv("userId", base.ToStr(userId))
	os.Setenv("userName", userName)
	os.Setenv("repoName", repoName)
}
Example #7
0
File: repo.go Project: jcfrank/gogs
// InitRepository initializes README and .gitignore if needed.
func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error {
	repoPath := RepoPath(user.Name, repo.Name)

	// Create bare new repository.
	if err := extractGitBareZip(repoPath); err != nil {
		return err
	}

	rp := strings.NewReplacer("\\", "/", " ", "\\ ")
	// hook/post-update
	if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"),
		fmt.Sprintf("#!/usr/bin/env %s\n%s update $1 $2 $3\n", setting.ScriptType,
			rp.Replace(appPath))); err != nil {
		return err
	}

	// Initialize repository according to user's choice.
	fileName := map[string]string{}
	if initReadme {
		fileName["readme"] = "README.md"
	}
	if repoLang != "" {
		fileName["gitign"] = ".gitignore"
	}
	if license != "" {
		fileName["license"] = "LICENSE"
	}

	// Clone to temprory path and do the init commit.
	tmpDir := filepath.Join(os.TempDir(), base.ToStr(time.Now().Nanosecond()))
	os.MkdirAll(tmpDir, os.ModePerm)

	_, stderr, err := com.ExecCmd("git", "clone", repoPath, tmpDir)
	if err != nil {
		return errors.New("git clone: " + stderr)
	}

	// README
	if initReadme {
		defaultReadme := repo.Name + "\n" + strings.Repeat("=",
			utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
		if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
			[]byte(defaultReadme), 0644); err != nil {
			return err
		}
	}

	// .gitignore
	if repoLang != "" {
		filePath := "conf/gitignore/" + repoLang
		targetPath := path.Join(tmpDir, fileName["gitign"])
		data, err := bin.Asset(filePath)
		if err == nil {
			if err = ioutil.WriteFile(targetPath, data, os.ModePerm); err != nil {
				return err
			}
		} else {
			// Check custom files.
			filePath = path.Join(setting.CustomPath, "conf/gitignore", repoLang)
			if com.IsFile(filePath) {
				if err := com.Copy(filePath, targetPath); err != nil {
					return err
				}
			}
		}
	}

	// LICENSE
	if license != "" {
		filePath := "conf/license/" + license
		targetPath := path.Join(tmpDir, fileName["license"])
		data, err := bin.Asset(filePath)
		if err == nil {
			if err = ioutil.WriteFile(targetPath, data, os.ModePerm); err != nil {
				return err
			}
		} else {
			// Check custom files.
			filePath = path.Join(setting.CustomPath, "conf/license", license)
			if com.IsFile(filePath) {
				if err := com.Copy(filePath, targetPath); err != nil {
					return err
				}
			}
		}
	}

	if len(fileName) == 0 {
		return nil
	}

	SetRepoEnvs(user.Id, user.Name, repo.Name, user.Name)

	// Apply changes and commit.
	return initRepoCommit(tmpDir, user.NewGitSig())
}
Example #8
0
// CreateRepository creates a repository for given user or organization.
func CreateRepository(u *User, name, desc, lang, license string, private, mirror, initReadme bool) (*Repository, error) {
	if !IsLegalName(name) {
		return nil, ErrRepoNameIllegal
	}

	isExist, err := IsRepositoryExist(u, name)
	if err != nil {
		return nil, err
	} else if isExist {
		return nil, ErrRepoAlreadyExist
	}

	sess := x.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return nil, err
	}

	repo := &Repository{
		OwnerId:     u.Id,
		Owner:       u,
		Name:        name,
		LowerName:   strings.ToLower(name),
		Description: desc,
		IsPrivate:   private,
		IsBare:      lang == "" && license == "" && !initReadme,
	}
	if !repo.IsBare {
		repo.DefaultBranch = "master"
	}

	if _, err = sess.Insert(repo); err != nil {
		sess.Rollback()
		return nil, err
	}

	var t *Team // Owner team.

	mode := WRITABLE
	if mirror {
		mode = READABLE
	}
	access := &Access{
		UserName: u.LowerName,
		RepoName: strings.ToLower(path.Join(u.Name, repo.Name)),
		Mode:     mode,
	}
	// Give access to all members in owner team.
	if u.IsOrganization() {
		t, err = u.GetOwnerTeam()
		if err != nil {
			sess.Rollback()
			return nil, err
		}
		us, err := GetTeamMembers(u.Id, t.Id)
		if err != nil {
			sess.Rollback()
			return nil, err
		}
		for _, u := range us {
			access.UserName = u.LowerName
			if _, err = sess.Insert(access); err != nil {
				sess.Rollback()
				return nil, err
			}
		}
	} else {
		if _, err = sess.Insert(access); err != nil {
			sess.Rollback()
			return nil, err
		}
	}

	rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
	if _, err = sess.Exec(rawSql, u.Id); err != nil {
		sess.Rollback()
		return nil, err
	}

	// Update owner team info and count.
	if u.IsOrganization() {
		t.RepoIds += "$" + base.ToStr(repo.Id) + "|"
		t.NumRepos++
		if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
			sess.Rollback()
			return nil, err
		}
	}

	if err = sess.Commit(); err != nil {
		return nil, err
	}

	if u.IsOrganization() {
		ous, err := GetOrgUsersByOrgId(u.Id)
		if err != nil {
			log.Error("repo.CreateRepository(GetOrgUsersByOrgId): %v", err)
		} else {
			for _, ou := range ous {
				if err = WatchRepo(ou.Uid, repo.Id, true); err != nil {
					log.Error("repo.CreateRepository(WatchRepo): %v", err)
				}
			}
		}
	}
	if err = WatchRepo(u.Id, repo.Id, true); err != nil {
		log.Error("repo.CreateRepository(WatchRepo2): %v", err)
	}

	if err = NewRepoAction(u, repo); err != nil {
		log.Error("repo.CreateRepository(NewRepoAction): %v", err)
	}

	// No need for init for mirror.
	if mirror {
		return repo, nil
	}

	repoPath := RepoPath(u.Name, repo.Name)
	if err = initRepository(repoPath, u, repo, initReadme, lang, license); err != nil {
		if err2 := os.RemoveAll(repoPath); err2 != nil {
			log.Error("repo.CreateRepository(initRepository): %v", err)
			return nil, errors.New(fmt.Sprintf(
				"delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2))
		}
		return nil, err
	}

	_, stderr, err := process.ExecDir(
		repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
		"git", "update-server-info")
	if err != nil {
		return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
	}

	return repo, nil
}
Example #9
0
func InstallPost(ctx *middleware.Context, form auth.InstallForm) {
	if setting.InstallLock {
		ctx.Handle(404, "install.Install", errors.New("Installation is prohibited"))
		return
	}

	ctx.Data["Title"] = "Install"
	ctx.Data["PageIsInstall"] = true

	renderDbOption(ctx)
	ctx.Data["CurDbOption"] = form.Database

	if ctx.HasError() {
		ctx.HTML(200, "install")
		return
	}

	if _, err := exec.LookPath("git"); err != nil {
		ctx.RenderWithErr("Fail to test 'git' command: "+err.Error(), "install", &form)
		return
	}

	// Pass basic check, now test configuration.
	// Test database setting.
	dbTypes := map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "SQLite3": "sqlite3"}
	models.DbCfg.Type = dbTypes[form.Database]
	models.DbCfg.Host = form.Host
	models.DbCfg.User = form.User
	models.DbCfg.Pwd = form.Passwd
	models.DbCfg.Name = form.DatabaseName
	models.DbCfg.SslMode = form.SslMode
	models.DbCfg.Path = form.DatabasePath

	// Set test engine.
	var x *xorm.Engine
	if err := models.NewTestEngine(x); err != nil {
		if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
			ctx.RenderWithErr("Your release version does not support SQLite3, please download the official binary version "+
				"from http://gogs.io/docs/installation/install_from_binary.md, NOT the gobuild version.", "install", &form)
		} else {
			ctx.RenderWithErr("Database setting is not correct: "+err.Error(), "install", &form)
		}
		return
	}

	// Test repository root path.
	if err := os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
		ctx.RenderWithErr("Repository root path is invalid: "+err.Error(), "install", &form)
		return
	}

	// Check run user.
	curUser := os.Getenv("USER")
	if len(curUser) == 0 {
		curUser = os.Getenv("USERNAME")
	}
	// Does not check run user when the install lock is off.
	if form.RunUser != curUser {
		ctx.RenderWithErr("Run user isn't the current user: "******" -> "+curUser, "install", &form)
		return
	}

	// Save settings.
	setting.Cfg.SetValue("database", "DB_TYPE", models.DbCfg.Type)
	setting.Cfg.SetValue("database", "HOST", models.DbCfg.Host)
	setting.Cfg.SetValue("database", "NAME", models.DbCfg.Name)
	setting.Cfg.SetValue("database", "USER", models.DbCfg.User)
	setting.Cfg.SetValue("database", "PASSWD", models.DbCfg.Pwd)
	setting.Cfg.SetValue("database", "SSL_MODE", models.DbCfg.SslMode)
	setting.Cfg.SetValue("database", "PATH", models.DbCfg.Path)

	setting.Cfg.SetValue("repository", "ROOT", form.RepoRootPath)
	setting.Cfg.SetValue("", "RUN_USER", form.RunUser)
	setting.Cfg.SetValue("server", "DOMAIN", form.Domain)
	setting.Cfg.SetValue("server", "ROOT_URL", form.AppUrl)

	if len(strings.TrimSpace(form.SmtpHost)) > 0 {
		setting.Cfg.SetValue("mailer", "ENABLED", "true")
		setting.Cfg.SetValue("mailer", "HOST", form.SmtpHost)
		setting.Cfg.SetValue("mailer", "USER", form.SmtpEmail)
		setting.Cfg.SetValue("mailer", "PASSWD", form.SmtpPasswd)

		setting.Cfg.SetValue("service", "REGISTER_EMAIL_CONFIRM", base.ToStr(form.RegisterConfirm == "on"))
		setting.Cfg.SetValue("service", "ENABLE_NOTIFY_MAIL", base.ToStr(form.MailNotify == "on"))
	}

	setting.Cfg.SetValue("", "RUN_MODE", "prod")

	setting.Cfg.SetValue("security", "INSTALL_LOCK", "true")

	os.MkdirAll("custom/conf", os.ModePerm)
	if err := goconfig.SaveConfigFile(setting.Cfg, path.Join(setting.CustomPath, "conf/app.ini")); err != nil {
		ctx.RenderWithErr("Fail to save configuration: "+err.Error(), "install", &form)
		return
	}

	GlobalInit()

	// Create admin account.
	if _, err := models.RegisterUser(&models.User{Name: form.AdminName, Email: form.AdminEmail, Passwd: form.AdminPasswd,
		IsAdmin: true, IsActive: true}); err != nil {
		if err != models.ErrUserAlreadyExist {
			setting.InstallLock = false
			ctx.RenderWithErr("Admin account setting is invalid: "+err.Error(), "install", &form)
			return
		}
		log.Info("Admin account already exist")
	}

	log.Info("First-time run install finished!")
	ctx.Flash.Success("Welcome! We're glad that you choose Gogs, have fun and take care.")
	ctx.Redirect("/user/login")
}