func checkUserFollowing(ctx *context.APIContext, u *models.User, followID int64) { if u.IsFollowing(followID) { ctx.Status(204) } else { ctx.Status(404) } }
// SendIssueMentionMail sends mail notification for who are mentioned in issue. func SendIssueMentionMail(r macaron.Render, u, owner *models.User, repo *models.Repository, issue *models.Issue, tos []string) error { if len(tos) == 0 { return nil } subject := fmt.Sprintf("[%s] %s (#%d)", repo.Name, issue.Name, issue.Index) data := ComposeTplData(nil) data["IssueLink"] = fmt.Sprintf("%s/%s/issues/%d", owner.Name, repo.Name, issue.Index) data["Subject"] = subject data["ActUserName"] = u.DisplayName() data["Content"] = string(base.RenderSpecialLink([]byte(issue.Content), owner.Name+"/"+repo.Name, repo.ComposeMetas())) body, err := r.HTMLString(string(NOTIFY_MENTION), data) if err != nil { return fmt.Errorf("HTMLString: %v", err) } msg := NewMessage(tos, subject, body) msg.Info = fmt.Sprintf("Subject: %s, issue mention", subject) SendAsync(msg) return nil }
// FIXME: limit size. func UpdateAvatarSetting(ctx *middleware.Context, form auth.UploadAvatarForm, ctxUser *models.User) error { ctxUser.UseCustomAvatar = form.Enable if form.Avatar != nil { fr, err := form.Avatar.Open() if err != nil { return fmt.Errorf("Avatar.Open: %v", err) } data, err := ioutil.ReadAll(fr) if err != nil { return fmt.Errorf("ReadAll: %v", err) } if _, ok := base.IsImageFile(data); !ok { return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image")) } if err = ctxUser.UploadAvatar(data); err != nil { return fmt.Errorf("UploadAvatar: %v", err) } } else { // In case no avatar at all. if form.Enable && !com.IsFile(ctx.User.CustomAvatarPath()) { return errors.New(ctx.Tr("settings.no_custom_avatar_available")) } } if err := models.UpdateUser(ctxUser); err != nil { return fmt.Errorf("UpdateUser: %v", err) } return nil }
func Delete(ctx *middleware.Context) { ctx.Data["Title"] = "Delete Account" ctx.Data["PageIsUserSetting"] = true ctx.Data["IsUserPageSettingDelete"] = true if ctx.Req.Method == "GET" { ctx.HTML(200, "user/delete") return } tmpUser := models.User{Passwd: ctx.Query("password")} tmpUser.EncodePasswd() if len(tmpUser.Passwd) == 0 || tmpUser.Passwd != ctx.User.Passwd { ctx.Data["HasError"] = true ctx.Data["ErrorMsg"] = "Password is not correct. Make sure you are owner of this account." } else { if err := models.DeleteUser(ctx.User); err != nil { ctx.Data["HasError"] = true switch err { case models.ErrUserOwnRepos: ctx.Data["ErrorMsg"] = "Your account still have ownership of repository, you have to delete or transfer them first." default: ctx.Handle(200, "user.Delete", err) return } } else { ctx.Redirect("/") return } } ctx.HTML(200, "user/delete") }
// ToApiUser converts user to API format. func ToApiUser(u *models.User) *api.User { return &api.User{ Id: u.Id, UserName: u.Name, AvatarUrl: string(setting.Protocol) + u.AvatarLink(), } }
func DeletePost(ctx *middleware.Context) { ctx.Data["Title"] = "Delete Account" ctx.Data["PageIsUserSetting"] = true ctx.Data["IsUserPageSettingDelete"] = true tmpUser := models.User{ Passwd: ctx.Query("password"), Salt: ctx.User.Salt, } tmpUser.EncodePasswd() if tmpUser.Passwd != ctx.User.Passwd { ctx.Flash.Error("Password is not correct. Make sure you are owner of this account.") } else { if err := models.DeleteUser(ctx.User); err != nil { switch err { case models.ErrUserOwnRepos: ctx.Flash.Error("Your account still have ownership of repository, you have to delete or transfer them first.") default: ctx.Handle(500, "user.Delete", err) return } } else { ctx.Redirect("/") return } } ctx.Redirect("/user/delete") }
func checkUserFollowing(ctx *middleware.Context, u *models.User, followID int64) { if u.IsFollowing(followID) { ctx.Status(204) } else { ctx.Error(404) } }
func listUserFollowing(ctx *context.APIContext, u *models.User) { users, err := u.GetFollowing(ctx.QueryInt("page")) if err != nil { ctx.Error(500, "GetFollowing", err) return } responseApiUsers(ctx, users) }
func listUserFollowers(ctx *middleware.Context, u *models.User) { users, err := u.GetFollowers(ctx.QueryInt("page")) if err != nil { ctx.APIError(500, "GetUserFollowers", err) return } responseApiUsers(ctx, users) }
// ToApiUser converts user to API format. func ToApiUser(u *models.User) *api.User { return &api.User{ ID: u.Id, UserName: u.Name, FullName: u.FullName, Email: u.Email, AvatarUrl: u.AvatarLink(), } }
func ToOrganization(org *models.User) *api.Organization { return &api.Organization{ ID: org.ID, AvatarUrl: org.AvatarLink(), UserName: org.Name, FullName: org.FullName, Description: org.Description, Website: org.Website, Location: org.Location, } }
func listUserOrgs(ctx *context.APIContext, u *models.User, all bool) { if err := u.GetOrganizations(all); err != nil { ctx.Error(500, "GetOrganizations", err) return } apiOrgs := make([]*api.Organization, len(u.Orgs)) for i := range u.Orgs { apiOrgs[i] = convert.ToOrganization(u.Orgs[i]) } ctx.JSON(200, &apiOrgs) }
func ToUser(u *models.User) *api.User { if u == nil { return nil } return &api.User{ ID: u.ID, UserName: u.Name, FullName: u.FullName, Email: u.Email, AvatarUrl: u.AvatarLink(), } }
// SendActivateAccountMail sends confirmation e-mail. func SendActivateEmailMail(c *macaron.Context, u *models.User, email *models.EmailAddress) { data := ComposeTplData(u) data["Code"] = u.GenerateEmailActivateCode(email.Email) data["Email"] = email.Email body, err := c.HTMLString(string(AUTH_ACTIVATE_EMAIL), data) if err != nil { log.Error(4, "HTMLString: %v", err) return } msg := NewMessage([]string{email.Email}, c.Tr("mail.activate_email"), body) msg.Info = fmt.Sprintf("UID: %d, activate email", u.Id) SendAsync(msg) }
func handleCreateError(ctx *middleware.Context, owner *models.User, err error, name string, tpl base.TplName, form interface{}) { switch { case models.IsErrReachLimitOfRepo(err): ctx.RenderWithErr(ctx.Tr("repo.form.reach_limit_of_creation", owner.RepoCreationNum()), tpl, form) case models.IsErrRepoAlreadyExist(err): ctx.Data["Err_RepoName"] = true ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tpl, form) case models.IsErrNameReserved(err): ctx.Data["Err_RepoName"] = true ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form) case models.IsErrNamePatternNotAllowed(err): ctx.Data["Err_RepoName"] = true ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form) default: ctx.Handle(500, name, err) } }
func parseLoginSource(ctx *middleware.Context, u *models.User, sourceID int64, loginName string) { if sourceID == 0 { return } source, err := models.GetLoginSourceByID(sourceID) if err != nil { if models.IsErrAuthenticationNotExist(err) { ctx.APIError(422, "", err) } else { ctx.APIError(500, "GetLoginSourceByID", err) } return } u.LoginType = source.Type u.LoginSource = source.ID u.LoginName = loginName }
func DeletePost(ctx *middleware.Context, params martini.Params) { ctx.Data["Title"] = "Settings" org, err := models.GetUserByName(params["org"]) if err != nil { if err == models.ErrUserNotExist { ctx.Handle(404, "org.DeletePost(GetUserByName)", err) } else { ctx.Handle(500, "org.DeletePost(GetUserByName)", err) } return } ctx.Data["Org"] = org if !org.IsOrgOwner(ctx.User.Id) { ctx.Error(403) return } tmpUser := models.User{ Passwd: ctx.Query("password"), Salt: ctx.User.Salt, } tmpUser.EncodePasswd() if tmpUser.Passwd != ctx.User.Passwd { ctx.Flash.Error("Password is not correct. Make sure you are owner of this account.") } else { if err := models.DeleteOrganization(org); err != nil { switch err { case models.ErrUserOwnRepos: ctx.Flash.Error("This organization still have ownership of repository, you have to delete or transfer them first.") default: ctx.Handle(500, "org.DeletePost(DeleteOrganization)", err) return } } else { ctx.Redirect("/") return } } ctx.Redirect("/org/" + org.Name + "/settings") }
// ParseRemoteAddr checks if given remote address is valid, // and returns composed URL with needed username and passowrd. // It also checks if given user has permission when remote address // is actually a local path. func (f MigrateRepoForm) ParseRemoteAddr(user *models.User) (string, error) { remoteAddr := f.CloneAddr // Remote address can be HTTP/HTTPS/Git URL or local path. if strings.HasPrefix(remoteAddr, "http://") || strings.HasPrefix(remoteAddr, "https://") || strings.HasPrefix(remoteAddr, "git://") { u, err := url.Parse(remoteAddr) if err != nil { return "", models.ErrInvalidCloneAddr{IsURLError: true} } if len(f.AuthUsername)+len(f.AuthPassword) > 0 { u.User = url.UserPassword(f.AuthUsername, f.AuthPassword) } remoteAddr = u.String() } else if !user.CanImportLocal() { return "", models.ErrInvalidCloneAddr{IsPermissionDenied: true} } else if !com.IsDir(remoteAddr) { return "", models.ErrInvalidCloneAddr{IsInvalidPath: true} } return remoteAddr, nil }
// FIXME: limit size. func UpdateAvatarSetting(ctx *context.Context, form auth.AvatarForm, ctxUser *models.User) error { ctxUser.UseCustomAvatar = form.Source == auth.AVATAR_LOCAL if len(form.Gravatar) > 0 { ctxUser.Avatar = base.EncodeMD5(form.Gravatar) ctxUser.AvatarEmail = form.Gravatar } if form.Avatar != nil { fr, err := form.Avatar.Open() if err != nil { return fmt.Errorf("Avatar.Open: %v", err) } defer fr.Close() data, err := ioutil.ReadAll(fr) if err != nil { return fmt.Errorf("ioutil.ReadAll: %v", err) } if !base.IsImageFile(data) { return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image")) } if err = ctxUser.UploadAvatar(data); err != nil { return fmt.Errorf("UploadAvatar: %v", err) } } else { // No avatar is uploaded but setting has been changed to enable, // generate a random one when needed. if ctxUser.UseCustomAvatar && !com.IsFile(ctxUser.CustomAvatarPath()) { if err := ctxUser.GenerateRandomAvatar(); err != nil { log.Error(4, "GenerateRandomAvatar[%d]: %v", ctxUser.ID, err) } } } if err := models.UpdateUser(ctxUser); err != nil { return fmt.Errorf("UpdateUser: %v", err) } return nil }
// FIXME: limit size. func UpdateAvatarSetting(ctx *middleware.Context, form auth.UploadAvatarForm, ctxUser *models.User) error { ctxUser.UseCustomAvatar = form.Enable if form.Avatar != nil { fr, err := form.Avatar.Open() if err != nil { return fmt.Errorf("Avatar.Open: %v", err) } defer fr.Close() data, err := ioutil.ReadAll(fr) if err != nil { return fmt.Errorf("ioutil.ReadAll: %v", err) } if _, ok := base.IsImageFile(data); !ok { return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image")) } if err = ctxUser.UploadAvatar(data); err != nil { return fmt.Errorf("UploadAvatar: %v", err) } } else { // No avatar is uploaded but setting has been changed to enable, // generate a random one when needed. if form.Enable && !com.IsFile(ctxUser.CustomAvatarPath()) { if err := ctxUser.GenerateRandomAvatar(); err != nil { log.Error(4, "GenerateRandomAvatar[%d]: %v", ctxUser.Id, err) } } } if err := models.UpdateUser(ctxUser); err != nil { return fmt.Errorf("UpdateUser: %v", err) } return nil }
func RepoAssignment(redirect bool, args ...bool) macaron.Handler { return func(ctx *Context) { var ( validBranch bool // To valid brach name. displayBare bool // To display bare page if it is a bare repo. ) if len(args) >= 1 { validBranch = args[0] } if len(args) >= 2 { displayBare = args[1] } 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") } // Collaborators who have write access can be seen as owners. if ctx.IsSigned { ctx.Repo.IsOwner, err = models.HasAccess(ctx.User.Name, userName+"/"+repoName, models.WRITABLE) if err != nil { ctx.Handle(500, "HasAccess", err) return } ctx.Repo.IsTrueOwner = ctx.User.LowerName == strings.ToLower(userName) } if !ctx.Repo.IsTrueOwner { u, err = models.GetUserByName(userName) if err != nil { if err == models.ErrUserNotExist { ctx.Handle(404, "GetUserByName", err) } else if redirect { log.Error(4, "GetUserByName", err) ctx.Redirect("/") } else { ctx.Handle(500, "GetUserByName", err) } return } } else { u = ctx.User } if u == nil { if redirect { ctx.Redirect("/") return } ctx.Handle(404, "RepoAssignment", errors.New("invliad user account for single repository")) return } ctx.Repo.Owner = u // Organization owner team members are true owners as well. if ctx.IsSigned && ctx.Repo.Owner.IsOrganization() && ctx.Repo.Owner.IsOrgOwner(ctx.User.Id) { ctx.Repo.IsTrueOwner = true } // Get repository. repo, err := models.GetRepositoryByName(u.Id, repoName) if err != nil { if err == models.ErrRepoNotExist { ctx.Handle(404, "GetRepositoryByName", err) return } else if redirect { ctx.Redirect("/") return } ctx.Handle(500, "GetRepositoryByName", err) return } else if err = repo.GetOwner(); err != nil { ctx.Handle(500, "GetOwner", err) return } // Check if the mirror repository owner(mirror repository doesn't have access). if ctx.IsSigned && !ctx.Repo.IsOwner { if repo.OwnerId == ctx.User.Id { ctx.Repo.IsOwner = true } // Check if current user has admin permission to repository. if u.IsOrganization() { auth, err := models.GetHighestAuthorize(u.Id, ctx.User.Id, 0, repo.Id) if err != nil { ctx.Handle(500, "GetHighestAuthorize", err) return } if auth == models.ORG_ADMIN { ctx.Repo.IsOwner = true ctx.Repo.IsAdmin = true } } } // Check access. if repo.IsPrivate && !ctx.Repo.IsOwner { if ctx.User == nil { ctx.Handle(404, "HasAccess", nil) return } hasAccess, err := models.HasAccess(ctx.User.Name, ctx.Repo.Owner.Name+"/"+repo.Name, models.READABLE) if err != nil { ctx.Handle(500, "HasAccess", err) return } else if !hasAccess { ctx.Handle(404, "HasAccess", nil) return } } ctx.Repo.HasAccess = true 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 = "/" + u.Name + "/" + repo.Name ctx.Data["RepoLink"] = ctx.Repo.RepoLink tags, err := ctx.Repo.GitRepo.GetTags() if err != nil { ctx.Handle(500, "GetTags", err) return } ctx.Repo.Repository.NumTags = len(tags) 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["IsRepositoryTrueOwner"] = ctx.Repo.IsTrueOwner if setting.SshPort != 22 { ctx.Repo.CloneLink.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.Domain, setting.SshPort, u.LowerName, repo.LowerName) } else { ctx.Repo.CloneLink.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.Domain, u.LowerName, repo.LowerName) } ctx.Repo.CloneLink.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, u.LowerName, repo.LowerName) ctx.Data["CloneLink"] = ctx.Repo.CloneLink if ctx.Repo.Repository.IsGoget { ctx.Data["GoGetLink"] = fmt.Sprintf("%s%s/%s", setting.AppUrl, u.LowerName, repo.LowerName) ctx.Data["GoGetImport"] = fmt.Sprintf("%s/%s/%s", setting.Domain, u.LowerName, repo.LowerName) } // when repo is bare, not valid branch if !ctx.Repo.Repository.IsBare && validBranch { detect: if len(refName) > 0 { if gitRepo.IsBranchExist(refName) { ctx.Repo.IsBranch = true ctx.Repo.BranchName = refName ctx.Repo.Commit, err = gitRepo.GetCommitOfBranch(refName) if err != nil { ctx.Handle(404, "RepoAssignment invalid branch", nil) return } ctx.Repo.CommitId = ctx.Repo.Commit.Id.String() } else if gitRepo.IsTagExist(refName) { ctx.Repo.IsTag = true ctx.Repo.BranchName = refName ctx.Repo.Tag, err = gitRepo.GetTag(refName) if err != nil { ctx.Handle(404, "RepoAssignment invalid tag", nil) return } ctx.Repo.Commit, _ = ctx.Repo.Tag.Commit() ctx.Repo.CommitId = ctx.Repo.Commit.Id.String() } else if len(refName) == 40 { ctx.Repo.IsCommit = true ctx.Repo.CommitId = refName ctx.Repo.BranchName = refName ctx.Repo.Commit, err = gitRepo.GetCommit(refName) if err != nil { ctx.Handle(404, "RepoAssignment invalid commit", nil) return } } else { ctx.Handle(404, "RepoAssignment invalid repo", errors.New("branch or tag not exist")) return } } else { if len(refName) == 0 { if gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) { refName = ctx.Repo.Repository.DefaultBranch } else { brs, err := gitRepo.GetBranches() if err != nil { ctx.Handle(500, "GetBranches", err) return } refName = brs[0] } } goto detect } ctx.Data["IsBranch"] = ctx.Repo.IsBranch ctx.Data["IsCommit"] = ctx.Repo.IsCommit ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount() if err != nil { ctx.Handle(500, "CommitsCount", err) return } ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount } // repo is bare and display enable if ctx.Repo.Repository.IsBare { log.Debug("Bare repository: %s", ctx.Repo.RepoLink) 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 { log.Error(4, "GetBranches: %v", err) } 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 ctx.Repo.BranchName == "" { if ctx.Repo.Repository.DefaultBranch != "" && 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 } }
// SendResetPasswordMail sends reset password e-mail. func SendResetPasswordMail(c *macaron.Context, u *models.User) { SendUserMail(c, u, AUTH_RESET_PASSWORD, u.GenerateActivateCode(), c.Tr("mail.reset_password"), "reset password") }
func SendActivateAccountMail(c *macaron.Context, u *models.User) { SendUserMail(c, u, AUTH_ACTIVATE, u.GenerateActivateCode(), c.Tr("mail.activate_account"), "activate account") }