Exemple #1
0
func ChangeMilestonStatus(ctx *middleware.Context) {
	m, err := models.GetMilestoneByID(ctx.ParamsInt64(":id"))
	if err != nil {
		if models.IsErrMilestoneNotExist(err) {
			ctx.Handle(404, "GetMilestoneByID", err)
		} else {
			ctx.Handle(500, "GetMilestoneByID", err)
		}
		return
	}

	switch ctx.Params(":action") {
	case "open":
		if m.IsClosed {
			if err = models.ChangeMilestoneStatus(m, false); err != nil {
				ctx.Handle(500, "ChangeMilestoneStatus", err)
				return
			}
		}
		ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=open")
	case "close":
		if !m.IsClosed {
			m.ClosedDate = time.Now()
			if err = models.ChangeMilestoneStatus(m, true); err != nil {
				ctx.Handle(500, "ChangeMilestoneStatus", err)
				return
			}
		}
		ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=closed")
	default:
		ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
	}
}
Exemple #2
0
func Download(ctx *middleware.Context) {
	ext := "." + ctx.Params(":ext")

	var archivePath string
	switch ext {
	case ".zip":
		archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/zip")
	case ".tar.gz":
		archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/targz")
	default:
		ctx.Error(404)
		return
	}

	if !com.IsDir(archivePath) {
		if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
			ctx.Handle(500, "Download -> os.MkdirAll(archivePath)", err)
			return
		}
	}

	archivePath = path.Join(archivePath, ctx.Repo.CommitId+ext)
	if !com.IsFile(archivePath) {
		if err := ctx.Repo.Commit.CreateArchive(archivePath, git.ZIP); err != nil {
			ctx.Handle(500, "Download -> CreateArchive "+archivePath, err)
			return
		}
	}

	ctx.ServeFile(archivePath, ctx.Repo.Repository.Name+"-"+base.ShortSha(ctx.Repo.CommitId)+ext)
}
Exemple #3
0
func showOrgProfile(ctx *middleware.Context) {
	ctx.SetParams(":org", ctx.Params(":username"))
	middleware.HandleOrgAssignment(ctx)
	if ctx.Written() {
		return
	}

	org := ctx.Org.Organization
	ctx.Data["Title"] = org.FullName

	repos, err := models.GetRepositories(org.Id, ctx.IsSigned && (ctx.User.IsAdmin || org.IsOrgMember(ctx.User.Id)))
	if err != nil {
		ctx.Handle(500, "GetRepositories", err)
		return
	}
	ctx.Data["Repos"] = repos

	if err = org.GetMembers(); err != nil {
		ctx.Handle(500, "GetMembers", err)
		return
	}
	ctx.Data["Members"] = org.Members

	if err = org.GetTeams(); err != nil {
		ctx.Handle(500, "GetTeams", err)
		return
	}
	ctx.Data["Teams"] = org.Teams

	ctx.HTML(200, ORG_HOME)
}
Exemple #4
0
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(ctx.Tr("admin.auths.still_in_used"))
		default:
			ctx.Flash.Error(fmt.Sprintf("DeleteSource: %v", err))
		}
		ctx.JSON(200, map[string]interface{}{
			"redirect": setting.AppSubUrl + "/admin/auths/" + ctx.Params(":authid"),
		})
		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",
	})
}
Exemple #5
0
func Profile(ctx *middleware.Context) {
	ctx.Data["Title"] = "Profile"
	ctx.Data["PageIsUserProfile"] = true

	uname := ctx.Params(":username")
	// Special handle for FireFox requests favicon.ico.
	if uname == "favicon.ico" {
		ctx.Redirect(setting.AppSubUrl + "/img/favicon.png")
		return
	} else if strings.HasSuffix(uname, ".png") {
		ctx.Error(404)
		return
	}

	isShowKeys := false
	if strings.HasSuffix(uname, ".keys") {
		isShowKeys = true
		uname = strings.TrimSuffix(uname, ".keys")
	}

	u, err := models.GetUserByName(uname)
	if err != nil {
		if models.IsErrUserNotExist(err) {
			ctx.Handle(404, "GetUserByName", err)
		} else {
			ctx.Handle(500, "GetUserByName", err)
		}
		return
	}

	// Show SSH keys.
	if isShowKeys {
		ShowSSHKeys(ctx, u.Id)
		return
	}

	if u.IsOrganization() {
		showOrgProfile(ctx)
		return
	}
	ctx.Data["Owner"] = u

	tab := ctx.Query("tab")
	ctx.Data["TabName"] = tab
	switch tab {
	case "activity":
		retrieveFeeds(ctx, u.Id, 0, true)
		if ctx.Written() {
			return
		}
	default:
		ctx.Data["Repos"], err = models.GetRepositories(u.Id, ctx.IsSigned && ctx.User.Id == u.Id)
		if err != nil {
			ctx.Handle(500, "GetRepositories", err)
			return
		}
	}

	ctx.HTML(200, PROFILE)
}
Exemple #6
0
func CompareDiff(ctx *middleware.Context) {
	ctx.Data["IsRepoToolbarCommits"] = true
	ctx.Data["IsDiffCompare"] = true
	userName := ctx.Repo.Owner.Name
	repoName := ctx.Repo.Repository.Name
	beforeCommitId := ctx.Params(":before")
	afterCommitId := ctx.Params(":after")

	commit, err := ctx.Repo.GitRepo.GetCommit(afterCommitId)
	if err != nil {
		ctx.Handle(404, "GetCommit", err)
		return
	}

	diff, err := models.GetDiffRange(models.RepoPath(userName, repoName), beforeCommitId, afterCommitId)
	if err != nil {
		ctx.Handle(404, "GetDiffRange", err)
		return
	}

	isImageFile := func(name string) bool {
		blob, err := commit.GetBlobByPath(name)
		if err != nil {
			return false
		}

		dataRc, err := blob.Data()
		if err != nil {
			return false
		}
		buf := make([]byte, 1024)
		n, _ := dataRc.Read(buf)
		if n > 0 {
			buf = buf[:n]
		}
		_, isImage := base.IsImageFile(buf)
		return isImage
	}

	commits, err := commit.CommitsBeforeUntil(beforeCommitId)
	if err != nil {
		ctx.Handle(500, "CommitsBeforeUntil", err)
		return
	}

	ctx.Data["Commits"] = commits
	ctx.Data["CommitCount"] = commits.Len()
	ctx.Data["BeforeCommitId"] = beforeCommitId
	ctx.Data["AfterCommitId"] = afterCommitId
	ctx.Data["Username"] = userName
	ctx.Data["Reponame"] = repoName
	ctx.Data["IsImageFile"] = isImageFile
	ctx.Data["Title"] = "Comparing " + base.ShortSha(beforeCommitId) + "..." + base.ShortSha(afterCommitId) + " · " + userName + "/" + repoName
	ctx.Data["Commit"] = commit
	ctx.Data["Diff"] = diff
	ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
	ctx.Data["SourcePath"] = "/" + path.Join(userName, repoName, "src", afterCommitId)
	ctx.Data["RawPath"] = "/" + path.Join(userName, repoName, "raw", afterCommitId)
	ctx.HTML(200, DIFF)
}
Exemple #7
0
func Action(ctx *middleware.Context) {
	u := GetUserByParams(ctx)
	if ctx.Written() {
		return
	}

	var err error
	switch ctx.Params(":action") {
	case "follow":
		err = models.FollowUser(ctx.User.Id, u.Id)
	case "unfollow":
		err = models.UnfollowUser(ctx.User.Id, u.Id)
	}

	if err != nil {
		ctx.Handle(500, fmt.Sprintf("Action (%s)", ctx.Params(":action")), err)
		return
	}

	redirectTo := ctx.Query("redirect_to")
	if len(redirectTo) == 0 {
		redirectTo = u.HomeLink()
	}
	ctx.Redirect(redirectTo)
}
Exemple #8
0
func DeleteAuthSource(ctx *middleware.Context) {
	id := com.StrTo(ctx.Params(":authid")).MustInt64()
	if id == 0 {
		ctx.Handle(404, "DeleteAuthSource", nil)
		return
	}

	a, err := models.GetLoginSourceById(id)
	if err != nil {
		ctx.Handle(500, "GetLoginSourceById", err)
		return
	}

	if err = models.DelLoginSource(a); 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, "DelLoginSource", err)
		}
		return
	}
	log.Trace("Authentication deleted by admin(%s): %s", ctx.User.Name, a.Name)
	ctx.Redirect(setting.AppSubUrl + "/admin/auths")
}
Exemple #9
0
func TeamsRepoAction(ctx *middleware.Context) {
	if !ctx.Org.IsOwner {
		ctx.Error(404)
		return
	}

	var err error
	switch ctx.Params(":action") {
	case "add":
		repoName := path.Base(ctx.Query("repo-name"))
		var repo *models.Repository
		repo, err = models.GetRepositoryByName(ctx.Org.Organization.Id, repoName)
		if err != nil {
			ctx.Handle(500, "GetRepositoryByName", err)
			return
		}
		err = ctx.Org.Team.AddRepository(repo)
	case "remove":
		err = ctx.Org.Team.RemoveRepository(com.StrTo(ctx.Query("repoid")).MustInt64())
	}

	if err != nil {
		log.Error(3, "Action(%s): %v", ctx.Params(":action"), err)
		ctx.JSON(200, map[string]interface{}{
			"ok":  false,
			"err": err.Error(),
		})
		return
	}
	ctx.Redirect(ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName + "/repositories")
}
Exemple #10
0
func Action(ctx *middleware.Context) {
	var err error
	switch ctx.Params(":action") {
	case "watch":
		err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.ID, true)
	case "unwatch":
		err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.ID, false)
	case "star":
		err = models.StarRepo(ctx.User.Id, ctx.Repo.Repository.ID, true)
	case "unstar":
		err = models.StarRepo(ctx.User.Id, ctx.Repo.Repository.ID, false)
	case "desc": // FIXME: this is not used
		if !ctx.Repo.IsOwner() {
			ctx.Error(404)
			return
		}

		ctx.Repo.Repository.Description = ctx.Query("desc")
		ctx.Repo.Repository.Website = ctx.Query("site")
		err = models.UpdateRepository(ctx.Repo.Repository, false)
	}

	if err != nil {
		ctx.Handle(500, fmt.Sprintf("Action (%s)", ctx.Params(":action")), err)
		return
	}

	redirectTo := ctx.Query("redirect_to")
	if len(redirectTo) == 0 {
		redirectTo = ctx.Repo.RepoLink
	}
	ctx.Redirect(redirectTo)
}
Exemple #11
0
func getDashboardContextUser(ctx *middleware.Context) *models.User {
	ctxUser := ctx.User
	orgName := ctx.Params(":org")
	if len(orgName) > 0 {
		// Organization.
		org, err := models.GetUserByName(orgName)
		if err != nil {
			if models.IsErrUserNotExist(err) {
				ctx.Handle(404, "GetUserByName", err)
			} else {
				ctx.Handle(500, "GetUserByName", err)
			}
			return nil
		}
		ctxUser = org
	}
	ctx.Data["ContextUser"] = ctxUser

	if err := ctx.User.GetOrganizations(); err != nil {
		ctx.Handle(500, "GetOrganizations", err)
		return nil
	}
	ctx.Data["Orgs"] = ctx.User.Orgs

	return ctxUser
}
Exemple #12
0
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",
	})
}
Exemple #13
0
func SingleDownload(ctx *middleware.Context) {
	treename := ctx.Params("*")

	blob, err := ctx.Repo.Commit.GetBlobByPath(treename)
	if err != nil {
		ctx.Handle(500, "GetBlobByPath", err)
		return
	}

	dataRc, err := blob.Data()
	if err != nil {
		ctx.Handle(500, "repo.SingleDownload(Data)", err)
		return
	}

	buf := make([]byte, 1024)
	n, _ := dataRc.Read(buf)
	if n > 0 {
		buf = buf[:n]
	}

	contentType, isTextFile := base.IsTextFile(buf)
	_, isImageFile := base.IsImageFile(buf)
	ctx.Resp.Header().Set("Content-Type", contentType)
	if !isTextFile && !isImageFile {
		ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+path.Base(treename))
		ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
	}
	ctx.Resp.Write(buf)
	io.Copy(ctx.Resp, dataRc)
}
Exemple #14
0
func SearchCommits(ctx *middleware.Context) {
	ctx.Data["IsSearchPage"] = true
	ctx.Data["IsRepoToolbarCommits"] = true

	keyword := ctx.Query("q")
	if len(keyword) == 0 {
		ctx.Redirect(ctx.Repo.RepoLink + "/commits/" + ctx.Repo.BranchName)
		return
	}

	userName := ctx.Params(":username")
	repoName := ctx.Params(":reponame")

	brs, err := ctx.Repo.GitRepo.GetBranches()
	if err != nil {
		ctx.Handle(500, "GetBranches", err)
		return
	} else if len(brs) == 0 {
		ctx.Handle(404, "GetBranches", nil)
		return
	}

	commits, err := ctx.Repo.Commit.SearchCommits(keyword)
	if err != nil {
		ctx.Handle(500, "repo.SearchCommits(SearchCommits)", err)
		return
	}

	ctx.Data["Keyword"] = keyword
	ctx.Data["Username"] = userName
	ctx.Data["Reponame"] = repoName
	ctx.Data["CommitCount"] = commits.Len()
	ctx.Data["Commits"] = commits
	ctx.HTML(200, COMMITS)
}
Exemple #15
0
func FileHistory(ctx *middleware.Context) {
	ctx.Data["IsRepoToolbarCommits"] = true

	fileName := ctx.Params("*")
	if len(fileName) == 0 {
		Commits(ctx)
		return
	}

	userName := ctx.Repo.Owner.Name
	repoName := ctx.Repo.Repository.Name
	branchName := ctx.Params(":branchname")

	brs, err := ctx.Repo.GitRepo.GetBranches()
	if err != nil {
		ctx.Handle(500, "GetBranches", err)
		return
	} else if len(brs) == 0 {
		ctx.Handle(404, "GetBranches", nil)
		return
	}

	commitsCount, err := ctx.Repo.GitRepo.FileCommitsCount(branchName, fileName)
	if err != nil {
		ctx.Handle(500, "repo.FileHistory(GetCommitsCount)", err)
		return
	} else if commitsCount == 0 {
		ctx.Handle(404, "repo.FileHistory", nil)
		return
	}

	// Calculate and validate page number.
	page := com.StrTo(ctx.Query("p")).MustInt()
	if page < 1 {
		page = 1
	}
	lastPage := page - 1
	if lastPage < 0 {
		lastPage = 0
	}
	nextPage := page + 1
	if nextPage*50 > commitsCount {
		nextPage = 0
	}

	ctx.Data["Commits"], err = ctx.Repo.GitRepo.CommitsByFileAndRange(
		branchName, fileName, page)
	if err != nil {
		ctx.Handle(500, "repo.FileHistory(CommitsByRange)", err)
		return
	}

	ctx.Data["Username"] = userName
	ctx.Data["Reponame"] = repoName
	ctx.Data["FileName"] = fileName
	ctx.Data["CommitCount"] = commitsCount
	ctx.Data["LastPageNum"] = lastPage
	ctx.Data["NextPageNum"] = nextPage
	ctx.HTML(200, COMMITS)
}
Exemple #16
0
func SlackHooksEditPost(ctx *middleware.Context, form auth.NewSlackHookForm) {
	ctx.Data["Title"] = ctx.Tr("repo.settings")
	ctx.Data["PageIsSettingsHooks"] = true
	ctx.Data["PageIsSettingsHooksEdit"] = true

	hookId := com.StrTo(ctx.Params(":id")).MustInt64()
	if hookId == 0 {
		ctx.Handle(404, "SlackHooksEditPost(hookId)", nil)
		return
	}

	orCtx, err := getOrgRepoCtx(ctx)
	if err != nil {
		ctx.Handle(500, "SlackHooksEditPost(getOrgRepoCtx)", err)
		return
	}

	w, err := models.GetWebhookById(hookId)
	if err != nil {
		if err == models.ErrWebhookNotExist {
			ctx.Handle(404, "GetWebhookById", nil)
		} else {
			ctx.Handle(500, "GetWebhookById", err)
		}
		return
	}
	w.GetEvent()
	ctx.Data["Webhook"] = w

	if ctx.HasError() {
		ctx.HTML(200, orCtx.NewTemplate)
		return
	}
	meta, err := json.Marshal(&models.Slack{
		Domain:  form.Domain,
		Channel: form.Channel,
		Token:   form.Token,
	})
	if err != nil {
		ctx.Handle(500, "SlackHooksNewPost: JSON marshal failed: ", err)
		return
	}

	w.Url = models.GetSlackURL(form.Domain, form.Token)
	w.Meta = string(meta)
	w.HookEvent = &models.HookEvent{
		PushOnly: form.PushOnly,
	}
	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, "SlackHooksEditPost", err)
		return
	}

	ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
	ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, hookId))
}
Exemple #17
0
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)
}
Exemple #18
0
func EditUser(ctx *middleware.Context) {
	ctx.Data["Title"] = ctx.Tr("admin.users.edit_account")
	ctx.Data["PageIsAdmin"] = true
	ctx.Data["PageIsAdminUsers"] = true

	uid := com.StrTo(ctx.Params(":userid")).MustInt64()
	if uid == 0 {
		ctx.Handle(404, "EditUser", nil)
		return
	}

	u, err := models.GetUserById(uid)
	if err != nil {
		ctx.Handle(500, "GetUserById", err)
		return
	}

	ctx.Data["User"] = u
	auths, err := models.GetAuths()
	if err != nil {
		ctx.Handle(500, "GetAuths", err)
		return
	}
	ctx.Data["LoginSources"] = auths
	ctx.HTML(200, USER_EDIT)
}
Exemple #19
0
func TeamsRepoAction(ctx *middleware.Context) {
	if !ctx.Org.IsOwner {
		ctx.Error(404)
		return
	}

	var err error
	switch ctx.Params(":action") {
	case "add":
		repoName := path.Base(ctx.Query("repo_name"))
		var repo *models.Repository
		repo, err = models.GetRepositoryByName(ctx.Org.Organization.Id, repoName)
		if err != nil {
			if models.IsErrRepoNotExist(err) {
				ctx.Flash.Error(ctx.Tr("org.teams.add_nonexistent_repo"))
				ctx.Redirect(ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName + "/repositories")
				return
			}
			ctx.Handle(500, "GetRepositoryByName", err)
			return
		}
		err = ctx.Org.Team.AddRepository(repo)
	case "remove":
		err = ctx.Org.Team.RemoveRepository(com.StrTo(ctx.Query("repoid")).MustInt64())
	}

	if err != nil {
		log.Error(3, "Action(%s): '%s' %v", ctx.Params(":action"), ctx.Org.Team.Name, err)
		ctx.Handle(500, "TeamsRepoAction", err)
		return
	}
	ctx.Redirect(ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName + "/repositories")
}
Exemple #20
0
func DeleteUser(ctx *middleware.Context) {
	uid := com.StrTo(ctx.Params(":userid")).MustInt64()
	if uid == 0 {
		ctx.Handle(404, "DeleteUser", nil)
		return
	}

	u, err := models.GetUserById(uid)
	if err != nil {
		ctx.Handle(500, "GetUserById", err)
		return
	}

	if err = models.DeleteUser(u); err != nil {
		switch err {
		case models.ErrUserOwnRepos:
			ctx.Flash.Error(ctx.Tr("admin.users.still_own_repo"))
			ctx.Redirect("/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.Redirect("/admin/users")
}
Exemple #21
0
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["PageIsAuths"] = true
	ctx.Data["LoginTypes"] = models.LoginTypes
	ctx.Data["SMTPAuths"] = models.SMTPAuths

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

	var config core.Conversion
	switch models.LoginType(form.Type) {
	case models.LDAP:
		config = &models.LDAPConfig{
			Ldapsource: ldap.Ldapsource{
				Host:         form.Host,
				Port:         form.Port,
				UseSSL:       form.UseSSL,
				BaseDN:       form.BaseDN,
				Attributes:   form.Attributes,
				Filter:       form.Filter,
				MsAdSAFormat: form.MsAdSA,
				Enabled:      true,
				Name:         form.AuthName,
			},
		}
	case models.SMTP:
		config = &models.SMTPConfig{
			Auth: form.SmtpAuth,
			Host: form.SmtpHost,
			Port: form.SmtpPort,
			TLS:  form.Tls,
		}
	default:
		ctx.Error(400)
		return
	}

	u := models.LoginSource{
		Id:                form.Id,
		Name:              form.AuthName,
		IsActived:         form.IsActived,
		Type:              models.LoginType(form.Type),
		AllowAutoRegister: form.AllowAutoRegister,
		Cfg:               config,
	}

	if err := models.UpdateSource(&u); err != nil {
		ctx.Handle(500, "UpdateSource", err)
		return
	}

	log.Trace("Authentication changed by admin(%s): %s", ctx.User.Name, form.AuthName)
	ctx.Flash.Success(ctx.Tr("admin.auths.update_success"))
	ctx.Redirect("/admin/auths/" + ctx.Params(":authid"))
}
Exemple #22
0
func checkHookType(ctx *middleware.Context) string {
	hookType := strings.ToLower(ctx.Params(":type"))
	if !com.IsSliceContainsStr(setting.Webhook.Types, hookType) {
		ctx.Handle(404, "checkHookType", nil)
		return ""
	}
	return hookType
}
Exemple #23
0
func CompareAndPullRequest(ctx *middleware.Context) {
	ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
	ctx.Data["PageIsComparePull"] = true

	repo := ctx.Repo.Repository

	// Get compare branch information.
	infos := strings.Split(ctx.Params("*"), "...")
	if len(infos) != 2 {
		ctx.Handle(404, "CompareAndPullRequest", nil)
		return
	}

	baseBranch := infos[0]
	ctx.Data["BaseBranch"] = baseBranch

	headInfos := strings.Split(infos[1], ":")
	if len(headInfos) != 2 {
		ctx.Handle(404, "CompareAndPullRequest", nil)
		return
	}
	headUser := headInfos[0]
	headBranch := headInfos[1]
	ctx.Data["HeadBranch"] = headBranch

	// TODO: check if branches are valid.
	fmt.Println(baseBranch, headUser, headBranch)

	// TODO: add organization support
	// Check if current user has fork of repository.
	headRepo, has := models.HasForkedRepo(ctx.User.Id, repo.ID)
	if !has {
		ctx.Handle(404, "HasForkedRepo", nil)
		return
	}

	headGitRepo, err := git.OpenRepository(models.RepoPath(ctx.User.Name, headRepo.Name))
	if err != nil {
		ctx.Handle(500, "OpenRepository", err)
		return
	}
	headBranches, err := headGitRepo.GetBranches()
	if err != nil {
		ctx.Handle(500, "GetBranches", err)
		return
	}
	ctx.Data["HeadBranches"] = headBranches

	// Setup information for new form.
	RetrieveRepoMetas(ctx, ctx.Repo.Repository)
	if ctx.Written() {
		return
	}

	// Get diff information.

	ctx.HTML(200, COMPARE_PULL)
}
Exemple #24
0
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.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"))
}
Exemple #25
0
func UpdateMilestone(ctx *middleware.Context) {
	ctx.Data["Title"] = "Update Milestone"
	ctx.Data["IsRepoToolbarIssues"] = true
	ctx.Data["IsRepoToolbarIssuesList"] = true

	idx := com.StrTo(ctx.Params(":index")).MustInt64()
	if idx == 0 {
		ctx.Handle(404, "issue.UpdateMilestone", nil)
		return
	}

	mile, err := models.GetMilestoneByIndex(ctx.Repo.Repository.Id, idx)
	if err != nil {
		if err == models.ErrMilestoneNotExist {
			ctx.Handle(404, "issue.UpdateMilestone(GetMilestoneByIndex)", err)
		} else {
			ctx.Handle(500, "issue.UpdateMilestone(GetMilestoneByIndex)", err)
		}
		return
	}

	action := ctx.Params(":action")
	if len(action) > 0 {
		switch action {
		case "open":
			if mile.IsClosed {
				if err = models.ChangeMilestoneStatus(mile, false); err != nil {
					ctx.Handle(500, "issue.UpdateMilestone(ChangeMilestoneStatus)", err)
					return
				}
			}
		case "close":
			if !mile.IsClosed {
				mile.ClosedDate = time.Now()
				if err = models.ChangeMilestoneStatus(mile, true); err != nil {
					ctx.Handle(500, "issue.UpdateMilestone(ChangeMilestoneStatus)", err)
					return
				}
			}
		case "delete":
			if err = models.DeleteMilestone(mile); err != nil {
				ctx.Handle(500, "issue.UpdateMilestone(DeleteMilestone)", err)
				return
			}
		}
		ctx.Redirect(ctx.Repo.RepoLink + "/issues/milestones")
		return
	}

	mile.DeadlineString = mile.Deadline.UTC().Format("01/02/2006")
	if mile.DeadlineString == "12/31/9999" {
		mile.DeadlineString = ""
	}
	ctx.Data["Milestone"] = mile

	ctx.HTML(200, MILESTONE_EDIT)
}
Exemple #26
0
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

	uid := com.StrTo(ctx.Params(":userid")).MustInt64()
	if uid == 0 {
		ctx.Handle(404, "EditUser", nil)
		return
	}

	u, err := models.GetUserByID(uid)
	if err != nil {
		ctx.Handle(500, "GetUserById", err)
		return
	}
	ctx.Data["User"] = u

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

	// FIXME: need password length check
	if len(form.Password) > 0 {
		u.Passwd = form.Password
		u.Salt = models.GetUserSalt()
		u.EncodePasswd()
	}

	u.FullName = form.FullName
	u.Email = form.Email
	u.Website = form.Website
	u.Location = form.Location
	if len(form.Avatar) == 0 {
		form.Avatar = form.Email
	}
	u.Avatar = base.EncodeMd5(form.Avatar)
	u.AvatarEmail = form.Avatar
	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"))
}
Exemple #27
0
func WebHooksEditPost(ctx *middleware.Context, form auth.NewWebhookForm) {
	ctx.Data["Title"] = ctx.Tr("repo.settings")
	ctx.Data["PageIsSettingsHooks"] = true
	ctx.Data["PageIsSettingsHooksEdit"] = true

	hookId := com.StrTo(ctx.Params(":id")).MustInt64()
	if hookId == 0 {
		ctx.Handle(404, "setting.WebHooksEditPost", nil)
		return
	}

	w, err := models.GetWebhookById(hookId)
	if err != nil {
		if err == models.ErrWebhookNotExist {
			ctx.Handle(404, "GetWebhookById", nil)
		} else {
			ctx.Handle(500, "GetWebhookById", err)
		}
		return
	}
	w.GetEvent()
	ctx.Data["Webhook"] = w

	orCtx, err := getOrgRepoCtx(ctx)
	if err != nil {
		ctx.Handle(500, "WebHooksEditPost(getOrgRepoCtx)", err)
		return
	}
	if ctx.HasError() {
		ctx.HTML(200, orCtx.NewTemplate)
		return
	}

	ct := models.JSON
	if form.ContentType == "2" {
		ct = models.FORM
	}

	w.Url = form.PayloadUrl
	w.ContentType = ct
	w.Secret = form.Secret
	w.HookEvent = &models.HookEvent{
		PushOnly: form.PushOnly,
	}
	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, hookId))
}
Exemple #28
0
func DeleteNotice(ctx *middleware.Context) {
	id := com.StrTo(ctx.Params(":id")).MustInt64()
	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")
}
Exemple #29
0
func CommitByID(ctx *middleware.Context) {
	commit, err := ctx.Repo.GitRepo.GetCommit(ctx.Params(":commitid"))
	if err != nil {
		log.Error(4, "GetCommit: %v", err)
		ctx.APIError(500, "GetCommit", err.Error())
		return
	}

	ctx.JSON(200, ToApiCommit(commit))
}
Exemple #30
0
func Profile(ctx *middleware.Context) {
	uname := ctx.Params(":username")
	// Special handle for FireFox requests favicon.ico.
	if uname == "favicon.ico" {
		ctx.ServeFile(path.Join(setting.StaticRootPath, "public/img/favicon.png"))
		return
	} else if strings.HasSuffix(uname, ".png") {
		ctx.Error(404)
		return
	}

	isShowKeys := false
	if strings.HasSuffix(uname, ".keys") {
		isShowKeys = true
	}

	u := GetUserByParams(ctx)
	if ctx.Written() {
		return
	}

	// Show SSH keys.
	if isShowKeys {
		ShowSSHKeys(ctx, u.Id)
		return
	}

	if u.IsOrganization() {
		showOrgProfile(ctx)
		return
	}

	ctx.Data["Title"] = u.DisplayName()
	ctx.Data["PageIsUserProfile"] = true
	ctx.Data["Owner"] = u

	tab := ctx.Query("tab")
	ctx.Data["TabName"] = tab
	switch tab {
	case "activity":
		retrieveFeeds(ctx, u.Id, 0, true)
		if ctx.Written() {
			return
		}
	default:
		var err error
		ctx.Data["Repos"], err = models.GetRepositories(u.Id, ctx.IsSigned && ctx.User.Id == u.Id)
		if err != nil {
			ctx.Handle(500, "GetRepositories", err)
			return
		}
	}

	ctx.HTML(200, PROFILE)
}