func (ls Ldapsource) 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 ldapDial(ls Ldapsource) (*ldap.Conn, error) { if ls.UseSSL { log.Debug("Using TLS for LDAP") return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), nil) } else { return ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port)) } }
func UpdateGravatarSource() { gravatarSource = setting.GravatarSource if strings.HasPrefix(gravatarSource, "//") { gravatarSource = "http:" + gravatarSource } else if !strings.HasPrefix(gravatarSource, "http://") && !strings.HasPrefix(gravatarSource, "https://") { gravatarSource = "http://" + gravatarSource } log.Debug("avatar.UpdateGravatarSource(update gavatar source): %s", gravatarSource) }
func (this *thunderTask) fetch() error { log.Debug("avatar.fetch(fetch new avatar): %s", this.Url) req, _ := http.NewRequest("GET", this.Url, nil) req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/jpeg,image/png,*/*;q=0.8") req.Header.Set("Accept-Encoding", "deflate,sdch") req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8") req.Header.Set("Cache-Control", "no-cache") req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36") resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != 200 { return fmt.Errorf("status code: %d", resp.StatusCode) } /* log.Println("headers:", resp.Header) switch resp.Header.Get("Content-Type") { case "image/jpeg": this.SaveFile += ".jpeg" case "image/png": this.SaveFile += ".png" } */ /* imgType := resp.Header.Get("Content-Type") if imgType != "image/jpeg" && imgType != "image/png" { return errors.New("not png or jpeg") } */ tmpFile := this.SaveFile + ".part" // mv to destination when finished fd, err := os.Create(tmpFile) if err != nil { return err } _, err = io.Copy(fd, resp.Body) fd.Close() if err != nil { os.Remove(tmpFile) return err } return os.Rename(tmpFile, this.SaveFile) }
// CommitRepoAction adds new action for committing repository. func CommitRepoAction( userID, repoUserID int64, userName, actEmail string, repoID int64, repoUserName, repoName string, refFullName string, commit *base.PushCommits, oldCommitID string, newCommitID string) error { u, err := GetUserByID(userID) if err != nil { return fmt.Errorf("GetUserByID: %v", err) } repo, err := GetRepositoryByName(repoUserID, repoName) if err != nil { return fmt.Errorf("GetRepositoryByName: %v", err) } else if err = repo.GetOwner(); err != nil { return fmt.Errorf("GetOwner: %v", err) } isNewBranch := false opType := COMMIT_REPO // Check it's tag push or branch. if strings.HasPrefix(refFullName, "refs/tags/") { opType = PUSH_TAG commit = &base.PushCommits{} } else { // if not the first commit, set the compareUrl if !strings.HasPrefix(oldCommitID, "0000000") { commit.CompareUrl = fmt.Sprintf("%s/%s/compare/%s...%s", repoUserName, repoName, oldCommitID, newCommitID) } else { isNewBranch = true } // Change repository bare status and update last updated time. repo.IsBare = false if err = UpdateRepository(repo, false); err != nil { return fmt.Errorf("UpdateRepository: %v", err) } if err = updateIssuesCommit(u, repo, repoUserName, repoName, commit.Commits); err != nil { log.Debug("updateIssuesCommit: %v", err) } } bs, err := json.Marshal(commit) if err != nil { return fmt.Errorf("Marshal: %v", err) } refName := git.RefEndName(refFullName) if err = NotifyWatchers(&Action{ ActUserID: u.Id, ActUserName: userName, ActEmail: actEmail, OpType: opType, Content: string(bs), RepoID: repo.ID, RepoUserName: repoUserName, RepoName: repoName, RefName: refName, IsPrivate: repo.IsPrivate, }); err != nil { return fmt.Errorf("NotifyWatchers: %v", err) } repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName) payloadRepo := &api.PayloadRepo{ ID: repo.ID, Name: repo.LowerName, URL: repoLink, Description: repo.Description, Website: repo.Website, Watchers: repo.NumWatches, Owner: &api.PayloadAuthor{ Name: repo.Owner.DisplayName(), Email: repo.Owner.Email, UserName: repo.Owner.Name, }, Private: repo.IsPrivate, } pusher_email, pusher_name := "", "" pusher, err := GetUserByName(userName) if err == nil { pusher_email = pusher.Email pusher_name = pusher.DisplayName() } payloadSender := &api.PayloadUser{ UserName: pusher.Name, ID: pusher.Id, AvatarUrl: setting.AppUrl + pusher.RelAvatarLink(), } switch opType { case COMMIT_REPO: // Push commits := make([]*api.PayloadCommit, len(commit.Commits)) for i, cmt := range commit.Commits { author_username := "" author, err := GetUserByEmail(cmt.AuthorEmail) if err == nil { author_username = author.Name } commits[i] = &api.PayloadCommit{ ID: cmt.Sha1, Message: cmt.Message, URL: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1), Author: &api.PayloadAuthor{ Name: cmt.AuthorName, Email: cmt.AuthorEmail, UserName: author_username, }, } } p := &api.PushPayload{ Ref: refFullName, Before: oldCommitID, After: newCommitID, CompareUrl: setting.AppUrl + commit.CompareUrl, Commits: commits, Repo: payloadRepo, Pusher: &api.PayloadAuthor{ Name: pusher_name, Email: pusher_email, UserName: userName, }, Sender: payloadSender, } if err = PrepareWebhooks(repo, HOOK_EVENT_PUSH, p); err != nil { return fmt.Errorf("PrepareWebhooks: %v", err) } if isNewBranch { return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{ Ref: refName, RefType: "branch", Repo: payloadRepo, Sender: payloadSender, }) } case PUSH_TAG: // Create return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{ Ref: refName, RefType: "tag", Repo: payloadRepo, Sender: payloadSender, }) } return nil }
func RepoAssignment(redirect bool, args ...bool) macaron.Handler { return func(ctx *Context) { var ( displayBare bool // To display bare page if it is a bare repo. ) if len(args) >= 1 { displayBare = args[0] } var ( u *models.User err error ) userName := ctx.Params(":username") repoName := ctx.Params(":reponame") refName := ctx.Params(":branchname") if len(refName) == 0 { refName = ctx.Params(":path") } // Check if the user is the same as the repository owner if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) { u = ctx.User } else { u, err = models.GetUserByName(userName) if err != nil { if models.IsErrUserNotExist(err) { ctx.Handle(404, "GetUserByName", err) } else { ctx.Handle(500, "GetUserByName", err) } return } } ctx.Repo.Owner = u // Get repository. repo, err := models.GetRepositoryByName(u.Id, repoName) if err != nil { if models.IsErrRepoNotExist(err) { ctx.Handle(404, "GetRepositoryByName", err) } else { ctx.Handle(500, "GetRepositoryByName", err) } return } else if err = repo.GetOwner(); err != nil { ctx.Handle(500, "GetOwner", err) return } mode, err := models.AccessLevel(ctx.User, repo) if err != nil { ctx.Handle(500, "AccessLevel", err) return } ctx.Repo.AccessMode = mode // Check access. if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE { ctx.Handle(404, "no access right", err) return } ctx.Data["HasAccess"] = true if repo.IsMirror { ctx.Repo.Mirror, err = models.GetMirror(repo.ID) if err != nil { ctx.Handle(500, "GetMirror", err) return } ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval } repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones ctx.Repo.Repository = repo ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName)) if err != nil { ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err) return } ctx.Repo.GitRepo = gitRepo ctx.Repo.RepoLink, err = repo.RepoLink() if err != nil { ctx.Handle(500, "RepoLink", err) return } ctx.Data["RepoLink"] = ctx.Repo.RepoLink tags, err := ctx.Repo.GitRepo.GetTags() if err != nil { ctx.Handle(500, "GetTags", err) return } ctx.Data["Tags"] = tags ctx.Repo.Repository.NumTags = len(tags) if repo.IsFork { RetrieveBaseRepo(ctx, repo) if ctx.Written() { return } } ctx.Data["Title"] = u.Name + "/" + repo.Name ctx.Data["Repository"] = repo ctx.Data["Owner"] = ctx.Repo.Repository.Owner ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner() ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin() ctx.Data["DisableSSH"] = setting.DisableSSH ctx.Repo.CloneLink, err = repo.CloneLink() if err != nil { ctx.Handle(500, "CloneLink", err) return } ctx.Data["CloneLink"] = ctx.Repo.CloneLink if ctx.Query("go-get") == "1" { ctx.Data["GoGetImport"] = fmt.Sprintf("%s/%s/%s", setting.Domain, u.LowerName, repo.LowerName) } // repo is bare and display enable if ctx.Repo.Repository.IsBare { log.Debug("Bare repository: %s", ctx.Repo.RepoLink) // NOTE: to prevent templating error ctx.Data["BranchName"] = "" if displayBare { ctx.HTML(200, "repo/bare") } return } if ctx.IsSigned { ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.Id, repo.ID) ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.Id, repo.ID) } ctx.Data["TagName"] = ctx.Repo.TagName brs, err := ctx.Repo.GitRepo.GetBranches() if err != nil { ctx.Handle(500, "GetBranches", err) return } ctx.Data["Branches"] = brs ctx.Data["BrancheCount"] = len(brs) // If not branch selected, try default one. // If default branch doesn't exists, fall back to some other branch. if len(ctx.Repo.BranchName) == 0 { if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) { ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch } else if len(brs) > 0 { ctx.Repo.BranchName = brs[0] } } ctx.Data["BranchName"] = ctx.Repo.BranchName ctx.Data["CommitID"] = ctx.Repo.CommitID userAgent := ctx.Req.Header.Get("User-Agent") ua := user_agent.New(userAgent) browserName, browserVer := ua.Browser() ctx.Data["BrowserSupportsCopy"] = (browserName == "Chrome" && version.Compare(browserVer, CHROME_COPY_SUPPORT, ">=")) || (browserName == "Firefox" && version.Compare(browserVer, FIREFOX_COPY_SUPPORT, ">=")) } }
// searchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter func (ls Ldapsource) SearchEntry(name, passwd string) (string, string, string, bool, 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 { 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 }