Merge remote-tracking branch 'upstream/main' into limit-repo-size

This commit is contained in:
DmitryFrolovTri
2023-02-17 04:41:27 +00:00
185 changed files with 1502 additions and 995 deletions
-1
View File
@@ -6,7 +6,6 @@ Kim Carlbäcker <kim.carlbacker@gmail.com> (@bkcsoft)
LefsFlare <nobody@nobody.tld> (@LefsFlarey)
Lunny Xiao <xiaolunwen@gmail.com> (@lunny)
Matthias Loibl <mail@matthiasloibl.com> (@metalmatze)
Morgan Bazalgette <the@howl.moe> (@thehowl)
Rachid Zarouali <nobody@nobody.tld> (@xinity)
Rémy Boulanouar <admin@dblk.org> (@DblK)
Sandro Santilli <strk@kbt.io> (@strk)
-406
View File
@@ -5,7 +5,6 @@
package cmd
import (
"context"
"errors"
"fmt"
"os"
@@ -16,20 +15,15 @@ import (
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/log"
pwd "code.gitea.io/gitea/modules/password"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/storage"
"code.gitea.io/gitea/modules/util"
auth_service "code.gitea.io/gitea/services/auth"
"code.gitea.io/gitea/services/auth/source/oauth2"
"code.gitea.io/gitea/services/auth/source/smtp"
repo_service "code.gitea.io/gitea/services/repository"
user_service "code.gitea.io/gitea/services/user"
"github.com/urfave/cli"
)
@@ -48,147 +42,6 @@ var (
},
}
subcmdUser = cli.Command{
Name: "user",
Usage: "Modify users",
Subcommands: []cli.Command{
microcmdUserCreate,
microcmdUserList,
microcmdUserChangePassword,
microcmdUserDelete,
microcmdUserGenerateAccessToken,
},
}
microcmdUserList = cli.Command{
Name: "list",
Usage: "List users",
Action: runListUsers,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "admin",
Usage: "List only admin users",
},
},
}
microcmdUserCreate = cli.Command{
Name: "create",
Usage: "Create a new user in database",
Action: runCreateUser,
Flags: []cli.Flag{
cli.StringFlag{
Name: "name",
Usage: "Username. DEPRECATED: use username instead",
},
cli.StringFlag{
Name: "username",
Usage: "Username",
},
cli.StringFlag{
Name: "password",
Usage: "User password",
},
cli.StringFlag{
Name: "email",
Usage: "User email address",
},
cli.BoolFlag{
Name: "admin",
Usage: "User is an admin",
},
cli.BoolFlag{
Name: "random-password",
Usage: "Generate a random password for the user",
},
cli.BoolFlag{
Name: "must-change-password",
Usage: "Set this option to false to prevent forcing the user to change their password after initial login, (Default: true)",
},
cli.IntFlag{
Name: "random-password-length",
Usage: "Length of the random password to be generated",
Value: 12,
},
cli.BoolFlag{
Name: "access-token",
Usage: "Generate access token for the user",
},
cli.BoolFlag{
Name: "restricted",
Usage: "Make a restricted user account",
},
},
}
microcmdUserChangePassword = cli.Command{
Name: "change-password",
Usage: "Change a user's password",
Action: runChangePassword,
Flags: []cli.Flag{
cli.StringFlag{
Name: "username,u",
Value: "",
Usage: "The user to change password for",
},
cli.StringFlag{
Name: "password,p",
Value: "",
Usage: "New password to set for user",
},
},
}
microcmdUserDelete = cli.Command{
Name: "delete",
Usage: "Delete specific user by id, name or email",
Flags: []cli.Flag{
cli.Int64Flag{
Name: "id",
Usage: "ID of user of the user to delete",
},
cli.StringFlag{
Name: "username,u",
Usage: "Username of the user to delete",
},
cli.StringFlag{
Name: "email,e",
Usage: "Email of the user to delete",
},
cli.BoolFlag{
Name: "purge",
Usage: "Purge user, all their repositories, organizations and comments",
},
},
Action: runDeleteUser,
}
microcmdUserGenerateAccessToken = cli.Command{
Name: "generate-access-token",
Usage: "Generate a access token for a specific user",
Flags: []cli.Flag{
cli.StringFlag{
Name: "username,u",
Usage: "Username",
},
cli.StringFlag{
Name: "token-name,t",
Usage: "Token name",
Value: "gitea-admin",
},
cli.BoolFlag{
Name: "raw",
Usage: "Display only the token value",
},
cli.StringFlag{
Name: "scopes",
Value: "",
Usage: "Comma separated list of scopes to apply to access token",
},
},
Action: runGenerateAccessToken,
}
subcmdRepoSyncReleases = cli.Command{
Name: "repo-sync-releases",
Usage: "Synchronize repository releases with tags",
@@ -486,265 +339,6 @@ var (
}
)
func runChangePassword(c *cli.Context) error {
if err := argsSet(c, "username", "password"); err != nil {
return err
}
ctx, cancel := installSignals()
defer cancel()
if err := initDB(ctx); err != nil {
return err
}
if len(c.String("password")) < setting.MinPasswordLength {
return fmt.Errorf("Password is not long enough. Needs to be at least %d", setting.MinPasswordLength)
}
if !pwd.IsComplexEnough(c.String("password")) {
return errors.New("Password does not meet complexity requirements")
}
pwned, err := pwd.IsPwned(context.Background(), c.String("password"))
if err != nil {
return err
}
if pwned {
return errors.New("The password you chose is on a list of stolen passwords previously exposed in public data breaches. Please try again with a different password.\nFor more details, see https://haveibeenpwned.com/Passwords")
}
uname := c.String("username")
user, err := user_model.GetUserByName(ctx, uname)
if err != nil {
return err
}
if err = user.SetPassword(c.String("password")); err != nil {
return err
}
if err = user_model.UpdateUserCols(ctx, user, "passwd", "passwd_hash_algo", "salt"); err != nil {
return err
}
fmt.Printf("%s's password has been successfully updated!\n", user.Name)
return nil
}
func runCreateUser(c *cli.Context) error {
if err := argsSet(c, "email"); err != nil {
return err
}
if c.IsSet("name") && c.IsSet("username") {
return errors.New("Cannot set both --name and --username flags")
}
if !c.IsSet("name") && !c.IsSet("username") {
return errors.New("One of --name or --username flags must be set")
}
if c.IsSet("password") && c.IsSet("random-password") {
return errors.New("cannot set both -random-password and -password flags")
}
var username string
if c.IsSet("username") {
username = c.String("username")
} else {
username = c.String("name")
fmt.Fprintf(os.Stderr, "--name flag is deprecated. Use --username instead.\n")
}
ctx, cancel := installSignals()
defer cancel()
if err := initDB(ctx); err != nil {
return err
}
var password string
if c.IsSet("password") {
password = c.String("password")
} else if c.IsSet("random-password") {
var err error
password, err = pwd.Generate(c.Int("random-password-length"))
if err != nil {
return err
}
fmt.Printf("generated random password is '%s'\n", password)
} else {
return errors.New("must set either password or random-password flag")
}
// always default to true
changePassword := true
// If this is the first user being created.
// Take it as the admin and don't force a password update.
if n := user_model.CountUsers(nil); n == 0 {
changePassword = false
}
if c.IsSet("must-change-password") {
changePassword = c.Bool("must-change-password")
}
restricted := util.OptionalBoolNone
if c.IsSet("restricted") {
restricted = util.OptionalBoolOf(c.Bool("restricted"))
}
// default user visibility in app.ini
visibility := setting.Service.DefaultUserVisibilityMode
u := &user_model.User{
Name: username,
Email: c.String("email"),
Passwd: password,
IsAdmin: c.Bool("admin"),
MustChangePassword: changePassword,
Visibility: visibility,
}
overwriteDefault := &user_model.CreateUserOverwriteOptions{
IsActive: util.OptionalBoolTrue,
IsRestricted: restricted,
}
if err := user_model.CreateUser(u, overwriteDefault); err != nil {
return fmt.Errorf("CreateUser: %w", err)
}
if c.Bool("access-token") {
t := &auth_model.AccessToken{
Name: "gitea-admin",
UID: u.ID,
}
if err := auth_model.NewAccessToken(t); err != nil {
return err
}
fmt.Printf("Access token was successfully created... %s\n", t.Token)
}
fmt.Printf("New user '%s' has been successfully created!\n", username)
return nil
}
func runListUsers(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
if err := initDB(ctx); err != nil {
return err
}
users, err := user_model.GetAllUsers()
if err != nil {
return err
}
w := tabwriter.NewWriter(os.Stdout, 5, 0, 1, ' ', 0)
if c.IsSet("admin") {
fmt.Fprintf(w, "ID\tUsername\tEmail\tIsActive\n")
for _, u := range users {
if u.IsAdmin {
fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", u.ID, u.Name, u.Email, u.IsActive)
}
}
} else {
twofa := user_model.UserList(users).GetTwoFaStatus()
fmt.Fprintf(w, "ID\tUsername\tEmail\tIsActive\tIsAdmin\t2FA\n")
for _, u := range users {
fmt.Fprintf(w, "%d\t%s\t%s\t%t\t%t\t%t\n", u.ID, u.Name, u.Email, u.IsActive, u.IsAdmin, twofa[u.ID])
}
}
w.Flush()
return nil
}
func runDeleteUser(c *cli.Context) error {
if !c.IsSet("id") && !c.IsSet("username") && !c.IsSet("email") {
return fmt.Errorf("You must provide the id, username or email of a user to delete")
}
ctx, cancel := installSignals()
defer cancel()
if err := initDB(ctx); err != nil {
return err
}
if err := storage.Init(); err != nil {
return err
}
var err error
var user *user_model.User
if c.IsSet("email") {
user, err = user_model.GetUserByEmail(c.String("email"))
} else if c.IsSet("username") {
user, err = user_model.GetUserByName(ctx, c.String("username"))
} else {
user, err = user_model.GetUserByID(ctx, c.Int64("id"))
}
if err != nil {
return err
}
if c.IsSet("username") && user.LowerName != strings.ToLower(strings.TrimSpace(c.String("username"))) {
return fmt.Errorf("The user %s who has email %s does not match the provided username %s", user.Name, c.String("email"), c.String("username"))
}
if c.IsSet("id") && user.ID != c.Int64("id") {
return fmt.Errorf("The user %s does not match the provided id %d", user.Name, c.Int64("id"))
}
return user_service.DeleteUser(ctx, user, c.Bool("purge"))
}
func runGenerateAccessToken(c *cli.Context) error {
if !c.IsSet("username") {
return fmt.Errorf("You must provide the username to generate a token for them")
}
ctx, cancel := installSignals()
defer cancel()
if err := initDB(ctx); err != nil {
return err
}
user, err := user_model.GetUserByName(ctx, c.String("username"))
if err != nil {
return err
}
accessTokenScope, err := auth_model.AccessTokenScope(c.String("scopes")).Normalize()
if err != nil {
return err
}
t := &auth_model.AccessToken{
Name: c.String("token-name"),
UID: user.ID,
Scope: accessTokenScope,
}
if err := auth_model.NewAccessToken(t); err != nil {
return err
}
if c.Bool("raw") {
fmt.Printf("%s\n", t.Token)
} else {
fmt.Printf("Access token was successfully created: %s\n", t.Token)
}
return nil
}
func runRepoSyncReleases(_ *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
+21
View File
@@ -0,0 +1,21 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package cmd
import (
"github.com/urfave/cli"
)
var subcmdUser = cli.Command{
Name: "user",
Usage: "Modify users",
Subcommands: []cli.Command{
microcmdUserCreate,
microcmdUserList,
microcmdUserChangePassword,
microcmdUserDelete,
microcmdUserGenerateAccessToken,
microcmdUserMustChangePassword,
},
}
+76
View File
@@ -0,0 +1,76 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package cmd
import (
"context"
"errors"
"fmt"
user_model "code.gitea.io/gitea/models/user"
pwd "code.gitea.io/gitea/modules/password"
"code.gitea.io/gitea/modules/setting"
"github.com/urfave/cli"
)
var microcmdUserChangePassword = cli.Command{
Name: "change-password",
Usage: "Change a user's password",
Action: runChangePassword,
Flags: []cli.Flag{
cli.StringFlag{
Name: "username,u",
Value: "",
Usage: "The user to change password for",
},
cli.StringFlag{
Name: "password,p",
Value: "",
Usage: "New password to set for user",
},
},
}
func runChangePassword(c *cli.Context) error {
if err := argsSet(c, "username", "password"); err != nil {
return err
}
ctx, cancel := installSignals()
defer cancel()
if err := initDB(ctx); err != nil {
return err
}
if len(c.String("password")) < setting.MinPasswordLength {
return fmt.Errorf("Password is not long enough. Needs to be at least %d", setting.MinPasswordLength)
}
if !pwd.IsComplexEnough(c.String("password")) {
return errors.New("Password does not meet complexity requirements")
}
pwned, err := pwd.IsPwned(context.Background(), c.String("password"))
if err != nil {
return err
}
if pwned {
return errors.New("The password you chose is on a list of stolen passwords previously exposed in public data breaches. Please try again with a different password.\nFor more details, see https://haveibeenpwned.com/Passwords")
}
uname := c.String("username")
user, err := user_model.GetUserByName(ctx, uname)
if err != nil {
return err
}
if err = user.SetPassword(c.String("password")); err != nil {
return err
}
if err = user_model.UpdateUserCols(ctx, user, "passwd", "passwd_hash_algo", "salt"); err != nil {
return err
}
fmt.Printf("%s's password has been successfully updated!\n", user.Name)
return nil
}
+169
View File
@@ -0,0 +1,169 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package cmd
import (
"errors"
"fmt"
"os"
auth_model "code.gitea.io/gitea/models/auth"
user_model "code.gitea.io/gitea/models/user"
pwd "code.gitea.io/gitea/modules/password"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"github.com/urfave/cli"
)
var microcmdUserCreate = cli.Command{
Name: "create",
Usage: "Create a new user in database",
Action: runCreateUser,
Flags: []cli.Flag{
cli.StringFlag{
Name: "name",
Usage: "Username. DEPRECATED: use username instead",
},
cli.StringFlag{
Name: "username",
Usage: "Username",
},
cli.StringFlag{
Name: "password",
Usage: "User password",
},
cli.StringFlag{
Name: "email",
Usage: "User email address",
},
cli.BoolFlag{
Name: "admin",
Usage: "User is an admin",
},
cli.BoolFlag{
Name: "random-password",
Usage: "Generate a random password for the user",
},
cli.BoolFlag{
Name: "must-change-password",
Usage: "Set this option to false to prevent forcing the user to change their password after initial login, (Default: true)",
},
cli.IntFlag{
Name: "random-password-length",
Usage: "Length of the random password to be generated",
Value: 12,
},
cli.BoolFlag{
Name: "access-token",
Usage: "Generate access token for the user",
},
cli.BoolFlag{
Name: "restricted",
Usage: "Make a restricted user account",
},
},
}
func runCreateUser(c *cli.Context) error {
if err := argsSet(c, "email"); err != nil {
return err
}
if c.IsSet("name") && c.IsSet("username") {
return errors.New("Cannot set both --name and --username flags")
}
if !c.IsSet("name") && !c.IsSet("username") {
return errors.New("One of --name or --username flags must be set")
}
if c.IsSet("password") && c.IsSet("random-password") {
return errors.New("cannot set both -random-password and -password flags")
}
var username string
if c.IsSet("username") {
username = c.String("username")
} else {
username = c.String("name")
fmt.Fprintf(os.Stderr, "--name flag is deprecated. Use --username instead.\n")
}
ctx, cancel := installSignals()
defer cancel()
if err := initDB(ctx); err != nil {
return err
}
var password string
if c.IsSet("password") {
password = c.String("password")
} else if c.IsSet("random-password") {
var err error
password, err = pwd.Generate(c.Int("random-password-length"))
if err != nil {
return err
}
fmt.Printf("generated random password is '%s'\n", password)
} else {
return errors.New("must set either password or random-password flag")
}
// always default to true
changePassword := true
// If this is the first user being created.
// Take it as the admin and don't force a password update.
if n := user_model.CountUsers(nil); n == 0 {
changePassword = false
}
if c.IsSet("must-change-password") {
changePassword = c.Bool("must-change-password")
}
restricted := util.OptionalBoolNone
if c.IsSet("restricted") {
restricted = util.OptionalBoolOf(c.Bool("restricted"))
}
// default user visibility in app.ini
visibility := setting.Service.DefaultUserVisibilityMode
u := &user_model.User{
Name: username,
Email: c.String("email"),
Passwd: password,
IsAdmin: c.Bool("admin"),
MustChangePassword: changePassword,
Visibility: visibility,
}
overwriteDefault := &user_model.CreateUserOverwriteOptions{
IsActive: util.OptionalBoolTrue,
IsRestricted: restricted,
}
if err := user_model.CreateUser(u, overwriteDefault); err != nil {
return fmt.Errorf("CreateUser: %w", err)
}
if c.Bool("access-token") {
t := &auth_model.AccessToken{
Name: "gitea-admin",
UID: u.ID,
}
if err := auth_model.NewAccessToken(t); err != nil {
return err
}
fmt.Printf("Access token was successfully created... %s\n", t.Token)
}
fmt.Printf("New user '%s' has been successfully created!\n", username)
return nil
}
+78
View File
@@ -0,0 +1,78 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package cmd
import (
"fmt"
"strings"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/storage"
user_service "code.gitea.io/gitea/services/user"
"github.com/urfave/cli"
)
var microcmdUserDelete = cli.Command{
Name: "delete",
Usage: "Delete specific user by id, name or email",
Flags: []cli.Flag{
cli.Int64Flag{
Name: "id",
Usage: "ID of user of the user to delete",
},
cli.StringFlag{
Name: "username,u",
Usage: "Username of the user to delete",
},
cli.StringFlag{
Name: "email,e",
Usage: "Email of the user to delete",
},
cli.BoolFlag{
Name: "purge",
Usage: "Purge user, all their repositories, organizations and comments",
},
},
Action: runDeleteUser,
}
func runDeleteUser(c *cli.Context) error {
if !c.IsSet("id") && !c.IsSet("username") && !c.IsSet("email") {
return fmt.Errorf("You must provide the id, username or email of a user to delete")
}
ctx, cancel := installSignals()
defer cancel()
if err := initDB(ctx); err != nil {
return err
}
if err := storage.Init(); err != nil {
return err
}
var err error
var user *user_model.User
if c.IsSet("email") {
user, err = user_model.GetUserByEmail(ctx, c.String("email"))
} else if c.IsSet("username") {
user, err = user_model.GetUserByName(ctx, c.String("username"))
} else {
user, err = user_model.GetUserByID(ctx, c.Int64("id"))
}
if err != nil {
return err
}
if c.IsSet("username") && user.LowerName != strings.ToLower(strings.TrimSpace(c.String("username"))) {
return fmt.Errorf("The user %s who has email %s does not match the provided username %s", user.Name, c.String("email"), c.String("username"))
}
if c.IsSet("id") && user.ID != c.Int64("id") {
return fmt.Errorf("The user %s does not match the provided id %d", user.Name, c.Int64("id"))
}
return user_service.DeleteUser(ctx, user, c.Bool("purge"))
}
+80
View File
@@ -0,0 +1,80 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package cmd
import (
"fmt"
auth_model "code.gitea.io/gitea/models/auth"
user_model "code.gitea.io/gitea/models/user"
"github.com/urfave/cli"
)
var microcmdUserGenerateAccessToken = cli.Command{
Name: "generate-access-token",
Usage: "Generate an access token for a specific user",
Flags: []cli.Flag{
cli.StringFlag{
Name: "username,u",
Usage: "Username",
},
cli.StringFlag{
Name: "token-name,t",
Usage: "Token name",
Value: "gitea-admin",
},
cli.BoolFlag{
Name: "raw",
Usage: "Display only the token value",
},
cli.StringFlag{
Name: "scopes",
Value: "",
Usage: "Comma separated list of scopes to apply to access token",
},
},
Action: runGenerateAccessToken,
}
func runGenerateAccessToken(c *cli.Context) error {
if !c.IsSet("username") {
return fmt.Errorf("You must provide a username to generate a token for")
}
ctx, cancel := installSignals()
defer cancel()
if err := initDB(ctx); err != nil {
return err
}
user, err := user_model.GetUserByName(ctx, c.String("username"))
if err != nil {
return err
}
accessTokenScope, err := auth_model.AccessTokenScope(c.String("scopes")).Normalize()
if err != nil {
return err
}
t := &auth_model.AccessToken{
Name: c.String("token-name"),
UID: user.ID,
Scope: accessTokenScope,
}
if err := auth_model.NewAccessToken(t); err != nil {
return err
}
if c.Bool("raw") {
fmt.Printf("%s\n", t.Token)
} else {
fmt.Printf("Access token was successfully created: %s\n", t.Token)
}
return nil
}
+60
View File
@@ -0,0 +1,60 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package cmd
import (
"fmt"
"os"
"text/tabwriter"
user_model "code.gitea.io/gitea/models/user"
"github.com/urfave/cli"
)
var microcmdUserList = cli.Command{
Name: "list",
Usage: "List users",
Action: runListUsers,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "admin",
Usage: "List only admin users",
},
},
}
func runListUsers(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
if err := initDB(ctx); err != nil {
return err
}
users, err := user_model.GetAllUsers()
if err != nil {
return err
}
w := tabwriter.NewWriter(os.Stdout, 5, 0, 1, ' ', 0)
if c.IsSet("admin") {
fmt.Fprintf(w, "ID\tUsername\tEmail\tIsActive\n")
for _, u := range users {
if u.IsAdmin {
fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", u.ID, u.Name, u.Email, u.IsActive)
}
}
} else {
twofa := user_model.UserList(users).GetTwoFaStatus()
fmt.Fprintf(w, "ID\tUsername\tEmail\tIsActive\tIsAdmin\t2FA\n")
for _, u := range users {
fmt.Fprintf(w, "%d\t%s\t%s\t%t\t%t\t%t\n", u.ID, u.Name, u.Email, u.IsActive, u.IsAdmin, twofa[u.ID])
}
}
w.Flush()
return nil
}
+58
View File
@@ -0,0 +1,58 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package cmd
import (
"errors"
"fmt"
user_model "code.gitea.io/gitea/models/user"
"github.com/urfave/cli"
)
var microcmdUserMustChangePassword = cli.Command{
Name: "must-change-password",
Usage: "Set the must change password flag for the provided users or all users",
Action: runMustChangePassword,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "all,A",
Usage: "All users must change password, except those explicitly excluded with --exclude",
},
cli.StringSliceFlag{
Name: "exclude,e",
Usage: "Do not change the must-change-password flag for these users",
},
cli.BoolFlag{
Name: "unset",
Usage: "Instead of setting the must-change-password flag, unset it",
},
},
}
func runMustChangePassword(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
if c.NArg() == 0 && !c.IsSet("all") {
return errors.New("either usernames or --all must be provided")
}
mustChangePassword := !c.Bool("unset")
all := c.Bool("all")
exclude := c.StringSlice("exclude")
if err := initDB(ctx); err != nil {
return err
}
n, err := user_model.SetMustChangePassword(ctx, all, mustChangePassword, c.Args(), exclude)
if err != nil {
return err
}
fmt.Printf("Updated %d users setting MustChangePassword to %t\n", n, mustChangePassword)
return nil
}
+41 -6
View File
@@ -79,6 +79,10 @@ func main() {
Name: "no-xdg-open",
Usage: "Set this flag to not use xdg-open to open the PR URL",
},
cli.BoolFlag{
Name: "continue",
Usage: "Set this flag to continue from a git cherry-pick that has broken",
},
}
cli.AppHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
@@ -104,7 +108,19 @@ func runBackport(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
continuing := c.Bool("continue")
var pr string
version := c.String("version")
if version == "" && continuing {
// determine version from current branch name
var err error
pr, version, err = readCurrentBranch(ctx)
if err != nil {
return err
}
}
if version == "" {
version = readVersion()
}
@@ -135,13 +151,14 @@ func runBackport(c *cli.Context) error {
localReleaseBranch := path.Join(upstream, upstreamReleaseBranch)
args := c.Args()
if len(args) == 0 {
if len(args) == 0 && pr == "" {
return fmt.Errorf("no PR number provided\nProvide a PR number to backport")
} else if len(args) != 1 {
} else if len(args) != 1 && pr == "" {
return fmt.Errorf("multiple PRs provided %v\nOnly a single PR can be backported at a time", args)
}
pr := args[0]
if pr == "" {
pr = args[0]
}
backportBranch := c.String("backport-branch")
if backportBranch == "" {
@@ -168,8 +185,10 @@ func runBackport(c *cli.Context) error {
}
}
if err := checkoutBackportBranch(ctx, backportBranch, localReleaseBranch); err != nil {
return err
if !continuing {
if err := checkoutBackportBranch(ctx, backportBranch, localReleaseBranch); err != nil {
return err
}
}
if err := cherrypick(ctx, sha); err != nil {
@@ -353,6 +372,22 @@ func determineRemote(ctx context.Context, forkUser string) (string, string, erro
return "", "", fmt.Errorf("unable to find appropriate remote in:\n%s", string(out))
}
func readCurrentBranch(ctx context.Context) (pr, version string, err error) {
out, err := exec.CommandContext(ctx, "git", "branch", "--show-current").Output()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to read current git branch:\n%s\n", string(out))
return "", "", fmt.Errorf("unable to read current git branch: %w", err)
}
parts := strings.Split(strings.TrimSpace(string(out)), "-")
if len(parts) != 3 || parts[0] != "backport" {
fmt.Fprintf(os.Stderr, "Unable to continue from git branch:\n%s\n", string(out))
return "", "", fmt.Errorf("unable to continue from git branch:\n%s", string(out))
}
return parts[1], parts[2], nil
}
func readVersion() string {
bs, err := os.ReadFile("docs/config.yaml")
if err != nil {
@@ -99,6 +99,13 @@ Admin operations:
- `--password value`, `-p value`: New password. Required.
- Examples:
- `gitea admin user change-password --username myname --password asecurepassword`
- `must-change-password`:
- Args:
- `[username...]`: Users that must change their passwords
- Options:
- `--all`, `-A`: Force a password change for all users
- `--exclude username`, `-e username`: Exclude the given user. Can be set multiple times.
- `--unset`: Revoke forced password change for the given users
- `regenerate`
- Options:
- `hooks`: Regenerate Git Hooks for all repositories
+3 -3
View File
@@ -97,12 +97,12 @@ func GetActivityStatsTopAuthors(ctx context.Context, repo *repo_model.Repository
}
users := make(map[int64]*ActivityAuthorData)
var unknownUserID int64
unknownUserAvatarLink := user_model.NewGhostUser().AvatarLink()
unknownUserAvatarLink := user_model.NewGhostUser().AvatarLink(ctx)
for _, v := range code.Authors {
if len(v.Email) == 0 {
continue
}
u, err := user_model.GetUserByEmail(v.Email)
u, err := user_model.GetUserByEmail(ctx, v.Email)
if u == nil || user_model.IsErrUserNotExist(err) {
unknownUserID--
users[unknownUserID] = &ActivityAuthorData{
@@ -119,7 +119,7 @@ func GetActivityStatsTopAuthors(ctx context.Context, repo *repo_model.Repository
users[u.ID] = &ActivityAuthorData{
Name: u.DisplayName(),
Login: u.LowerName,
AvatarLink: u.AvatarLink(),
AvatarLink: u.AvatarLink(ctx),
HomeLink: u.HomeLink(),
Commits: v.Commits,
}
@@ -4,6 +4,7 @@
package asymkey
import (
"context"
"fmt"
"hash"
"strings"
@@ -70,14 +71,14 @@ const (
)
// ParseCommitsWithSignature checks if signaute of commits are corresponding to users gpg keys.
func ParseCommitsWithSignature(oldCommits []*user_model.UserCommit, repoTrustModel repo_model.TrustModelType, isOwnerMemberCollaborator func(*user_model.User) (bool, error)) []*SignCommit {
func ParseCommitsWithSignature(ctx context.Context, oldCommits []*user_model.UserCommit, repoTrustModel repo_model.TrustModelType, isOwnerMemberCollaborator func(*user_model.User) (bool, error)) []*SignCommit {
newCommits := make([]*SignCommit, 0, len(oldCommits))
keyMap := map[string]bool{}
for _, c := range oldCommits {
signCommit := &SignCommit{
UserCommit: c,
Verification: ParseCommitWithSignature(c.Commit),
Verification: ParseCommitWithSignature(ctx, c.Commit),
}
_ = CalculateTrustStatus(signCommit.Verification, repoTrustModel, isOwnerMemberCollaborator, &keyMap)
@@ -88,13 +89,13 @@ func ParseCommitsWithSignature(oldCommits []*user_model.UserCommit, repoTrustMod
}
// ParseCommitWithSignature check if signature is good against keystore.
func ParseCommitWithSignature(c *git.Commit) *CommitVerification {
func ParseCommitWithSignature(ctx context.Context, c *git.Commit) *CommitVerification {
var committer *user_model.User
if c.Committer != nil {
var err error
// Find Committer account
committer, err = user_model.GetUserByEmail(c.Committer.Email) // This finds the user by primary email or activated email so commit will not be valid if email is not
if err != nil { // Skipping not user for committer
committer, err = user_model.GetUserByEmail(ctx, c.Committer.Email) // This finds the user by primary email or activated email so commit will not be valid if email is not
if err != nil { // Skipping not user for committer
committer = &user_model.User{
Name: c.Committer.Name,
Email: c.Committer.Email,
+1 -1
View File
@@ -23,7 +23,7 @@ import "code.gitea.io/gitea/models/db"
// GPGKeyImport the original import of key
type GPGKeyImport struct {
KeyID string `xorm:"pk CHAR(16) NOT NULL"`
Content string `xorm:"TEXT NOT NULL"`
Content string `xorm:"MEDIUMTEXT NOT NULL"`
}
func init() {
+7 -7
View File
@@ -147,13 +147,13 @@ func generateRecognizedAvatarURL(u url.URL, size int) string {
// generateEmailAvatarLink returns a email avatar link.
// if final is true, it may use a slow path (eg: query DNS).
// if final is false, it always uses a fast path.
func generateEmailAvatarLink(email string, size int, final bool) string {
func generateEmailAvatarLink(ctx context.Context, email string, size int, final bool) string {
email = strings.TrimSpace(email)
if email == "" {
return DefaultAvatarLink()
}
enableFederatedAvatar := system_model.GetSettingBool(system_model.KeyPictureEnableFederatedAvatar)
enableFederatedAvatar := system_model.GetSettingBool(ctx, system_model.KeyPictureEnableFederatedAvatar)
var err error
if enableFederatedAvatar && system_model.LibravatarService != nil {
@@ -174,7 +174,7 @@ func generateEmailAvatarLink(email string, size int, final bool) string {
return urlStr
}
disableGravatar := system_model.GetSettingBool(system_model.KeyPictureDisableGravatar)
disableGravatar := system_model.GetSettingBool(ctx, system_model.KeyPictureDisableGravatar)
if !disableGravatar {
// copy GravatarSourceURL, because we will modify its Path.
avatarURLCopy := *system_model.GravatarSourceURL
@@ -186,11 +186,11 @@ func generateEmailAvatarLink(email string, size int, final bool) string {
}
// GenerateEmailAvatarFastLink returns a avatar link (fast, the link may be a delegated one: "/avatar/${hash}")
func GenerateEmailAvatarFastLink(email string, size int) string {
return generateEmailAvatarLink(email, size, false)
func GenerateEmailAvatarFastLink(ctx context.Context, email string, size int) string {
return generateEmailAvatarLink(ctx, email, size, false)
}
// GenerateEmailAvatarFinalLink returns a avatar final link (maybe slow)
func GenerateEmailAvatarFinalLink(email string, size int) string {
return generateEmailAvatarLink(email, size, true)
func GenerateEmailAvatarFinalLink(ctx context.Context, email string, size int) string {
return generateEmailAvatarLink(ctx, email, size, true)
}
+6 -5
View File
@@ -7,6 +7,7 @@ import (
"testing"
avatars_model "code.gitea.io/gitea/models/avatars"
"code.gitea.io/gitea/models/db"
system_model "code.gitea.io/gitea/models/system"
"code.gitea.io/gitea/modules/setting"
@@ -16,15 +17,15 @@ import (
const gravatarSource = "https://secure.gravatar.com/avatar/"
func disableGravatar(t *testing.T) {
err := system_model.SetSettingNoVersion(system_model.KeyPictureEnableFederatedAvatar, "false")
err := system_model.SetSettingNoVersion(db.DefaultContext, system_model.KeyPictureEnableFederatedAvatar, "false")
assert.NoError(t, err)
err = system_model.SetSettingNoVersion(system_model.KeyPictureDisableGravatar, "true")
err = system_model.SetSettingNoVersion(db.DefaultContext, system_model.KeyPictureDisableGravatar, "true")
assert.NoError(t, err)
system_model.LibravatarService = nil
}
func enableGravatar(t *testing.T) {
err := system_model.SetSettingNoVersion(system_model.KeyPictureDisableGravatar, "false")
err := system_model.SetSettingNoVersion(db.DefaultContext, system_model.KeyPictureDisableGravatar, "false")
assert.NoError(t, err)
setting.GravatarSource = gravatarSource
err = system_model.Init()
@@ -47,11 +48,11 @@ func TestSizedAvatarLink(t *testing.T) {
disableGravatar(t)
assert.Equal(t, "/testsuburl/assets/img/avatar_default.png",
avatars_model.GenerateEmailAvatarFastLink("gitea@example.com", 100))
avatars_model.GenerateEmailAvatarFastLink(db.DefaultContext, "gitea@example.com", 100))
enableGravatar(t)
assert.Equal(t,
"https://secure.gravatar.com/avatar/353cbad9b58e69c96154ad99f92bedc7?d=identicon&s=100",
avatars_model.GenerateEmailAvatarFastLink("gitea@example.com", 100),
avatars_model.GenerateEmailAvatarFastLink(db.DefaultContext, "gitea@example.com", 100),
)
}
+2 -1
View File
@@ -351,7 +351,8 @@ func hashCommitStatusContext(context string) string {
func ConvertFromGitCommit(ctx context.Context, commits []*git.Commit, repo *repo_model.Repository) []*SignCommitWithStatuses {
return ParseCommitsWithStatus(ctx,
asymkey_model.ParseCommitsWithSignature(
user_model.ValidateCommitsWithEmails(commits),
ctx,
user_model.ValidateCommitsWithEmails(ctx, commits),
repo.GetTrustModel(),
func(user *user_model.User) (bool, error) {
return repo_model.IsOwnerMemberCollaborator(repo, user.ID)
+5
View File
@@ -1244,3 +1244,8 @@ func FixCommentTypeLabelWithOutsideLabels(ctx context.Context) (int64, error) {
return res.RowsAffected()
}
// HasOriginalAuthor returns if a comment was migrated and has an original author.
func (c *Comment) HasOriginalAuthor() bool {
return c.OriginalAuthor != "" && c.OriginalAuthorID != 0
}
+5
View File
@@ -2403,3 +2403,8 @@ func DeleteOrphanedIssues(ctx context.Context) error {
}
return nil
}
// HasOriginalAuthor returns if an issue was migrated and has an original author.
func (issue *Issue) HasOriginalAuthor() bool {
return issue.OriginalAuthor != "" && issue.OriginalAuthorID != 0
}
+2
View File
@@ -457,6 +457,8 @@ var migrations = []Migration{
NewMigration("Add actions tables", v1_19.AddActionsTables),
// v241 -> v242
NewMigration("Add card_type column to project table", v1_19.AddCardTypeToProjectTable),
// v242 -> v243
NewMigration("Alter gpg_key_import content TEXT field to MEDIUMTEXT", v1_19.AlterPublicGPGKeyImportContentFieldToMediumText),
// to modify later
NewMigration("add size limit on repository", v1_19.AddSizeLimitOnRepo),
}
+26
View File
@@ -0,0 +1,26 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package v1_19 //nolint
import (
"code.gitea.io/gitea/modules/setting"
"xorm.io/xorm"
)
// AlterPublicGPGKeyImportContentFieldToMediumText: set GPGKeyImport Content field to MEDIUMTEXT
func AlterPublicGPGKeyImportContentFieldToMediumText(x *xorm.Engine) error {
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
if setting.Database.UseMySQL {
if _, err := sess.Exec("ALTER TABLE `gpg_key_import` CHANGE `content` `content` MEDIUMTEXT"); err != nil {
return err
}
}
return sess.Commit()
}
+2 -2
View File
@@ -156,8 +156,8 @@ func (org *Organization) hasMemberWithUserID(ctx context.Context, userID int64)
}
// AvatarLink returns the full avatar link with http host
func (org *Organization) AvatarLink() string {
return org.AsUser().AvatarLink()
func (org *Organization) AvatarLink(ctx context.Context) string {
return org.AsUser().AvatarLink(ctx)
}
// HTMLURL returns the organization's full link.
+1 -6
View File
@@ -85,12 +85,7 @@ func (repo *Repository) relAvatarLink(ctx context.Context) string {
}
// AvatarLink returns a link to the repository's avatar.
func (repo *Repository) AvatarLink() string {
return repo.avatarLink(db.DefaultContext)
}
// avatarLink returns user avatar absolute link.
func (repo *Repository) avatarLink(ctx context.Context) string {
func (repo *Repository) AvatarLink(ctx context.Context) string {
link := repo.relAvatarLink(ctx)
// we only prepend our AppURL to our known (relative, internal) avatar link to get an absolute URL
if strings.HasPrefix(link, "/") && !strings.HasPrefix(link, "//") {
+33 -26
View File
@@ -80,8 +80,8 @@ func IsErrDataExpired(err error) bool {
}
// GetSettingNoCache returns specific setting without using the cache
func GetSettingNoCache(key string) (*Setting, error) {
v, err := GetSettings([]string{key})
func GetSettingNoCache(ctx context.Context, key string) (*Setting, error) {
v, err := GetSettings(ctx, []string{key})
if err != nil {
return nil, err
}
@@ -91,27 +91,31 @@ func GetSettingNoCache(key string) (*Setting, error) {
return v[strings.ToLower(key)], nil
}
const contextCacheKey = "system_setting"
// GetSetting returns the setting value via the key
func GetSetting(key string) (string, error) {
return cache.GetString(genSettingCacheKey(key), func() (string, error) {
res, err := GetSettingNoCache(key)
if err != nil {
return "", err
}
return res.SettingValue, nil
func GetSetting(ctx context.Context, key string) (string, error) {
return cache.GetWithContextCache(ctx, contextCacheKey, key, func() (string, error) {
return cache.GetString(genSettingCacheKey(key), func() (string, error) {
res, err := GetSettingNoCache(ctx, key)
if err != nil {
return "", err
}
return res.SettingValue, nil
})
})
}
// GetSettingBool return bool value of setting,
// none existing keys and errors are ignored and result in false
func GetSettingBool(key string) bool {
s, _ := GetSetting(key)
func GetSettingBool(ctx context.Context, key string) bool {
s, _ := GetSetting(ctx, key)
v, _ := strconv.ParseBool(s)
return v
}
// GetSettings returns specific settings
func GetSettings(keys []string) (map[string]*Setting, error) {
func GetSettings(ctx context.Context, keys []string) (map[string]*Setting, error) {
for i := 0; i < len(keys); i++ {
keys[i] = strings.ToLower(keys[i])
}
@@ -161,16 +165,17 @@ func GetAllSettings() (AllSettings, error) {
}
// DeleteSetting deletes a specific setting for a user
func DeleteSetting(setting *Setting) error {
func DeleteSetting(ctx context.Context, setting *Setting) error {
cache.RemoveContextData(ctx, contextCacheKey, setting.SettingKey)
cache.Remove(genSettingCacheKey(setting.SettingKey))
_, err := db.GetEngine(db.DefaultContext).Delete(setting)
return err
}
func SetSettingNoVersion(key, value string) error {
s, err := GetSettingNoCache(key)
func SetSettingNoVersion(ctx context.Context, key, value string) error {
s, err := GetSettingNoCache(ctx, key)
if IsErrSettingIsNotExist(err) {
return SetSetting(&Setting{
return SetSetting(ctx, &Setting{
SettingKey: key,
SettingValue: value,
})
@@ -179,11 +184,11 @@ func SetSettingNoVersion(key, value string) error {
return err
}
s.SettingValue = value
return SetSetting(s)
return SetSetting(ctx, s)
}
// SetSetting updates a users' setting for a specific key
func SetSetting(setting *Setting) error {
func SetSetting(ctx context.Context, setting *Setting) error {
if err := upsertSettingValue(strings.ToLower(setting.SettingKey), setting.SettingValue, setting.Version); err != nil {
return err
}
@@ -192,9 +197,11 @@ func SetSetting(setting *Setting) error {
cc := cache.GetCache()
if cc != nil {
return cc.Put(genSettingCacheKey(setting.SettingKey), setting.SettingValue, setting_module.CacheService.TTLSeconds())
if err := cc.Put(genSettingCacheKey(setting.SettingKey), setting.SettingValue, setting_module.CacheService.TTLSeconds()); err != nil {
return err
}
}
cache.SetContextData(ctx, contextCacheKey, setting.SettingKey, setting.SettingValue)
return nil
}
@@ -244,7 +251,7 @@ var (
func Init() error {
var disableGravatar bool
disableGravatarSetting, err := GetSettingNoCache(KeyPictureDisableGravatar)
disableGravatarSetting, err := GetSettingNoCache(db.DefaultContext, KeyPictureDisableGravatar)
if IsErrSettingIsNotExist(err) {
disableGravatar = setting_module.GetDefaultDisableGravatar()
disableGravatarSetting = &Setting{SettingValue: strconv.FormatBool(disableGravatar)}
@@ -255,7 +262,7 @@ func Init() error {
}
var enableFederatedAvatar bool
enableFederatedAvatarSetting, err := GetSettingNoCache(KeyPictureEnableFederatedAvatar)
enableFederatedAvatarSetting, err := GetSettingNoCache(db.DefaultContext, KeyPictureEnableFederatedAvatar)
if IsErrSettingIsNotExist(err) {
enableFederatedAvatar = setting_module.GetDefaultEnableFederatedAvatar(disableGravatar)
enableFederatedAvatarSetting = &Setting{SettingValue: strconv.FormatBool(enableFederatedAvatar)}
@@ -268,13 +275,13 @@ func Init() error {
if setting_module.OfflineMode {
disableGravatar = true
enableFederatedAvatar = false
if !GetSettingBool(KeyPictureDisableGravatar) {
if err := SetSettingNoVersion(KeyPictureDisableGravatar, "true"); err != nil {
if !GetSettingBool(db.DefaultContext, KeyPictureDisableGravatar) {
if err := SetSettingNoVersion(db.DefaultContext, KeyPictureDisableGravatar, "true"); err != nil {
return fmt.Errorf("Failed to set setting %q: %w", KeyPictureDisableGravatar, err)
}
}
if GetSettingBool(KeyPictureEnableFederatedAvatar) {
if err := SetSettingNoVersion(KeyPictureEnableFederatedAvatar, "false"); err != nil {
if GetSettingBool(db.DefaultContext, KeyPictureEnableFederatedAvatar) {
if err := SetSettingNoVersion(db.DefaultContext, KeyPictureEnableFederatedAvatar, "false"); err != nil {
return fmt.Errorf("Failed to set setting %q: %w", KeyPictureEnableFederatedAvatar, err)
}
}
+7 -6
View File
@@ -7,6 +7,7 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/system"
"code.gitea.io/gitea/models/unittest"
@@ -20,24 +21,24 @@ func TestSettings(t *testing.T) {
newSetting := &system.Setting{SettingKey: keyName, SettingValue: "50"}
// create setting
err := system.SetSetting(newSetting)
err := system.SetSetting(db.DefaultContext, newSetting)
assert.NoError(t, err)
// test about saving unchanged values
err = system.SetSetting(newSetting)
err = system.SetSetting(db.DefaultContext, newSetting)
assert.NoError(t, err)
// get specific setting
settings, err := system.GetSettings([]string{keyName})
settings, err := system.GetSettings(db.DefaultContext, []string{keyName})
assert.NoError(t, err)
assert.Len(t, settings, 1)
assert.EqualValues(t, newSetting.SettingValue, settings[strings.ToLower(keyName)].SettingValue)
// updated setting
updatedSetting := &system.Setting{SettingKey: keyName, SettingValue: "100", Version: settings[strings.ToLower(keyName)].Version}
err = system.SetSetting(updatedSetting)
err = system.SetSetting(db.DefaultContext, updatedSetting)
assert.NoError(t, err)
value, err := system.GetSetting(keyName)
value, err := system.GetSetting(db.DefaultContext, keyName)
assert.NoError(t, err)
assert.EqualValues(t, updatedSetting.SettingValue, value)
@@ -48,7 +49,7 @@ func TestSettings(t *testing.T) {
assert.EqualValues(t, updatedSetting.SettingValue, settings[strings.ToLower(updatedSetting.SettingKey)].SettingValue)
// delete setting
err = system.DeleteSetting(&system.Setting{SettingKey: strings.ToLower(keyName)})
err = system.DeleteSetting(db.DefaultContext, &system.Setting{SettingKey: strings.ToLower(keyName)})
assert.NoError(t, err)
settings, err = system.GetAllSettings()
assert.NoError(t, err)
+6 -6
View File
@@ -58,7 +58,7 @@ func GenerateRandomAvatar(ctx context.Context, u *User) error {
}
// AvatarLinkWithSize returns a link to the user's avatar with size. size <= 0 means default size
func (u *User) AvatarLinkWithSize(size int) string {
func (u *User) AvatarLinkWithSize(ctx context.Context, size int) string {
if u.ID == -1 {
// ghost user
return avatars.DefaultAvatarLink()
@@ -67,7 +67,7 @@ func (u *User) AvatarLinkWithSize(size int) string {
useLocalAvatar := false
autoGenerateAvatar := false
disableGravatar := system_model.GetSettingBool(system_model.KeyPictureDisableGravatar)
disableGravatar := system_model.GetSettingBool(ctx, system_model.KeyPictureDisableGravatar)
switch {
case u.UseCustomAvatar:
@@ -79,7 +79,7 @@ func (u *User) AvatarLinkWithSize(size int) string {
if useLocalAvatar {
if u.Avatar == "" && autoGenerateAvatar {
if err := GenerateRandomAvatar(db.DefaultContext, u); err != nil {
if err := GenerateRandomAvatar(ctx, u); err != nil {
log.Error("GenerateRandomAvatar: %v", err)
}
}
@@ -88,12 +88,12 @@ func (u *User) AvatarLinkWithSize(size int) string {
}
return avatars.GenerateUserAvatarImageLink(u.Avatar, size)
}
return avatars.GenerateEmailAvatarFastLink(u.AvatarEmail, size)
return avatars.GenerateEmailAvatarFastLink(ctx, u.AvatarEmail, size)
}
// AvatarLink returns the full avatar link with http host
func (u *User) AvatarLink() string {
link := u.AvatarLinkWithSize(0)
func (u *User) AvatarLink(ctx context.Context) string {
link := u.AvatarLinkWithSize(ctx, 0)
if !strings.HasPrefix(link, "//") && !strings.Contains(link, "://") {
return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL+"/")
}
+49
View File
@@ -0,0 +1,49 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package user
import (
"context"
"strings"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder"
)
func SetMustChangePassword(ctx context.Context, all, mustChangePassword bool, include, exclude []string) (int64, error) {
sliceTrimSpaceDropEmpty := func(input []string) []string {
output := make([]string, 0, len(input))
for _, in := range input {
in = strings.ToLower(strings.TrimSpace(in))
if in == "" {
continue
}
output = append(output, in)
}
return output
}
var cond builder.Cond
// Only include the users where something changes to get an accurate count
cond = builder.Neq{"must_change_password": mustChangePassword}
if !all {
include = sliceTrimSpaceDropEmpty(include)
if len(include) == 0 {
return 0, util.NewSilentWrapErrorf(util.ErrInvalidArgument, "no users to include provided")
}
cond = cond.And(builder.In("lower_name", include))
}
exclude = sliceTrimSpaceDropEmpty(exclude)
if len(exclude) > 0 {
cond = cond.And(builder.NotIn("lower_name", exclude))
}
return db.GetEngine(ctx).Where(cond).MustCols("must_change_password").Update(&User{MustChangePassword: mustChangePassword})
}
+19 -11
View File
@@ -640,6 +640,11 @@ func CreateUser(u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err e
u.IsRestricted = setting.Service.DefaultUserIsRestricted
u.IsActive = !(setting.Service.RegisterEmailConfirm || setting.Service.RegisterManualConfirm)
// Ensure consistency of the dates.
if u.UpdatedUnix < u.CreatedUnix {
u.UpdatedUnix = u.CreatedUnix
}
// overwrite defaults if set
if len(overwriteDefault) != 0 && overwriteDefault[0] != nil {
overwrite := overwriteDefault[0]
@@ -717,7 +722,15 @@ func CreateUser(u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err e
return err
}
if err = db.Insert(ctx, u); err != nil {
if u.CreatedUnix == 0 {
// Caller expects auto-time for creation & update timestamps.
err = db.Insert(ctx, u)
} else {
// Caller sets the timestamps themselves. They are responsible for ensuring
// both `CreatedUnix` and `UpdatedUnix` are set appropriately.
_, err = db.GetEngine(ctx).NoAutoTime().Insert(u)
}
if err != nil {
return err
}
@@ -1114,11 +1127,11 @@ type UserCommit struct { //revive:disable-line:exported
}
// ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
func ValidateCommitWithEmail(c *git.Commit) *User {
func ValidateCommitWithEmail(ctx context.Context, c *git.Commit) *User {
if c.Author == nil {
return nil
}
u, err := GetUserByEmail(c.Author.Email)
u, err := GetUserByEmail(ctx, c.Author.Email)
if err != nil {
return nil
}
@@ -1126,7 +1139,7 @@ func ValidateCommitWithEmail(c *git.Commit) *User {
}
// ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
func ValidateCommitsWithEmails(ctx context.Context, oldCommits []*git.Commit) []*UserCommit {
var (
emails = make(map[string]*User)
newCommits = make([]*UserCommit, 0, len(oldCommits))
@@ -1135,7 +1148,7 @@ func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
var u *User
if c.Author != nil {
if v, ok := emails[c.Author.Email]; !ok {
u, _ = GetUserByEmail(c.Author.Email)
u, _ = GetUserByEmail(ctx, c.Author.Email)
emails[c.Author.Email] = u
} else {
u = v
@@ -1151,12 +1164,7 @@ func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
}
// GetUserByEmail returns the user object by given e-mail if exists.
func GetUserByEmail(email string) (*User, error) {
return GetUserByEmailContext(db.DefaultContext, email)
}
// GetUserByEmailContext returns the user object by given e-mail if exists with db context
func GetUserByEmailContext(ctx context.Context, email string) (*User, error) {
func GetUserByEmail(ctx context.Context, email string) (*User, error) {
if len(email) == 0 {
return nil, ErrUserNotExist{0, email, 0}
}
+55
View File
@@ -4,9 +4,11 @@
package user_test
import (
"context"
"math/rand"
"strings"
"testing"
"time"
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
@@ -14,6 +16,7 @@ import (
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert"
@@ -252,6 +255,58 @@ func TestCreateUserEmailAlreadyUsed(t *testing.T) {
assert.True(t, user_model.IsErrEmailAlreadyUsed(err))
}
func TestCreateUserCustomTimestamps(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
// Add new user with a custom creation timestamp.
var creationTimestamp timeutil.TimeStamp = 12345
user.Name = "testuser"
user.LowerName = strings.ToLower(user.Name)
user.ID = 0
user.Email = "unique@example.com"
user.CreatedUnix = creationTimestamp
err := user_model.CreateUser(user)
assert.NoError(t, err)
fetched, err := user_model.GetUserByID(context.Background(), user.ID)
assert.NoError(t, err)
assert.Equal(t, creationTimestamp, fetched.CreatedUnix)
assert.Equal(t, creationTimestamp, fetched.UpdatedUnix)
}
func TestCreateUserWithoutCustomTimestamps(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
// There is no way to use a mocked time for the XORM auto-time functionality,
// so use the real clock to approximate the expected timestamp.
timestampStart := time.Now().Unix()
// Add new user without a custom creation timestamp.
user.Name = "Testuser"
user.LowerName = strings.ToLower(user.Name)
user.ID = 0
user.Email = "unique@example.com"
user.CreatedUnix = 0
user.UpdatedUnix = 0
err := user_model.CreateUser(user)
assert.NoError(t, err)
timestampEnd := time.Now().Unix()
fetched, err := user_model.GetUserByID(context.Background(), user.ID)
assert.NoError(t, err)
assert.LessOrEqual(t, timestampStart, fetched.CreatedUnix)
assert.LessOrEqual(t, fetched.CreatedUnix, timestampEnd)
assert.LessOrEqual(t, timestampStart, fetched.UpdatedUnix)
assert.LessOrEqual(t, fetched.UpdatedUnix, timestampEnd)
}
func TestGetUserIDsByNames(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
+2 -1
View File
@@ -8,6 +8,7 @@ import (
"encoding/gob"
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
@@ -62,7 +63,7 @@ func (u *User) WebAuthnDisplayName() string {
// WebAuthnIcon implements the webauthn.User interface
func (u *User) WebAuthnIcon() string {
return (*user_model.User)(u).AvatarLink()
return (*user_model.User)(u).AvatarLink(db.DefaultContext)
}
// WebAuthnCredentials implementns the webauthn.User interface
+92
View File
@@ -0,0 +1,92 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package cache
import (
"context"
"sync"
"code.gitea.io/gitea/modules/log"
)
// cacheContext is a context that can be used to cache data in a request level context
// This is useful for caching data that is expensive to calculate and is likely to be
// used multiple times in a request.
type cacheContext struct {
ctx context.Context
data map[any]map[any]any
lock sync.RWMutex
}
func (cc *cacheContext) Get(tp, key any) any {
cc.lock.RLock()
defer cc.lock.RUnlock()
if cc.data[tp] == nil {
return nil
}
return cc.data[tp][key]
}
func (cc *cacheContext) Put(tp, key, value any) {
cc.lock.Lock()
defer cc.lock.Unlock()
if cc.data[tp] == nil {
cc.data[tp] = make(map[any]any)
}
cc.data[tp][key] = value
}
func (cc *cacheContext) Delete(tp, key any) {
cc.lock.Lock()
defer cc.lock.Unlock()
if cc.data[tp] == nil {
return
}
delete(cc.data[tp], key)
}
var cacheContextKey = struct{}{}
func WithCacheContext(ctx context.Context) context.Context {
return context.WithValue(ctx, cacheContextKey, &cacheContext{
ctx: ctx,
data: make(map[any]map[any]any),
})
}
func GetContextData(ctx context.Context, tp, key any) any {
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
return c.Get(tp, key)
}
log.Warn("cannot get cache context when getting data: %v", ctx)
return nil
}
func SetContextData(ctx context.Context, tp, key, value any) {
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
c.Put(tp, key, value)
return
}
log.Warn("cannot get cache context when setting data: %v", ctx)
}
func RemoveContextData(ctx context.Context, tp, key any) {
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
c.Delete(tp, key)
}
}
// GetWithContextCache returns the cache value of the given key in the given context.
func GetWithContextCache[T any](ctx context.Context, cacheGroupKey string, cacheTargetID any, f func() (T, error)) (T, error) {
v := GetContextData(ctx, cacheGroupKey, cacheTargetID)
if vv, ok := v.(T); ok {
return vv, nil
}
t, err := f()
if err != nil {
return t, err
}
SetContextData(ctx, cacheGroupKey, cacheTargetID, t)
return t, nil
}
+41
View File
@@ -0,0 +1,41 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package cache
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
)
func TestWithCacheContext(t *testing.T) {
ctx := WithCacheContext(context.Background())
v := GetContextData(ctx, "empty_field", "my_config1")
assert.Nil(t, v)
const field = "system_setting"
v = GetContextData(ctx, field, "my_config1")
assert.Nil(t, v)
SetContextData(ctx, field, "my_config1", 1)
v = GetContextData(ctx, field, "my_config1")
assert.NotNil(t, v)
assert.EqualValues(t, 1, v.(int))
RemoveContextData(ctx, field, "my_config1")
RemoveContextData(ctx, field, "my_config2") // remove an non-exist key
v = GetContextData(ctx, field, "my_config1")
assert.Nil(t, v)
vInt, err := GetWithContextCache(ctx, field, "my_config1", func() (int, error) {
return 1, nil
})
assert.NoError(t, err)
assert.EqualValues(t, 1, vInt)
v = GetContextData(ctx, field, "my_config1")
assert.EqualValues(t, 1, v)
}
+2 -1
View File
@@ -101,12 +101,13 @@ func (te *TreeEntry) FollowLinks() (*TreeEntry, error) {
return entry, nil
}
// returns the subtree, or nil if this is not a tree
// returns the Tree pointed to by this TreeEntry, or nil if this is not a tree
func (te *TreeEntry) Tree() *Tree {
t, err := te.ptree.repo.getTree(te.ID)
if err != nil {
return nil
}
t.ptree = te.ptree
return t
}
+4 -4
View File
@@ -5,6 +5,7 @@ package gitgraph
import (
"bytes"
"context"
"fmt"
"strings"
@@ -88,9 +89,8 @@ func (graph *Graph) AddCommit(row, column int, flowID int64, data []byte) error
// LoadAndProcessCommits will load the git.Commits for each commit in the graph,
// the associate the commit with the user author, and check the commit verification
// before finally retrieving the latest status
func (graph *Graph) LoadAndProcessCommits(repository *repo_model.Repository, gitRepo *git.Repository) error {
func (graph *Graph) LoadAndProcessCommits(ctx context.Context, repository *repo_model.Repository, gitRepo *git.Repository) error {
var err error
var ok bool
emails := map[string]*user_model.User{}
@@ -108,12 +108,12 @@ func (graph *Graph) LoadAndProcessCommits(repository *repo_model.Repository, git
if c.Commit.Author != nil {
email := c.Commit.Author.Email
if c.User, ok = emails[email]; !ok {
c.User, _ = user_model.GetUserByEmail(email)
c.User, _ = user_model.GetUserByEmail(ctx, email)
emails[email] = c.User
}
}
c.Verification = asymkey_model.ParseCommitWithSignature(c.Commit)
c.Verification = asymkey_model.ParseCommitWithSignature(ctx, c.Commit)
_ = asymkey_model.CalculateTrustStatus(c.Verification, repository.GetTrustModel(), func(user *user_model.User) (bool, error) {
return repo_model.IsOwnerMemberCollaborator(repository, user.ID)
+6 -6
View File
@@ -53,7 +53,7 @@ func (pc *PushCommits) toAPIPayloadCommit(ctx context.Context, repoPath, repoLin
authorUsername := ""
author, ok := pc.emailUsers[commit.AuthorEmail]
if !ok {
author, err = user_model.GetUserByEmail(commit.AuthorEmail)
author, err = user_model.GetUserByEmail(ctx, commit.AuthorEmail)
if err == nil {
authorUsername = author.Name
pc.emailUsers[commit.AuthorEmail] = author
@@ -65,7 +65,7 @@ func (pc *PushCommits) toAPIPayloadCommit(ctx context.Context, repoPath, repoLin
committerUsername := ""
committer, ok := pc.emailUsers[commit.CommitterEmail]
if !ok {
committer, err = user_model.GetUserByEmail(commit.CommitterEmail)
committer, err = user_model.GetUserByEmail(ctx, commit.CommitterEmail)
if err == nil {
// TODO: check errors other than email not found.
committerUsername = committer.Name
@@ -133,7 +133,7 @@ func (pc *PushCommits) ToAPIPayloadCommits(ctx context.Context, repoPath, repoLi
// AvatarLink tries to match user in database with e-mail
// in order to show custom avatar, and falls back to general avatar link.
func (pc *PushCommits) AvatarLink(email string) string {
func (pc *PushCommits) AvatarLink(ctx context.Context, email string) string {
if pc.avatars == nil {
pc.avatars = make(map[string]string)
}
@@ -147,9 +147,9 @@ func (pc *PushCommits) AvatarLink(email string) string {
u, ok := pc.emailUsers[email]
if !ok {
var err error
u, err = user_model.GetUserByEmail(email)
u, err = user_model.GetUserByEmail(ctx, email)
if err != nil {
pc.avatars[email] = avatars.GenerateEmailAvatarFastLink(email, size)
pc.avatars[email] = avatars.GenerateEmailAvatarFastLink(ctx, email, size)
if !user_model.IsErrUserNotExist(err) {
log.Error("GetUserByEmail: %v", err)
return ""
@@ -159,7 +159,7 @@ func (pc *PushCommits) AvatarLink(email string) string {
}
}
if u != nil {
pc.avatars[email] = u.AvatarLinkWithSize(size)
pc.avatars[email] = u.AvatarLinkWithSize(ctx, size)
}
return pc.avatars[email]
+4 -3
View File
@@ -9,6 +9,7 @@ import (
"testing"
"time"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
system_model "code.gitea.io/gitea/models/system"
"code.gitea.io/gitea/models/unittest"
@@ -102,7 +103,7 @@ func TestPushCommits_ToAPIPayloadCommits(t *testing.T) {
}
func enableGravatar(t *testing.T) {
err := system_model.SetSettingNoVersion(system_model.KeyPictureDisableGravatar, "false")
err := system_model.SetSettingNoVersion(db.DefaultContext, system_model.KeyPictureDisableGravatar, "false")
assert.NoError(t, err)
setting.GravatarSource = "https://secure.gravatar.com/avatar"
err = system_model.Init()
@@ -136,13 +137,13 @@ func TestPushCommits_AvatarLink(t *testing.T) {
assert.Equal(t,
"https://secure.gravatar.com/avatar/ab53a2911ddf9b4817ac01ddcd3d975f?d=identicon&s=84",
pushCommits.AvatarLink("user2@example.com"))
pushCommits.AvatarLink(db.DefaultContext, "user2@example.com"))
assert.Equal(t,
"https://secure.gravatar.com/avatar/"+
fmt.Sprintf("%x", md5.Sum([]byte("nonexistent@example.com")))+
"?d=identicon&s=84",
pushCommits.AvatarLink("nonexistent@example.com"))
pushCommits.AvatarLink(db.DefaultContext, "nonexistent@example.com"))
}
func TestCommitToPushCommit(t *testing.T) {
+3 -3
View File
@@ -318,7 +318,7 @@ func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository)
return nil
}
if err := PushUpdateAddTag(repo, gitRepo, tagName, sha1, refname); err != nil {
if err := PushUpdateAddTag(db.DefaultContext, repo, gitRepo, tagName, sha1, refname); err != nil {
return fmt.Errorf("unable to PushUpdateAddTag: %q to Repo[%d:%s/%s]: %w", tagName, repo.ID, repo.OwnerName, repo.Name, err)
}
@@ -328,7 +328,7 @@ func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository)
}
// PushUpdateAddTag must be called for any push actions to add tag
func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagName, sha1, refname string) error {
func PushUpdateAddTag(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, tagName, sha1, refname string) error {
tag, err := gitRepo.GetTagWithID(sha1, tagName)
if err != nil {
return fmt.Errorf("unable to GetTag: %w", err)
@@ -350,7 +350,7 @@ func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagN
createdAt := time.Unix(1, 0)
if sig != nil {
author, err = user_model.GetUserByEmail(sig.Email)
author, err = user_model.GetUserByEmail(ctx, sig.Email)
if err != nil && !user_model.IsErrUserNotExist(err) {
return fmt.Errorf("unable to GetUserByEmail for %q: %w", sig.Email, err)
}
+7
View File
@@ -4,6 +4,8 @@
package structs
import "time"
// CreateUserOption create user options
type CreateUserOption struct {
SourceID int64 `json:"source_id"`
@@ -20,6 +22,11 @@ type CreateUserOption struct {
SendNotify bool `json:"send_notify"`
Restricted *bool `json:"restricted"`
Visibility string `json:"visibility" binding:"In(,public,limited,private)"`
// For explicitly setting the user creation timestamp. Useful when users are
// migrated from other systems. When omitted, the user's creation timestamp
// will be set to "now".
Created *time.Time `json:"created_at"`
}
// EditUserOption edit user options
+11 -12
View File
@@ -25,7 +25,6 @@ import (
activities_model "code.gitea.io/gitea/models/activities"
"code.gitea.io/gitea/models/avatars"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/organization"
repo_model "code.gitea.io/gitea/models/repo"
@@ -90,8 +89,8 @@ func NewFuncMap() []template.FuncMap {
"AssetVersion": func() string {
return setting.AssetVersion
},
"DisableGravatar": func() bool {
return system_model.GetSettingBool(system_model.KeyPictureDisableGravatar)
"DisableGravatar": func(ctx context.Context) bool {
return system_model.GetSettingBool(ctx, system_model.KeyPictureDisableGravatar)
},
"DefaultShowFullName": func() bool {
return setting.UI.DefaultShowFullName
@@ -613,22 +612,22 @@ func AvatarHTML(src string, size int, class, name string) template.HTML {
}
// Avatar renders user avatars. args: user, size (int), class (string)
func Avatar(item interface{}, others ...interface{}) template.HTML {
func Avatar(ctx context.Context, item interface{}, others ...interface{}) template.HTML {
size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...)
switch t := item.(type) {
case *user_model.User:
src := t.AvatarLinkWithSize(size * setting.Avatar.RenderedSizeFactor)
src := t.AvatarLinkWithSize(ctx, size*setting.Avatar.RenderedSizeFactor)
if src != "" {
return AvatarHTML(src, size, class, t.DisplayName())
}
case *repo_model.Collaborator:
src := t.AvatarLinkWithSize(size * setting.Avatar.RenderedSizeFactor)
src := t.AvatarLinkWithSize(ctx, size*setting.Avatar.RenderedSizeFactor)
if src != "" {
return AvatarHTML(src, size, class, t.DisplayName())
}
case *organization.Organization:
src := t.AsUser().AvatarLinkWithSize(size * setting.Avatar.RenderedSizeFactor)
src := t.AsUser().AvatarLinkWithSize(ctx, size*setting.Avatar.RenderedSizeFactor)
if src != "" {
return AvatarHTML(src, size, class, t.AsUser().DisplayName())
}
@@ -638,9 +637,9 @@ func Avatar(item interface{}, others ...interface{}) template.HTML {
}
// AvatarByAction renders user avatars from action. args: action, size (int), class (string)
func AvatarByAction(action *activities_model.Action, others ...interface{}) template.HTML {
action.LoadActUser(db.DefaultContext)
return Avatar(action.ActUser, others...)
func AvatarByAction(ctx context.Context, action *activities_model.Action, others ...interface{}) template.HTML {
action.LoadActUser(ctx)
return Avatar(ctx, action.ActUser, others...)
}
// RepoAvatar renders repo avatars. args: repo, size(int), class (string)
@@ -655,9 +654,9 @@ func RepoAvatar(repo *repo_model.Repository, others ...interface{}) template.HTM
}
// AvatarByEmail renders avatars by email address. args: email, name, size (int), class (string)
func AvatarByEmail(email, name string, others ...interface{}) template.HTML {
func AvatarByEmail(ctx context.Context, email, name string, others ...interface{}) template.HTML {
size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...)
src := avatars.GenerateEmailAvatarFastLink(email, size*setting.Avatar.RenderedSizeFactor)
src := avatars.GenerateEmailAvatarFastLink(ctx, email, size*setting.Avatar.RenderedSizeFactor)
if src != "" {
return AvatarHTML(src, size, class, name)
+1 -1
View File
@@ -1364,7 +1364,7 @@ issues.commented_at = `commented <a href="#%s">%s</a>`
issues.delete_comment_confirm = Are you sure you want to delete this comment?
issues.context.copy_link = Copy Link
issues.context.quote_reply = Quote Reply
issues.context.reference_issue = Reference in new issue
issues.context.reference_issue = Reference in New Issue
issues.context.edit = Edit
issues.context.delete = Delete
issues.no_content = There is no content yet.
+1 -1
View File
@@ -55,7 +55,7 @@ func Person(ctx *context.APIContext) {
person.Icon = ap.Image{
Type: ap.ImageType,
MediaType: "image/png",
URL: ap.IRI(ctx.ContextUser.AvatarLink()),
URL: ap.IRI(ctx.ContextUser.AvatarLink(ctx)),
}
person.Inbox = ap.IRI(link + "/inbox")
+2 -2
View File
@@ -74,7 +74,7 @@ func CreateOrg(ctx *context.APIContext) {
return
}
ctx.JSON(http.StatusCreated, convert.ToOrganization(org))
ctx.JSON(http.StatusCreated, convert.ToOrganization(ctx, org))
}
// GetAllOrgs API for getting information of all the organizations
@@ -114,7 +114,7 @@ func GetAllOrgs(ctx *context.APIContext) {
}
orgs := make([]*api.Organization, len(users))
for i := range users {
orgs[i] = convert.ToOrganization(organization.OrgFromUser(users[i]))
orgs[i] = convert.ToOrganization(ctx, organization.OrgFromUser(users[i]))
}
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
+12 -3
View File
@@ -20,6 +20,7 @@ import (
"code.gitea.io/gitea/modules/password"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers/api/v1/user"
@@ -120,6 +121,14 @@ func CreateUser(ctx *context.APIContext) {
overwriteDefault.Visibility = &visibility
}
// Update the user creation timestamp. This can only be done after the user
// record has been inserted into the database; the insert intself will always
// set the creation timestamp to "now".
if form.Created != nil {
u.CreatedUnix = timeutil.TimeStamp(form.Created.Unix())
u.UpdatedUnix = u.CreatedUnix
}
if err := user_model.CreateUser(u, overwriteDefault); err != nil {
if user_model.IsErrUserAlreadyExist(err) ||
user_model.IsErrEmailAlreadyUsed(err) ||
@@ -140,7 +149,7 @@ func CreateUser(ctx *context.APIContext) {
if form.SendNotify {
mailer.SendRegisterNotifyMail(u)
}
ctx.JSON(http.StatusCreated, convert.ToUser(u, ctx.Doer))
ctx.JSON(http.StatusCreated, convert.ToUser(ctx, u, ctx.Doer))
}
// EditUser api for modifying a user's information
@@ -280,7 +289,7 @@ func EditUser(ctx *context.APIContext) {
}
log.Trace("Account profile updated by admin (%s): %s", ctx.Doer.Name, ctx.ContextUser.Name)
ctx.JSON(http.StatusOK, convert.ToUser(ctx.ContextUser, ctx.Doer))
ctx.JSON(http.StatusOK, convert.ToUser(ctx, ctx.ContextUser, ctx.Doer))
}
// DeleteUser api for deleting a user
@@ -441,7 +450,7 @@ func GetAllUsers(ctx *context.APIContext) {
results := make([]*api.User, len(users))
for i := range users {
results[i] = convert.ToUser(users[i], ctx.Doer)
results[i] = convert.ToUser(ctx, users[i], ctx.Doer)
}
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
+1 -1
View File
@@ -39,7 +39,7 @@ func listMembers(ctx *context.APIContext, publicOnly bool) {
apiMembers := make([]*api.User, len(members))
for i, member := range members {
apiMembers[i] = convert.ToUser(member, ctx.Doer)
apiMembers[i] = convert.ToUser(ctx, member, ctx.Doer)
}
ctx.SetTotalCountHeader(count)
+5 -5
View File
@@ -42,7 +42,7 @@ func listUserOrgs(ctx *context.APIContext, u *user_model.User) {
apiOrgs := make([]*api.Organization, len(orgs))
for i := range orgs {
apiOrgs[i] = convert.ToOrganization(orgs[i])
apiOrgs[i] = convert.ToOrganization(ctx, orgs[i])
}
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
@@ -211,7 +211,7 @@ func GetAll(ctx *context.APIContext) {
}
orgs := make([]*api.Organization, len(publicOrgs))
for i := range publicOrgs {
orgs[i] = convert.ToOrganization(organization.OrgFromUser(publicOrgs[i]))
orgs[i] = convert.ToOrganization(ctx, organization.OrgFromUser(publicOrgs[i]))
}
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
@@ -274,7 +274,7 @@ func Create(ctx *context.APIContext) {
return
}
ctx.JSON(http.StatusCreated, convert.ToOrganization(org))
ctx.JSON(http.StatusCreated, convert.ToOrganization(ctx, org))
}
// Get get an organization
@@ -298,7 +298,7 @@ func Get(ctx *context.APIContext) {
ctx.NotFound("HasOrgOrUserVisible", nil)
return
}
ctx.JSON(http.StatusOK, convert.ToOrganization(ctx.Org.Organization))
ctx.JSON(http.StatusOK, convert.ToOrganization(ctx, ctx.Org.Organization))
}
// Edit change an organization's information
@@ -344,7 +344,7 @@ func Edit(ctx *context.APIContext) {
return
}
ctx.JSON(http.StatusOK, convert.ToOrganization(org))
ctx.JSON(http.StatusOK, convert.ToOrganization(ctx, org))
}
// Delete an organization
+8 -8
View File
@@ -58,7 +58,7 @@ func ListTeams(ctx *context.APIContext) {
return
}
apiTeams, err := convert.ToTeams(teams, false)
apiTeams, err := convert.ToTeams(ctx, teams, false)
if err != nil {
ctx.Error(http.StatusInternalServerError, "ConvertToTeams", err)
return
@@ -97,7 +97,7 @@ func ListUserTeams(ctx *context.APIContext) {
return
}
apiTeams, err := convert.ToTeams(teams, true)
apiTeams, err := convert.ToTeams(ctx, teams, true)
if err != nil {
ctx.Error(http.StatusInternalServerError, "ConvertToTeams", err)
return
@@ -125,7 +125,7 @@ func GetTeam(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/Team"
apiTeam, err := convert.ToTeam(ctx.Org.Team)
apiTeam, err := convert.ToTeam(ctx, ctx.Org.Team)
if err != nil {
ctx.InternalServerError(err)
return
@@ -223,7 +223,7 @@ func CreateTeam(ctx *context.APIContext) {
return
}
apiTeam, err := convert.ToTeam(team)
apiTeam, err := convert.ToTeam(ctx, team)
if err != nil {
ctx.InternalServerError(err)
return
@@ -306,7 +306,7 @@ func EditTeam(ctx *context.APIContext) {
return
}
apiTeam, err := convert.ToTeam(team)
apiTeam, err := convert.ToTeam(ctx, team)
if err != nil {
ctx.InternalServerError(err)
return
@@ -383,7 +383,7 @@ func GetTeamMembers(ctx *context.APIContext) {
members := make([]*api.User, len(teamMembers))
for i, member := range teamMembers {
members[i] = convert.ToUser(member, ctx.Doer)
members[i] = convert.ToUser(ctx, member, ctx.Doer)
}
ctx.SetTotalCountHeader(int64(ctx.Org.Team.NumMembers))
@@ -428,7 +428,7 @@ func GetTeamMember(ctx *context.APIContext) {
ctx.NotFound()
return
}
ctx.JSON(http.StatusOK, convert.ToUser(u, ctx.Doer))
ctx.JSON(http.StatusOK, convert.ToUser(ctx, u, ctx.Doer))
}
// AddTeamMember api for add a member to a team
@@ -779,7 +779,7 @@ func SearchTeam(ctx *context.APIContext) {
return
}
apiTeams, err := convert.ToTeams(teams, false)
apiTeams, err := convert.ToTeams(ctx, teams, false)
if err != nil {
ctx.InternalServerError(err)
return
+3 -3
View File
@@ -76,7 +76,7 @@ func GetBranch(ctx *context.APIContext) {
return
}
br, err := convert.ToBranch(ctx.Repo.Repository, branch, c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
br, err := convert.ToBranch(ctx, ctx.Repo.Repository, branch, c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
if err != nil {
ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err)
return
@@ -212,7 +212,7 @@ func CreateBranch(ctx *context.APIContext) {
return
}
br, err := convert.ToBranch(ctx.Repo.Repository, branch, commit, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
br, err := convert.ToBranch(ctx, ctx.Repo.Repository, branch, commit, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
if err != nil {
ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err)
return
@@ -284,7 +284,7 @@ func ListBranches(ctx *context.APIContext) {
}
branchProtection := rules.GetFirstMatched(branches[i].Name)
apiBranch, err := convert.ToBranch(ctx.Repo.Repository, branches[i], c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
apiBranch, err := convert.ToBranch(ctx, ctx.Repo.Repository, branches[i], c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
if err != nil {
ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err)
return
+4 -4
View File
@@ -65,7 +65,7 @@ func ListCollaborators(ctx *context.APIContext) {
users := make([]*api.User, len(collaborators))
for i, collaborator := range collaborators {
users[i] = convert.ToUser(collaborator.User, ctx.Doer)
users[i] = convert.ToUser(ctx, collaborator.User, ctx.Doer)
}
ctx.SetTotalCountHeader(count)
@@ -287,7 +287,7 @@ func GetRepoPermissions(ctx *context.APIContext) {
return
}
ctx.JSON(http.StatusOK, convert.ToUserAndPermission(collaborator, ctx.ContextUser, permission.AccessMode))
ctx.JSON(http.StatusOK, convert.ToUserAndPermission(ctx, collaborator, ctx.ContextUser, permission.AccessMode))
}
// GetReviewers return all users that can be requested to review in this repo
@@ -317,7 +317,7 @@ func GetReviewers(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "ListCollaborators", err)
return
}
ctx.JSON(http.StatusOK, convert.ToUsers(ctx.Doer, reviewers))
ctx.JSON(http.StatusOK, convert.ToUsers(ctx, ctx.Doer, reviewers))
}
// GetAssignees return all users that have write access and can be assigned to issues
@@ -347,5 +347,5 @@ func GetAssignees(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "ListCollaborators", err)
return
}
ctx.JSON(http.StatusOK, convert.ToUsers(ctx.Doer, assignees))
ctx.JSON(http.StatusOK, convert.ToUsers(ctx, ctx.Doer, assignees))
}
+2 -2
View File
@@ -69,7 +69,7 @@ func getCommit(ctx *context.APIContext, identifier string) {
return
}
json, err := convert.ToCommit(ctx.Repo.Repository, ctx.Repo.GitRepo, commit, nil, true)
json, err := convert.ToCommit(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, commit, nil, true)
if err != nil {
ctx.Error(http.StatusInternalServerError, "toCommit", err)
return
@@ -217,7 +217,7 @@ func GetAllCommits(ctx *context.APIContext) {
for i, commit := range commits {
// Create json struct
apiCommits[i], err = convert.ToCommit(ctx.Repo.Repository, ctx.Repo.GitRepo, commit, userCache, stat)
apiCommits[i], err = convert.ToCommit(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, commit, userCache, stat)
if err != nil {
ctx.Error(http.StatusInternalServerError, "toCommit", err)
return
+3 -3
View File
@@ -174,7 +174,7 @@ func TestHook(ctx *context.APIContext) {
return
}
commit := convert.ToPayloadCommit(ctx.Repo.Repository, ctx.Repo.Commit)
commit := convert.ToPayloadCommit(ctx, ctx.Repo.Repository, ctx.Repo.Commit)
commitID := ctx.Repo.Commit.ID.String()
if err := webhook_service.PrepareWebhook(ctx, hook, webhook_module.HookEventPush, &api.PushPayload{
@@ -186,8 +186,8 @@ func TestHook(ctx *context.APIContext) {
TotalCommits: 1,
HeadCommit: commit,
Repo: convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeNone),
Pusher: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone),
Sender: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone),
Pusher: convert.ToUserWithAccessMode(ctx, ctx.Doer, perm.AccessModeNone),
Sender: convert.ToUserWithAccessMode(ctx, ctx.Doer, perm.AccessModeNone),
}); err != nil {
ctx.Error(http.StatusInternalServerError, "PrepareWebhook: ", err)
return
+5 -5
View File
@@ -103,7 +103,7 @@ func ListIssueComments(ctx *context.APIContext) {
apiComments := make([]*api.Comment, len(comments))
for i, comment := range comments {
comment.Issue = issue
apiComments[i] = convert.ToComment(comments[i])
apiComments[i] = convert.ToComment(ctx, comments[i])
}
ctx.SetTotalCountHeader(totalCount)
@@ -308,7 +308,7 @@ func ListRepoIssueComments(ctx *context.APIContext) {
return
}
for i := range comments {
apiComments[i] = convert.ToComment(comments[i])
apiComments[i] = convert.ToComment(ctx, comments[i])
}
ctx.SetTotalCountHeader(totalCount)
@@ -368,7 +368,7 @@ func CreateIssueComment(ctx *context.APIContext) {
return
}
ctx.JSON(http.StatusCreated, convert.ToComment(comment))
ctx.JSON(http.StatusCreated, convert.ToComment(ctx, comment))
}
// GetIssueComment Get a comment by ID
@@ -436,7 +436,7 @@ func GetIssueComment(ctx *context.APIContext) {
return
}
ctx.JSON(http.StatusOK, convert.ToComment(comment))
ctx.JSON(http.StatusOK, convert.ToComment(ctx, comment))
}
// EditIssueComment modify a comment of an issue
@@ -561,7 +561,7 @@ func editIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption)
return
}
ctx.JSON(http.StatusOK, convert.ToComment(comment))
ctx.JSON(http.StatusOK, convert.ToComment(ctx, comment))
}
// DeleteIssueComment delete a comment from an issue
+6 -6
View File
@@ -80,7 +80,7 @@ func GetIssueCommentReactions(ctx *context.APIContext) {
var result []api.Reaction
for _, r := range reactions {
result = append(result, api.Reaction{
User: convert.ToUser(r.User, ctx.Doer),
User: convert.ToUser(ctx, r.User, ctx.Doer),
Reaction: r.Type,
Created: r.CreatedUnix.AsTime(),
})
@@ -202,7 +202,7 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp
ctx.Error(http.StatusForbidden, err.Error(), err)
} else if issues_model.IsErrReactionAlreadyExist(err) {
ctx.JSON(http.StatusOK, api.Reaction{
User: convert.ToUser(ctx.Doer, ctx.Doer),
User: convert.ToUser(ctx, ctx.Doer, ctx.Doer),
Reaction: reaction.Type,
Created: reaction.CreatedUnix.AsTime(),
})
@@ -213,7 +213,7 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp
}
ctx.JSON(http.StatusCreated, api.Reaction{
User: convert.ToUser(ctx.Doer, ctx.Doer),
User: convert.ToUser(ctx, ctx.Doer, ctx.Doer),
Reaction: reaction.Type,
Created: reaction.CreatedUnix.AsTime(),
})
@@ -298,7 +298,7 @@ func GetIssueReactions(ctx *context.APIContext) {
var result []api.Reaction
for _, r := range reactions {
result = append(result, api.Reaction{
User: convert.ToUser(r.User, ctx.Doer),
User: convert.ToUser(ctx, r.User, ctx.Doer),
Reaction: r.Type,
Created: r.CreatedUnix.AsTime(),
})
@@ -412,7 +412,7 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i
ctx.Error(http.StatusForbidden, err.Error(), err)
} else if issues_model.IsErrReactionAlreadyExist(err) {
ctx.JSON(http.StatusOK, api.Reaction{
User: convert.ToUser(ctx.Doer, ctx.Doer),
User: convert.ToUser(ctx, ctx.Doer, ctx.Doer),
Reaction: reaction.Type,
Created: reaction.CreatedUnix.AsTime(),
})
@@ -423,7 +423,7 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i
}
ctx.JSON(http.StatusCreated, api.Reaction{
User: convert.ToUser(ctx.Doer, ctx.Doer),
User: convert.ToUser(ctx, ctx.Doer, ctx.Doer),
Reaction: reaction.Type,
Created: reaction.CreatedUnix.AsTime(),
})
+1 -1
View File
@@ -280,7 +280,7 @@ func GetIssueSubscribers(ctx *context.APIContext) {
}
apiUsers := make([]*api.User, 0, len(users))
for _, v := range users {
apiUsers = append(apiUsers, convert.ToUser(v, ctx.Doer))
apiUsers = append(apiUsers, convert.ToUser(ctx, v, ctx.Doer))
}
count, err := issues_model.CountIssueWatchers(ctx, issue.ID)
+1 -1
View File
@@ -68,7 +68,7 @@ func getNote(ctx *context.APIContext, identifier string) {
return
}
cmt, err := convert.ToCommit(ctx.Repo.Repository, ctx.Repo.GitRepo, note.Commit, nil, true)
cmt, err := convert.ToCommit(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, note.Commit, nil, true)
if err != nil {
ctx.Error(http.StatusInternalServerError, "ToCommit", err)
return
+1 -1
View File
@@ -1311,7 +1311,7 @@ func GetPullRequestCommits(ctx *context.APIContext) {
apiCommits := make([]*api.Commit, 0, end-start)
for i := start; i < end; i++ {
apiCommit, err := convert.ToCommit(ctx.Repo.Repository, baseGitRepo, commits[i], userCache, true)
apiCommit, err := convert.ToCommit(ctx, ctx.Repo.Repository, baseGitRepo, commits[i], userCache, true)
if err != nil {
ctx.ServerError("toCommit", err)
return
+1 -1
View File
@@ -673,7 +673,7 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions
for _, r := range opts.Reviewers {
var reviewer *user_model.User
if strings.Contains(r, "@") {
reviewer, err = user_model.GetUserByEmail(r)
reviewer, err = user_model.GetUserByEmail(ctx, r)
} else {
reviewer, err = user_model.GetUserByName(ctx, r)
}
+5 -5
View File
@@ -64,7 +64,7 @@ func GetRelease(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return
}
ctx.JSON(http.StatusOK, convert.ToRelease(release))
ctx.JSON(http.StatusOK, convert.ToRelease(ctx, release))
}
// GetLatestRelease gets the most recent non-prerelease, non-draft release of a repository, sorted by created_at
@@ -105,7 +105,7 @@ func GetLatestRelease(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return
}
ctx.JSON(http.StatusOK, convert.ToRelease(release))
ctx.JSON(http.StatusOK, convert.ToRelease(ctx, release))
}
// ListReleases list a repository's releases
@@ -174,7 +174,7 @@ func ListReleases(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return
}
rels[i] = convert.ToRelease(release)
rels[i] = convert.ToRelease(ctx, release)
}
filteredCount, err := repo_model.CountReleasesByRepoID(ctx.Repo.Repository.ID, opts)
@@ -272,7 +272,7 @@ func CreateRelease(ctx *context.APIContext) {
return
}
}
ctx.JSON(http.StatusCreated, convert.ToRelease(rel))
ctx.JSON(http.StatusCreated, convert.ToRelease(ctx, rel))
}
// EditRelease edit a release
@@ -357,7 +357,7 @@ func EditRelease(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return
}
ctx.JSON(http.StatusOK, convert.ToRelease(rel))
ctx.JSON(http.StatusOK, convert.ToRelease(ctx, rel))
}
// DeleteRelease delete a release from a repository
+1 -1
View File
@@ -117,7 +117,7 @@ func ListReleaseAttachments(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return
}
ctx.JSON(http.StatusOK, convert.ToRelease(release).Attachments)
ctx.JSON(http.StatusOK, convert.ToRelease(ctx, release).Attachments)
}
// CreateReleaseAttachment creates an attachment and saves the given file
+1 -1
View File
@@ -63,7 +63,7 @@ func GetReleaseByTag(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return
}
ctx.JSON(http.StatusOK, convert.ToRelease(release))
ctx.JSON(http.StatusOK, convert.ToRelease(ctx, release))
}
// DeleteReleaseByTag delete a release from a repository by tag name
+1 -1
View File
@@ -50,7 +50,7 @@ func ListStargazers(ctx *context.APIContext) {
}
users := make([]*api.User, len(stargazers))
for i, stargazer := range stargazers {
users[i] = convert.ToUser(stargazer, ctx.Doer)
users[i] = convert.ToUser(ctx, stargazer, ctx.Doer)
}
ctx.SetTotalCountHeader(int64(ctx.Repo.Repository.NumStars))
+1 -1
View File
@@ -50,7 +50,7 @@ func ListSubscribers(ctx *context.APIContext) {
}
users := make([]*api.User, len(subscribers))
for i, subscriber := range subscribers {
users[i] = convert.ToUser(subscriber, ctx.Doer)
users[i] = convert.ToUser(ctx, subscriber, ctx.Doer)
}
ctx.SetTotalCountHeader(int64(ctx.Repo.Repository.NumWatches))
+1 -1
View File
@@ -107,7 +107,7 @@ func GetAnnotatedTag(ctx *context.APIContext) {
if err != nil {
ctx.Error(http.StatusBadRequest, "GetAnnotatedTag", err)
}
ctx.JSON(http.StatusOK, convert.ToAnnotatedTag(ctx.Repo.Repository, tag, commit))
ctx.JSON(http.StatusOK, convert.ToAnnotatedTag(ctx, ctx.Repo.Repository, tag, commit))
}
}
+2 -2
View File
@@ -47,7 +47,7 @@ func ListTeams(ctx *context.APIContext) {
return
}
apiTeams, err := convert.ToTeams(teams, false)
apiTeams, err := convert.ToTeams(ctx, teams, false)
if err != nil {
ctx.InternalServerError(err)
return
@@ -98,7 +98,7 @@ func IsTeam(ctx *context.APIContext) {
}
if models.HasRepository(team, ctx.Repo.Repository.ID) {
apiTeam, err := convert.ToTeam(team)
apiTeam, err := convert.ToTeam(ctx, team)
if err != nil {
ctx.InternalServerError(err)
return
+1 -1
View File
@@ -81,7 +81,7 @@ func Transfer(ctx *context.APIContext) {
return
}
org := convert.ToOrganization(organization.OrgFromUser(newOwner))
org := convert.ToOrganization(ctx, organization.OrgFromUser(newOwner))
for _, tID := range *opts.TeamIDs {
team, err := organization.GetTeamByID(ctx, tID)
if err != nil {
+1 -1
View File
@@ -17,7 +17,7 @@ import (
func responseAPIUsers(ctx *context.APIContext, users []*user_model.User) {
apiUsers := make([]*api.User, len(users))
for i := range users {
apiUsers[i] = convert.ToUser(users[i], ctx.Doer)
apiUsers[i] = convert.ToUser(ctx, users[i], ctx.Doer)
}
ctx.JSON(http.StatusOK, &apiUsers)
}
+7 -6
View File
@@ -4,6 +4,7 @@
package user
import (
std_ctx "context"
"net/http"
asymkey_model "code.gitea.io/gitea/models/asymkey"
@@ -21,20 +22,20 @@ import (
)
// appendPrivateInformation appends the owner and key type information to api.PublicKey
func appendPrivateInformation(apiKey *api.PublicKey, key *asymkey_model.PublicKey, defaultUser *user_model.User) (*api.PublicKey, error) {
func appendPrivateInformation(ctx std_ctx.Context, apiKey *api.PublicKey, key *asymkey_model.PublicKey, defaultUser *user_model.User) (*api.PublicKey, error) {
if key.Type == asymkey_model.KeyTypeDeploy {
apiKey.KeyType = "deploy"
} else if key.Type == asymkey_model.KeyTypeUser {
apiKey.KeyType = "user"
if defaultUser.ID == key.OwnerID {
apiKey.Owner = convert.ToUser(defaultUser, defaultUser)
apiKey.Owner = convert.ToUser(ctx, defaultUser, defaultUser)
} else {
user, err := user_model.GetUserByID(db.DefaultContext, key.OwnerID)
if err != nil {
return apiKey, err
}
apiKey.Owner = convert.ToUser(user, user)
apiKey.Owner = convert.ToUser(ctx, user, user)
}
} else {
apiKey.KeyType = "unknown"
@@ -87,7 +88,7 @@ func listPublicKeys(ctx *context.APIContext, user *user_model.User) {
for i := range keys {
apiKeys[i] = convert.ToPublicKey(apiLink, keys[i])
if ctx.Doer.IsAdmin || ctx.Doer.ID == keys[i].OwnerID {
apiKeys[i], _ = appendPrivateInformation(apiKeys[i], keys[i], user)
apiKeys[i], _ = appendPrivateInformation(ctx, apiKeys[i], keys[i], user)
}
}
@@ -187,7 +188,7 @@ func GetPublicKey(ctx *context.APIContext) {
apiLink := composePublicKeysAPILink()
apiKey := convert.ToPublicKey(apiLink, key)
if ctx.Doer.IsAdmin || ctx.Doer.ID == key.OwnerID {
apiKey, _ = appendPrivateInformation(apiKey, key, ctx.Doer)
apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Doer)
}
ctx.JSON(http.StatusOK, apiKey)
}
@@ -208,7 +209,7 @@ func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid
apiLink := composePublicKeysAPILink()
apiKey := convert.ToPublicKey(apiLink, key)
if ctx.Doer.IsAdmin || ctx.Doer.ID == key.OwnerID {
apiKey, _ = appendPrivateInformation(apiKey, key, ctx.Doer)
apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Doer)
}
ctx.JSON(http.StatusCreated, apiKey)
}
+3 -3
View File
@@ -74,7 +74,7 @@ func Search(ctx *context.APIContext) {
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true,
"data": convert.ToUsers(ctx.Doer, users),
"data": convert.ToUsers(ctx, ctx.Doer, users),
})
}
@@ -102,7 +102,7 @@ func GetInfo(ctx *context.APIContext) {
ctx.NotFound("GetUserByName", user_model.ErrUserNotExist{Name: ctx.Params(":username")})
return
}
ctx.JSON(http.StatusOK, convert.ToUser(ctx.ContextUser, ctx.Doer))
ctx.JSON(http.StatusOK, convert.ToUser(ctx, ctx.ContextUser, ctx.Doer))
}
// GetAuthenticatedUser get current user's information
@@ -116,7 +116,7 @@ func GetAuthenticatedUser(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/User"
ctx.JSON(http.StatusOK, convert.ToUser(ctx.Doer, ctx.Doer))
ctx.JSON(http.StatusOK, convert.ToUser(ctx, ctx.Doer, ctx.Doer))
}
// GetUserHeatmapData is the handler to get a users heatmap
+2 -1
View File
@@ -8,6 +8,7 @@ import (
"net/http"
"strings"
"code.gitea.io/gitea/modules/cache"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/process"
@@ -28,7 +29,7 @@ func Middlewares() []func(http.Handler) http.Handler {
ctx, _, finished := process.GetManager().AddTypedContext(req.Context(), fmt.Sprintf("%s: %s", req.Method, req.RequestURI), process.RequestProcessType, true)
defer finished()
next.ServeHTTP(context.NewResponse(resp), req.WithContext(ctx))
next.ServeHTTP(context.NewResponse(resp), req.WithContext(cache.WithCacheContext(ctx)))
})
},
}
+2 -2
View File
@@ -441,11 +441,11 @@ func SubmitInstall(ctx *context.Context) {
cfg.Section("server").Key("OFFLINE_MODE").SetValue(fmt.Sprint(form.OfflineMode))
// if you are reinstalling, this maybe not right because of missing version
if err := system_model.SetSettingNoVersion(system_model.KeyPictureDisableGravatar, strconv.FormatBool(form.DisableGravatar)); err != nil {
if err := system_model.SetSettingNoVersion(ctx, system_model.KeyPictureDisableGravatar, strconv.FormatBool(form.DisableGravatar)); err != nil {
ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
return
}
if err := system_model.SetSettingNoVersion(system_model.KeyPictureEnableFederatedAvatar, strconv.FormatBool(form.EnableFederatedAvatar)); err != nil {
if err := system_model.SetSettingNoVersion(ctx, system_model.KeyPictureEnableFederatedAvatar, strconv.FormatBool(form.EnableFederatedAvatar)); err != nil {
ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
return
}
+1 -1
View File
@@ -101,7 +101,7 @@ func readAndVerifyCommit(sha string, repo *git.Repository, env []string) error {
if err != nil {
return err
}
verification := asymkey_model.ParseCommitWithSignature(commit)
verification := asymkey_model.ParseCommitWithSignature(ctx, commit)
if !verification.Verified {
cancel()
return &errUnverifiedCommit{
+1 -1
View File
@@ -213,7 +213,7 @@ func ChangeConfig(ctx *context.Context) {
}
}
if err := system_model.SetSetting(&system_model.Setting{
if err := system_model.SetSetting(ctx, &system_model.Setting{
SettingKey: key,
SettingValue: value,
Version: version,
+1 -1
View File
@@ -59,7 +59,7 @@ func LinkAccount(ctx *context.Context) {
ctx.Data["email"] = email
if len(email) != 0 {
u, err := user_model.GetUserByEmail(email)
u, err := user_model.GetUserByEmail(ctx, email)
if err != nil && !user_model.IsErrUserNotExist(err) {
ctx.ServerError("UserSignIn", err)
return
+2 -2
View File
@@ -225,7 +225,7 @@ func newAccessTokenResponse(ctx stdContext.Context, grant *auth.OAuth2Grant, ser
idToken.Name = user.GetDisplayName()
idToken.PreferredUsername = user.Name
idToken.Profile = user.HTMLURL()
idToken.Picture = user.AvatarLink()
idToken.Picture = user.AvatarLink(ctx)
idToken.Website = user.Website
idToken.Locale = user.Language
idToken.UpdatedAt = user.UpdatedUnix
@@ -286,7 +286,7 @@ func InfoOAuth(ctx *context.Context) {
Name: ctx.Doer.FullName,
Username: ctx.Doer.Name,
Email: ctx.Doer.Email,
Picture: ctx.Doer.AvatarLink(),
Picture: ctx.Doer.AvatarLink(ctx),
}
groups, err := getOAuthGroupsForUser(ctx.Doer)
+2 -2
View File
@@ -69,7 +69,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) {
assert.Equal(t, user.Name, oidcToken.Name)
assert.Equal(t, user.Name, oidcToken.PreferredUsername)
assert.Equal(t, user.HTMLURL(), oidcToken.Profile)
assert.Equal(t, user.AvatarLink(), oidcToken.Picture)
assert.Equal(t, user.AvatarLink(db.DefaultContext), oidcToken.Picture)
assert.Equal(t, user.Website, oidcToken.Website)
assert.Equal(t, user.UpdatedUnix, oidcToken.UpdatedAt)
assert.Equal(t, user.Email, oidcToken.Email)
@@ -87,7 +87,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) {
assert.Equal(t, user.FullName, oidcToken.Name)
assert.Equal(t, user.Name, oidcToken.PreferredUsername)
assert.Equal(t, user.HTMLURL(), oidcToken.Profile)
assert.Equal(t, user.AvatarLink(), oidcToken.Picture)
assert.Equal(t, user.AvatarLink(db.DefaultContext), oidcToken.Picture)
assert.Equal(t, user.Website, oidcToken.Website)
assert.Equal(t, user.UpdatedUnix, oidcToken.UpdatedAt)
assert.Equal(t, user.Email, oidcToken.Email)
+1 -1
View File
@@ -197,7 +197,7 @@ func signInOpenIDVerify(ctx *context.Context) {
log.Trace("User has email=%s and nickname=%s", email, nickname)
if email != "" {
u, err = user_model.GetUserByEmail(email)
u, err = user_model.GetUserByEmail(ctx, email)
if err != nil {
if !user_model.IsErrUserNotExist(err) {
ctx.RenderWithErr(err.Error(), tplSignInOpenID, &forms.SignInOpenIDForm{
+1 -1
View File
@@ -59,7 +59,7 @@ func ForgotPasswdPost(ctx *context.Context) {
email := ctx.FormString("email")
ctx.Data["Email"] = email
u, err := user_model.GetUserByEmail(email)
u, err := user_model.GetUserByEmail(ctx, email)
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale)
+1 -1
View File
@@ -401,7 +401,7 @@ func SearchTeam(ctx *context.Context) {
return
}
apiTeams, err := convert.ToTeams(teams, false)
apiTeams, err := convert.ToTeams(ctx, teams, false)
if err != nil {
log.Error("convert ToTeams failed: %v", err)
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
+3 -3
View File
@@ -199,7 +199,7 @@ func processBlameParts(ctx *context.Context, blameParts []git.BlamePart) (map[st
}
// populate commit email addresses to later look up avatars.
for _, c := range user_model.ValidateCommitsWithEmails(commits) {
for _, c := range user_model.ValidateCommitsWithEmails(ctx, commits) {
commitNames[c.ID.String()] = c
}
@@ -262,9 +262,9 @@ func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames m
var avatar string
if commit.User != nil {
avatar = string(templates.Avatar(commit.User, 18, "gt-mr-3"))
avatar = string(templates.Avatar(ctx, commit.User, 18, "gt-mr-3"))
} else {
avatar = string(templates.AvatarByEmail(commit.Author.Email, commit.Author.Name, 18, "gt-mr-3"))
avatar = string(templates.AvatarByEmail(ctx, commit.Author.Email, commit.Author.Name, 18, "gt-mr-3"))
}
br.Avatar = gotemplate.HTML(avatar)
+4 -4
View File
@@ -138,7 +138,7 @@ func Graph(ctx *context.Context) {
return
}
if err := graph.LoadAndProcessCommits(ctx.Repo.Repository, ctx.Repo.GitRepo); err != nil {
if err := graph.LoadAndProcessCommits(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo); err != nil {
ctx.ServerError("LoadAndProcessCommits", err)
return
}
@@ -343,9 +343,9 @@ func Diff(ctx *context.Context) {
ctx.Data["CommitStatus"] = git_model.CalcCommitStatus(statuses)
ctx.Data["CommitStatuses"] = statuses
verification := asymkey_model.ParseCommitWithSignature(commit)
verification := asymkey_model.ParseCommitWithSignature(ctx, commit)
ctx.Data["Verification"] = verification
ctx.Data["Author"] = user_model.ValidateCommitWithEmail(commit)
ctx.Data["Author"] = user_model.ValidateCommitWithEmail(ctx, commit)
ctx.Data["Parents"] = parents
ctx.Data["DiffNotAvailable"] = diff.NumFiles == 0
@@ -361,7 +361,7 @@ func Diff(ctx *context.Context) {
if err == nil {
ctx.Data["Note"] = string(charset.ToUTF8WithFallback(note.Message))
ctx.Data["NoteCommit"] = note.Commit
ctx.Data["NoteAuthor"] = user_model.ValidateCommitWithEmail(note.Commit)
ctx.Data["NoteAuthor"] = user_model.ValidateCommitWithEmail(ctx, note.Commit)
}
ctx.Data["BranchName"], err = commit.GetBranchName()
+9 -5
View File
@@ -1142,7 +1142,11 @@ func NewIssuePost(ctx *context.Context) {
}
// roleDescriptor returns the Role Descriptor for a comment in/with the given repo, poster and issue
func roleDescriptor(ctx stdCtx.Context, repo *repo_model.Repository, poster *user_model.User, issue *issues_model.Issue) (issues_model.RoleDescriptor, error) {
func roleDescriptor(ctx stdCtx.Context, repo *repo_model.Repository, poster *user_model.User, issue *issues_model.Issue, hasOriginalAuthor bool) (issues_model.RoleDescriptor, error) {
if hasOriginalAuthor {
return issues_model.RoleDescriptorNone, nil
}
perm, err := access_model.GetUserRepoPermission(ctx, repo, poster)
if err != nil {
return issues_model.RoleDescriptorNone, err
@@ -1444,7 +1448,7 @@ func ViewIssue(ctx *context.Context) {
// check if dependencies can be created across repositories
ctx.Data["AllowCrossRepositoryDependencies"] = setting.Service.AllowCrossRepositoryDependencies
if issue.ShowRole, err = roleDescriptor(ctx, repo, issue.Poster, issue); err != nil {
if issue.ShowRole, err = roleDescriptor(ctx, repo, issue.Poster, issue, issue.HasOriginalAuthor()); err != nil {
ctx.ServerError("roleDescriptor", err)
return
}
@@ -1483,7 +1487,7 @@ func ViewIssue(ctx *context.Context) {
continue
}
comment.ShowRole, err = roleDescriptor(ctx, repo, comment.Poster, issue)
comment.ShowRole, err = roleDescriptor(ctx, repo, comment.Poster, issue, comment.HasOriginalAuthor())
if err != nil {
ctx.ServerError("roleDescriptor", err)
return
@@ -1582,7 +1586,7 @@ func ViewIssue(ctx *context.Context) {
continue
}
c.ShowRole, err = roleDescriptor(ctx, repo, c.Poster, issue)
c.ShowRole, err = roleDescriptor(ctx, repo, c.Poster, issue, c.HasOriginalAuthor())
if err != nil {
ctx.ServerError("roleDescriptor", err)
return
@@ -3272,5 +3276,5 @@ func handleTeamMentions(ctx *context.Context) {
ctx.Data["MentionableTeams"] = teams
ctx.Data["MentionableTeamsOrg"] = ctx.Repo.Owner.Name
ctx.Data["MentionableTeamsOrgAvatar"] = ctx.Repo.Owner.AvatarLink()
ctx.Data["MentionableTeamsOrgAvatar"] = ctx.Repo.Owner.AvatarLink(ctx)
}
+2 -2
View File
@@ -811,7 +811,7 @@ func renderDirectoryFiles(ctx *context.Context, timeout time.Duration) git.Entri
ctx.Data["LatestCommit"] = latestCommit
if latestCommit != nil {
verification := asymkey_model.ParseCommitWithSignature(latestCommit)
verification := asymkey_model.ParseCommitWithSignature(ctx, latestCommit)
if err := asymkey_model.CalculateTrustStatus(verification, ctx.Repo.Repository.GetTrustModel(), func(user *user_model.User) (bool, error) {
return repo_model.IsOwnerMemberCollaborator(ctx.Repo.Repository, user.ID)
@@ -820,7 +820,7 @@ func renderDirectoryFiles(ctx *context.Context, timeout time.Duration) git.Entri
return nil
}
ctx.Data["LatestCommitVerification"] = verification
ctx.Data["LatestCommitUser"] = user_model.ValidateCommitWithEmail(latestCommit)
ctx.Data["LatestCommitUser"] = user_model.ValidateCommitWithEmail(ctx, latestCommit)
statuses, _, err := git_model.GetLatestCommitStatus(ctx, ctx.Repo.Repository.ID, latestCommit.ID.String(), db.ListOptions{})
if err != nil {
+1 -1
View File
@@ -660,7 +660,7 @@ func TestWebhook(ctx *context.Context) {
}
}
apiUser := convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone)
apiUser := convert.ToUserWithAccessMode(ctx, ctx.Doer, perm.AccessModeNone)
apiCommit := &api.PayloadCommit{
ID: commit.ID.String(),
+2 -2
View File
@@ -41,7 +41,7 @@ func AvatarByUserName(ctx *context.Context) {
user = user_model.NewGhostUser()
}
cacheableRedirect(ctx, user.AvatarLinkWithSize(size))
cacheableRedirect(ctx, user.AvatarLinkWithSize(ctx, size))
}
// AvatarByEmailHash redirects the browser to the email avatar link
@@ -53,5 +53,5 @@ func AvatarByEmailHash(ctx *context.Context) {
return
}
size := ctx.FormInt("size")
cacheableRedirect(ctx, avatars.GenerateEmailAvatarFinalLink(email, size))
cacheableRedirect(ctx, avatars.GenerateEmailAvatarFinalLink(ctx, email, size))
}
+1 -1
View File
@@ -38,6 +38,6 @@ func Search(ctx *context.Context) {
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true,
"data": convert.ToUsers(ctx.Doer, users),
"data": convert.ToUsers(ctx, ctx.Doer, users),
})
}
+2 -2
View File
@@ -60,7 +60,7 @@ func WebfingerQuery(ctx *context.Context) {
u, err = user_model.GetUserByName(ctx, parts[0])
case "mailto":
u, err = user_model.GetUserByEmailContext(ctx, resource.Opaque)
u, err = user_model.GetUserByEmail(ctx, resource.Opaque)
if u != nil && u.KeepEmailPrivate {
err = user_model.ErrUserNotExist{}
}
@@ -99,7 +99,7 @@ func WebfingerQuery(ctx *context.Context) {
},
{
Rel: "http://webfinger.net/rel/avatar",
Href: u.AvatarLink(),
Href: u.AvatarLink(ctx),
},
{
Rel: "self",
+23 -23
View File
@@ -52,7 +52,7 @@ func (n *actionsNotifier) NotifyNewIssue(ctx context.Context, issue *issues_mode
Index: issue.Index,
Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(issue.Poster, nil),
Sender: convert.ToUser(ctx, issue.Poster, nil),
}).Notify(withMethod(ctx, "NotifyNewIssue"))
}
@@ -70,7 +70,7 @@ func (n *actionsNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *use
Index: issue.Index,
PullRequest: convert.ToAPIPullRequest(db.DefaultContext, issue.PullRequest, nil),
Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil),
Sender: convert.ToUser(ctx, doer, nil),
CommitID: commitID,
}
if isClosed {
@@ -88,7 +88,7 @@ func (n *actionsNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *use
Index: issue.Index,
Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil),
Sender: convert.ToUser(ctx, doer, nil),
}
if isClosed {
apiIssue.Action = api.HookIssueClosed
@@ -134,7 +134,7 @@ func (n *actionsNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *use
Index: issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil),
Repository: convert.ToRepo(ctx, issue.Repo, perm_model.AccessModeNone),
Sender: convert.ToUser(doer, nil),
Sender: convert.ToUser(ctx, doer, nil),
}).
Notify(ctx)
return
@@ -146,7 +146,7 @@ func (n *actionsNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *use
Index: issue.Index,
Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil),
Sender: convert.ToUser(ctx, doer, nil),
}).
Notify(ctx)
}
@@ -165,9 +165,9 @@ func (n *actionsNotifier) NotifyCreateIssueComment(ctx context.Context, doer *us
WithPayload(&api.IssueCommentPayload{
Action: api.HookIssueCommentCreated,
Issue: convert.ToAPIIssue(ctx, issue),
Comment: convert.ToComment(comment),
Comment: convert.ToComment(ctx, comment),
Repository: convert.ToRepo(ctx, repo, mode),
Sender: convert.ToUser(doer, nil),
Sender: convert.ToUser(ctx, doer, nil),
IsPull: true,
}).
Notify(ctx)
@@ -178,9 +178,9 @@ func (n *actionsNotifier) NotifyCreateIssueComment(ctx context.Context, doer *us
WithPayload(&api.IssueCommentPayload{
Action: api.HookIssueCommentCreated,
Issue: convert.ToAPIIssue(ctx, issue),
Comment: convert.ToComment(comment),
Comment: convert.ToComment(ctx, comment),
Repository: convert.ToRepo(ctx, repo, mode),
Sender: convert.ToUser(doer, nil),
Sender: convert.ToUser(ctx, doer, nil),
IsPull: false,
}).
Notify(ctx)
@@ -210,7 +210,7 @@ func (n *actionsNotifier) NotifyNewPullRequest(ctx context.Context, pull *issues
Index: pull.Issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, pull, nil),
Repository: convert.ToRepo(ctx, pull.Issue.Repo, mode),
Sender: convert.ToUser(pull.Issue.Poster, nil),
Sender: convert.ToUser(ctx, pull.Issue.Poster, nil),
}).
WithPullRequest(pull).
Notify(ctx)
@@ -222,8 +222,8 @@ func (n *actionsNotifier) NotifyCreateRepository(ctx context.Context, doer, u *u
newNotifyInput(repo, doer, webhook_module.HookEventRepository).WithPayload(&api.RepositoryPayload{
Action: api.HookRepoCreated,
Repository: convert.ToRepo(ctx, repo, perm_model.AccessModeOwner),
Organization: convert.ToUser(u, nil),
Sender: convert.ToUser(doer, nil),
Organization: convert.ToUser(ctx, u, nil),
Sender: convert.ToUser(ctx, doer, nil),
}).Notify(ctx)
}
@@ -237,7 +237,7 @@ func (n *actionsNotifier) NotifyForkRepository(ctx context.Context, doer *user_m
newNotifyInput(oldRepo, doer, webhook_module.HookEventFork).WithPayload(&api.ForkPayload{
Forkee: convert.ToRepo(ctx, oldRepo, oldMode),
Repo: convert.ToRepo(ctx, repo, mode),
Sender: convert.ToUser(doer, nil),
Sender: convert.ToUser(ctx, doer, nil),
}).Notify(ctx)
u := repo.MustOwner(ctx)
@@ -249,8 +249,8 @@ func (n *actionsNotifier) NotifyForkRepository(ctx context.Context, doer *user_m
WithPayload(&api.RepositoryPayload{
Action: api.HookRepoCreated,
Repository: convert.ToRepo(ctx, repo, perm_model.AccessModeOwner),
Organization: convert.ToUser(u, nil),
Sender: convert.ToUser(doer, nil),
Organization: convert.ToUser(ctx, u, nil),
Sender: convert.ToUser(ctx, doer, nil),
}).Notify(ctx)
}
}
@@ -291,7 +291,7 @@ func (n *actionsNotifier) NotifyPullRequestReview(ctx context.Context, pr *issue
Index: review.Issue.Index,
PullRequest: convert.ToAPIPullRequest(db.DefaultContext, pr, nil),
Repository: convert.ToRepo(ctx, review.Issue.Repo, mode),
Sender: convert.ToUser(review.Reviewer, nil),
Sender: convert.ToUser(ctx, review.Reviewer, nil),
Review: &api.ReviewPayload{
Type: string(reviewHookType),
Content: review.Content,
@@ -329,7 +329,7 @@ func (*actionsNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_m
Index: pr.Issue.Index,
PullRequest: convert.ToAPIPullRequest(db.DefaultContext, pr, nil),
Repository: convert.ToRepo(ctx, pr.Issue.Repo, mode),
Sender: convert.ToUser(doer, nil),
Sender: convert.ToUser(ctx, doer, nil),
Action: api.HookIssueClosed,
}
@@ -343,7 +343,7 @@ func (*actionsNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_m
func (n *actionsNotifier) NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
ctx = withMethod(ctx, "NotifyPushCommits")
apiPusher := convert.ToUser(pusher, nil)
apiPusher := convert.ToUser(ctx, pusher, nil)
apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(ctx, repo.RepoPath(), repo.HTMLURL())
if err != nil {
log.Error("commits.ToAPIPayloadCommits failed: %v", err)
@@ -369,7 +369,7 @@ func (n *actionsNotifier) NotifyPushCommits(ctx context.Context, pusher *user_mo
func (n *actionsNotifier) NotifyCreateRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) {
ctx = withMethod(ctx, "NotifyCreateRef")
apiPusher := convert.ToUser(pusher, nil)
apiPusher := convert.ToUser(ctx, pusher, nil)
apiRepo := convert.ToRepo(ctx, repo, perm_model.AccessModeNone)
refName := git.RefEndName(refFullName)
@@ -388,7 +388,7 @@ func (n *actionsNotifier) NotifyCreateRef(ctx context.Context, pusher *user_mode
func (n *actionsNotifier) NotifyDeleteRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) {
ctx = withMethod(ctx, "NotifyDeleteRef")
apiPusher := convert.ToUser(pusher, nil)
apiPusher := convert.ToUser(ctx, pusher, nil)
apiRepo := convert.ToRepo(ctx, repo, perm_model.AccessModeNone)
refName := git.RefEndName(refFullName)
@@ -407,7 +407,7 @@ func (n *actionsNotifier) NotifyDeleteRef(ctx context.Context, pusher *user_mode
func (n *actionsNotifier) NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
ctx = withMethod(ctx, "NotifySyncPushCommits")
apiPusher := convert.ToUser(pusher, nil)
apiPusher := convert.ToUser(ctx, pusher, nil)
apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(db.DefaultContext, repo.RepoPath(), repo.HTMLURL())
if err != nil {
log.Error("commits.ToAPIPayloadCommits failed: %v", err)
@@ -490,7 +490,7 @@ func (n *actionsNotifier) NotifyPullRequestSynchronized(ctx context.Context, doe
Index: pr.Issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, pr, nil),
Repository: convert.ToRepo(ctx, pr.Issue.Repo, perm_model.AccessModeNone),
Sender: convert.ToUser(doer, nil),
Sender: convert.ToUser(ctx, doer, nil),
}).
WithPullRequest(pr).
Notify(ctx)
@@ -521,7 +521,7 @@ func (n *actionsNotifier) NotifyPullRequestChangeTargetBranch(ctx context.Contex
},
PullRequest: convert.ToAPIPullRequest(ctx, pr, nil),
Repository: convert.ToRepo(ctx, pr.Issue.Repo, mode),
Sender: convert.ToUser(doer, nil),
Sender: convert.ToUser(ctx, doer, nil),
}).
WithPullRequest(pr).
Notify(ctx)
+3 -3
View File
@@ -205,9 +205,9 @@ func notifyRelease(ctx context.Context, doer *user_model.User, rel *repo_model.R
WithRef(ref).
WithPayload(&api.ReleasePayload{
Action: action,
Release: convert.ToRelease(rel),
Release: convert.ToRelease(ctx, rel),
Repository: convert.ToRepo(ctx, rel.Repo, mode),
Sender: convert.ToUser(doer, nil),
Sender: convert.ToUser(ctx, doer, nil),
}).
Notify(ctx)
}
@@ -230,7 +230,7 @@ func notifyPackage(ctx context.Context, sender *user_model.User, pd *packages_mo
WithPayload(&api.PackagePayload{
Action: action,
Package: apiPackage,
Sender: convert.ToUser(sender, nil),
Sender: convert.ToUser(ctx, sender, nil),
}).
Notify(ctx)
}
+6 -6
View File
@@ -207,7 +207,7 @@ Loop:
if commit.Signature == nil {
return false, "", nil, &ErrWontSign{parentSigned}
}
verification := asymkey_model.ParseCommitWithSignature(commit)
verification := asymkey_model.ParseCommitWithSignature(ctx, commit)
if !verification.Verified {
return false, "", nil, &ErrWontSign{parentSigned}
}
@@ -260,7 +260,7 @@ Loop:
if commit.Signature == nil {
return false, "", nil, &ErrWontSign{parentSigned}
}
verification := asymkey_model.ParseCommitWithSignature(commit)
verification := asymkey_model.ParseCommitWithSignature(ctx, commit)
if !verification.Verified {
return false, "", nil, &ErrWontSign{parentSigned}
}
@@ -332,7 +332,7 @@ Loop:
if err != nil {
return false, "", nil, err
}
verification := asymkey_model.ParseCommitWithSignature(commit)
verification := asymkey_model.ParseCommitWithSignature(ctx, commit)
if !verification.Verified {
return false, "", nil, &ErrWontSign{baseSigned}
}
@@ -348,7 +348,7 @@ Loop:
if err != nil {
return false, "", nil, err
}
verification := asymkey_model.ParseCommitWithSignature(commit)
verification := asymkey_model.ParseCommitWithSignature(ctx, commit)
if !verification.Verified {
return false, "", nil, &ErrWontSign{headSigned}
}
@@ -364,7 +364,7 @@ Loop:
if err != nil {
return false, "", nil, err
}
verification := asymkey_model.ParseCommitWithSignature(commit)
verification := asymkey_model.ParseCommitWithSignature(ctx, commit)
if !verification.Verified {
return false, "", nil, &ErrWontSign{commitsSigned}
}
@@ -378,7 +378,7 @@ Loop:
return false, "", nil, err
}
for _, commit := range commitList {
verification := asymkey_model.ParseCommitWithSignature(commit)
verification := asymkey_model.ParseCommitWithSignature(ctx, commit)
if !verification.Verified {
return false, "", nil, &ErrWontSign{commitsSigned}
}
+1 -1
View File
@@ -91,7 +91,7 @@ func (r *ReverseProxy) getUserFromAuthEmail(req *http.Request) *user_model.User
}
log.Trace("ReverseProxy Authorization: Found email: %s", email)
user, err := user_model.GetUserByEmail(email)
user, err := user_model.GetUserByEmail(req.Context(), email)
if err != nil {
// Do not allow auto-registration, we don't have a username here
if !user_model.IsErrUserNotExist(err) {
+13 -13
View File
@@ -39,7 +39,7 @@ func ToEmail(email *user_model.EmailAddress) *api.Email {
}
// ToBranch convert a git.Commit and git.Branch to an api.Branch
func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git_model.ProtectedBranch, user *user_model.User, isRepoAdmin bool) (*api.Branch, error) {
func ToBranch(ctx context.Context, repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git_model.ProtectedBranch, user *user_model.User, isRepoAdmin bool) (*api.Branch, error) {
if bp == nil {
var hasPerm bool
var canPush bool
@@ -59,7 +59,7 @@ func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git
return &api.Branch{
Name: b.Name,
Commit: ToPayloadCommit(repo, c),
Commit: ToPayloadCommit(ctx, repo, c),
Protected: false,
RequiredApprovals: 0,
EnableStatusCheck: false,
@@ -71,7 +71,7 @@ func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git
branch := &api.Branch{
Name: b.Name,
Commit: ToPayloadCommit(repo, c),
Commit: ToPayloadCommit(ctx, repo, c),
Protected: true,
RequiredApprovals: bp.RequiredApprovals,
EnableStatusCheck: bp.EnableStatusCheck,
@@ -169,8 +169,8 @@ func ToTag(repo *repo_model.Repository, t *git.Tag) *api.Tag {
}
// ToVerification convert a git.Commit.Signature to an api.PayloadCommitVerification
func ToVerification(c *git.Commit) *api.PayloadCommitVerification {
verif := asymkey_model.ParseCommitWithSignature(c)
func ToVerification(ctx context.Context, c *git.Commit) *api.PayloadCommitVerification {
verif := asymkey_model.ParseCommitWithSignature(ctx, c)
commitVerification := &api.PayloadCommitVerification{
Verified: verif.Verified,
Reason: verif.Reason,
@@ -271,10 +271,10 @@ func ToDeployKey(apiLink string, key *asymkey_model.DeployKey) *api.DeployKey {
}
// ToOrganization convert user_model.User to api.Organization
func ToOrganization(org *organization.Organization) *api.Organization {
func ToOrganization(ctx context.Context, org *organization.Organization) *api.Organization {
return &api.Organization{
ID: org.ID,
AvatarURL: org.AsUser().AvatarLink(),
AvatarURL: org.AsUser().AvatarLink(ctx),
Name: org.Name,
UserName: org.Name,
FullName: org.FullName,
@@ -287,8 +287,8 @@ func ToOrganization(org *organization.Organization) *api.Organization {
}
// ToTeam convert models.Team to api.Team
func ToTeam(team *organization.Team, loadOrg ...bool) (*api.Team, error) {
teams, err := ToTeams([]*organization.Team{team}, len(loadOrg) != 0 && loadOrg[0])
func ToTeam(ctx context.Context, team *organization.Team, loadOrg ...bool) (*api.Team, error) {
teams, err := ToTeams(ctx, []*organization.Team{team}, len(loadOrg) != 0 && loadOrg[0])
if err != nil || len(teams) == 0 {
return nil, err
}
@@ -296,7 +296,7 @@ func ToTeam(team *organization.Team, loadOrg ...bool) (*api.Team, error) {
}
// ToTeams convert models.Team list to api.Team list
func ToTeams(teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) {
func ToTeams(ctx context.Context, teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) {
if len(teams) == 0 || teams[0] == nil {
return nil, nil
}
@@ -326,7 +326,7 @@ func ToTeams(teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) {
if err != nil {
return nil, err
}
apiOrg = ToOrganization(org)
apiOrg = ToOrganization(ctx, org)
cache[teams[i].OrgID] = apiOrg
}
apiTeams[i].Organization = apiOrg
@@ -336,7 +336,7 @@ func ToTeams(teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) {
}
// ToAnnotatedTag convert git.Tag to api.AnnotatedTag
func ToAnnotatedTag(repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag {
func ToAnnotatedTag(ctx context.Context, repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag {
return &api.AnnotatedTag{
Tag: t.Name,
SHA: t.ID.String(),
@@ -344,7 +344,7 @@ func ToAnnotatedTag(repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api
Message: t.Message,
URL: util.URLJoin(repo.APIURL(), "git/tags", t.ID.String()),
Tagger: ToCommitUser(t.Tagger),
Verification: ToVerification(c),
Verification: ToVerification(ctx, c),
}
}
+13 -12
View File
@@ -4,6 +4,7 @@
package convert
import (
"context"
"net/url"
"time"
@@ -37,16 +38,16 @@ func ToCommitMeta(repo *repo_model.Repository, tag *git.Tag) *api.CommitMeta {
}
// ToPayloadCommit convert a git.Commit to api.PayloadCommit
func ToPayloadCommit(repo *repo_model.Repository, c *git.Commit) *api.PayloadCommit {
func ToPayloadCommit(ctx context.Context, repo *repo_model.Repository, c *git.Commit) *api.PayloadCommit {
authorUsername := ""
if author, err := user_model.GetUserByEmail(c.Author.Email); err == nil {
if author, err := user_model.GetUserByEmail(ctx, c.Author.Email); err == nil {
authorUsername = author.Name
} else if !user_model.IsErrUserNotExist(err) {
log.Error("GetUserByEmail: %v", err)
}
committerUsername := ""
if committer, err := user_model.GetUserByEmail(c.Committer.Email); err == nil {
if committer, err := user_model.GetUserByEmail(ctx, c.Committer.Email); err == nil {
committerUsername = committer.Name
} else if !user_model.IsErrUserNotExist(err) {
log.Error("GetUserByEmail: %v", err)
@@ -67,12 +68,12 @@ func ToPayloadCommit(repo *repo_model.Repository, c *git.Commit) *api.PayloadCom
UserName: committerUsername,
},
Timestamp: c.Author.When,
Verification: ToVerification(c),
Verification: ToVerification(ctx, c),
}
}
// ToCommit convert a git.Commit to api.Commit
func ToCommit(repo *repo_model.Repository, gitRepo *git.Repository, commit *git.Commit, userCache map[string]*user_model.User, stat bool) (*api.Commit, error) {
func ToCommit(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, commit *git.Commit, userCache map[string]*user_model.User, stat bool) (*api.Commit, error) {
var apiAuthor, apiCommitter *api.User
// Retrieve author and committer information
@@ -87,13 +88,13 @@ func ToCommit(repo *repo_model.Repository, gitRepo *git.Repository, commit *git.
}
if ok {
apiAuthor = ToUser(cacheAuthor, nil)
apiAuthor = ToUser(ctx, cacheAuthor, nil)
} else {
author, err := user_model.GetUserByEmail(commit.Author.Email)
author, err := user_model.GetUserByEmail(ctx, commit.Author.Email)
if err != nil && !user_model.IsErrUserNotExist(err) {
return nil, err
} else if err == nil {
apiAuthor = ToUser(author, nil)
apiAuthor = ToUser(ctx, author, nil)
if userCache != nil {
userCache[commit.Author.Email] = author
}
@@ -109,13 +110,13 @@ func ToCommit(repo *repo_model.Repository, gitRepo *git.Repository, commit *git.
}
if ok {
apiCommitter = ToUser(cacheCommitter, nil)
apiCommitter = ToUser(ctx, cacheCommitter, nil)
} else {
committer, err := user_model.GetUserByEmail(commit.Committer.Email)
committer, err := user_model.GetUserByEmail(ctx, commit.Committer.Email)
if err != nil && !user_model.IsErrUserNotExist(err) {
return nil, err
} else if err == nil {
apiCommitter = ToUser(committer, nil)
apiCommitter = ToUser(ctx, committer, nil)
if userCache != nil {
userCache[commit.Committer.Email] = committer
}
@@ -161,7 +162,7 @@ func ToCommit(repo *repo_model.Repository, gitRepo *git.Repository, commit *git.
SHA: commit.ID.String(),
Created: commit.Committer.When,
},
Verification: ToVerification(commit),
Verification: ToVerification(ctx, commit),
},
Author: apiAuthor,
Committer: apiCommitter,
+3 -3
View File
@@ -41,7 +41,7 @@ func ToAPIIssue(ctx context.Context, issue *issues_model.Issue) *api.Issue {
URL: issue.APIURL(),
HTMLURL: issue.HTMLURL(),
Index: issue.Index,
Poster: ToUser(issue.Poster, nil),
Poster: ToUser(ctx, issue.Poster, nil),
Title: issue.Title,
Body: issue.Content,
Attachments: ToAttachments(issue.Attachments),
@@ -77,9 +77,9 @@ func ToAPIIssue(ctx context.Context, issue *issues_model.Issue) *api.Issue {
}
if len(issue.Assignees) > 0 {
for _, assignee := range issue.Assignees {
apiIssue.Assignees = append(apiIssue.Assignees, ToUser(assignee, nil))
apiIssue.Assignees = append(apiIssue.Assignees, ToUser(ctx, assignee, nil))
}
apiIssue.Assignee = ToUser(issue.Assignees[0], nil) // For compatibility, we're keeping the first assignee as `apiIssue.Assignee`
apiIssue.Assignee = ToUser(ctx, issue.Assignees[0], nil) // For compatibility, we're keeping the first assignee as `apiIssue.Assignee`
}
if issue.IsPull {
if err := issue.LoadPullRequest(ctx); err != nil {
+7 -7
View File
@@ -14,10 +14,10 @@ import (
)
// ToComment converts a issues_model.Comment to the api.Comment format
func ToComment(c *issues_model.Comment) *api.Comment {
func ToComment(ctx context.Context, c *issues_model.Comment) *api.Comment {
return &api.Comment{
ID: c.ID,
Poster: ToUser(c.Poster, nil),
Poster: ToUser(ctx, c.Poster, nil),
HTMLURL: c.HTMLURL(),
IssueURL: c.IssueURL(),
PRURL: c.PRURL(),
@@ -69,7 +69,7 @@ func ToTimelineComment(ctx context.Context, c *issues_model.Comment, doer *user_
comment := &api.TimelineComment{
ID: c.ID,
Type: c.Type.String(),
Poster: ToUser(c.Poster, nil),
Poster: ToUser(ctx, c.Poster, nil),
HTMLURL: c.HTMLURL(),
IssueURL: c.IssueURL(),
PRURL: c.PRURL(),
@@ -131,7 +131,7 @@ func ToTimelineComment(ctx context.Context, c *issues_model.Comment, doer *user_
log.Error("LoadPoster: %v", err)
return nil
}
comment.RefComment = ToComment(com)
comment.RefComment = ToComment(ctx, com)
}
if c.Label != nil {
@@ -157,14 +157,14 @@ func ToTimelineComment(ctx context.Context, c *issues_model.Comment, doer *user_
}
if c.Assignee != nil {
comment.Assignee = ToUser(c.Assignee, nil)
comment.Assignee = ToUser(ctx, c.Assignee, nil)
}
if c.AssigneeTeam != nil {
comment.AssigneeTeam, _ = ToTeam(c.AssigneeTeam)
comment.AssigneeTeam, _ = ToTeam(ctx, c.AssigneeTeam)
}
if c.ResolveDoer != nil {
comment.ResolveDoer = ToUser(c.ResolveDoer, nil)
comment.ResolveDoer = ToUser(ctx, c.ResolveDoer, nil)
}
if c.DependentIssue != nil {
+2 -2
View File
@@ -28,9 +28,9 @@ func ToPackage(ctx context.Context, pd *packages.PackageDescriptor, doer *user_m
return &api.Package{
ID: pd.Version.ID,
Owner: ToUser(pd.Owner, doer),
Owner: ToUser(ctx, pd.Owner, doer),
Repository: repo,
Creator: ToUser(pd.Creator, doer),
Creator: ToUser(ctx, pd.Creator, doer),
Type: string(pd.Package.Type),
Name: pd.Package.Name,
Version: pd.Version.Version,
+1 -1
View File
@@ -201,7 +201,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u
if pr.HasMerged {
apiPullRequest.Merged = pr.MergedUnix.AsTimePtr()
apiPullRequest.MergedCommitID = &pr.MergedCommitID
apiPullRequest.MergedBy = ToUser(pr.Merger, nil)
apiPullRequest.MergedBy = ToUser(ctx, pr.Merger, nil)
}
return apiPullRequest
+4 -4
View File
@@ -21,14 +21,14 @@ func ToPullReview(ctx context.Context, r *issues_model.Review, doer *user_model.
r.Reviewer = user_model.NewGhostUser()
}
apiTeam, err := ToTeam(r.ReviewerTeam)
apiTeam, err := ToTeam(ctx, r.ReviewerTeam)
if err != nil {
return nil, err
}
result := &api.PullReview{
ID: r.ID,
Reviewer: ToUser(r.Reviewer, doer),
Reviewer: ToUser(ctx, r.Reviewer, doer),
ReviewerTeam: apiTeam,
State: api.ReviewStateUnknown,
Body: r.Content,
@@ -93,8 +93,8 @@ func ToPullReviewCommentList(ctx context.Context, review *issues_model.Review, d
apiComment := &api.PullReviewComment{
ID: comment.ID,
Body: comment.Content,
Poster: ToUser(comment.Poster, doer),
Resolver: ToUser(comment.ResolveDoer, doer),
Poster: ToUser(ctx, comment.Poster, doer),
Resolver: ToUser(ctx, comment.ResolveDoer, doer),
ReviewID: review.ID,
Created: comment.CreatedUnix.AsTime(),
Updated: comment.UpdatedUnix.AsTime(),
+4 -2
View File
@@ -4,12 +4,14 @@
package convert
import (
"context"
repo_model "code.gitea.io/gitea/models/repo"
api "code.gitea.io/gitea/modules/structs"
)
// ToRelease convert a repo_model.Release to api.Release
func ToRelease(r *repo_model.Release) *api.Release {
func ToRelease(ctx context.Context, r *repo_model.Release) *api.Release {
return &api.Release{
ID: r.ID,
TagName: r.TagName,
@@ -24,7 +26,7 @@ func ToRelease(r *repo_model.Release) *api.Release {
IsPrerelease: r.IsPrerelease,
CreatedAt: r.CreatedUnix.AsTime(),
PublishedAt: r.CreatedUnix.AsTime(),
Publisher: ToUser(r.Publisher, nil),
Publisher: ToUser(ctx, r.Publisher, nil),
Attachments: ToAttachments(r.Attachments),
}
}
+7 -7
View File
@@ -126,7 +126,7 @@ func innerToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.Acc
if err := t.LoadAttributes(ctx); err != nil {
log.Warn("LoadAttributes of RepoTransfer: %v", err)
} else {
transfer = ToRepoTransfer(t)
transfer = ToRepoTransfer(ctx, t)
}
}
}
@@ -140,7 +140,7 @@ func innerToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.Acc
return &api.Repository{
ID: repo.ID,
Owner: ToUserWithAccessMode(repo.Owner, mode),
Owner: ToUserWithAccessMode(ctx, repo.Owner, mode),
Name: repo.Name,
FullName: repo.FullName(),
Description: repo.Description,
@@ -185,7 +185,7 @@ func innerToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.Acc
DefaultDeleteBranchAfterMerge: defaultDeleteBranchAfterMerge,
DefaultMergeStyle: string(defaultMergeStyle),
DefaultAllowMaintainerEdit: defaultAllowMaintainerEdit,
AvatarURL: repo.AvatarLink(),
AvatarURL: repo.AvatarLink(ctx),
Internal: !repo.IsPrivate && repo.Owner.Visibility == api.VisibleTypePrivate,
MirrorInterval: mirrorInterval,
MirrorUpdated: mirrorUpdated,
@@ -194,12 +194,12 @@ func innerToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.Acc
}
// ToRepoTransfer convert a models.RepoTransfer to a structs.RepeTransfer
func ToRepoTransfer(t *models.RepoTransfer) *api.RepoTransfer {
teams, _ := ToTeams(t.Teams, false)
func ToRepoTransfer(ctx context.Context, t *models.RepoTransfer) *api.RepoTransfer {
teams, _ := ToTeams(ctx, t.Teams, false)
return &api.RepoTransfer{
Doer: ToUser(t.Doer, nil),
Recipient: ToUser(t.Recipient, nil),
Doer: ToUser(ctx, t.Doer, nil),
Recipient: ToUser(ctx, t.Recipient, nil),
Teams: teams,
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ func ToCommitStatus(ctx context.Context, status *git_model.CommitStatus) *api.Co
if status.CreatorID != 0 {
creator, _ := user_model.GetUserByID(ctx, status.CreatorID)
apiStatus.Creator = ToUser(creator, nil)
apiStatus.Creator = ToUser(ctx, creator, nil)
}
return apiStatus
+12 -10
View File
@@ -4,6 +4,8 @@
package convert
import (
"context"
"code.gitea.io/gitea/models/perm"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@@ -11,7 +13,7 @@ import (
// ToUser convert user_model.User to api.User
// if doer is set, private information is added if the doer has the permission to see it
func ToUser(user, doer *user_model.User) *api.User {
func ToUser(ctx context.Context, user, doer *user_model.User) *api.User {
if user == nil {
return nil
}
@@ -21,36 +23,36 @@ func ToUser(user, doer *user_model.User) *api.User {
signed = true
authed = doer.ID == user.ID || doer.IsAdmin
}
return toUser(user, signed, authed)
return toUser(ctx, user, signed, authed)
}
// ToUsers convert list of user_model.User to list of api.User
func ToUsers(doer *user_model.User, users []*user_model.User) []*api.User {
func ToUsers(ctx context.Context, doer *user_model.User, users []*user_model.User) []*api.User {
result := make([]*api.User, len(users))
for i := range users {
result[i] = ToUser(users[i], doer)
result[i] = ToUser(ctx, users[i], doer)
}
return result
}
// ToUserWithAccessMode convert user_model.User to api.User
// AccessMode is not none show add some more information
func ToUserWithAccessMode(user *user_model.User, accessMode perm.AccessMode) *api.User {
func ToUserWithAccessMode(ctx context.Context, user *user_model.User, accessMode perm.AccessMode) *api.User {
if user == nil {
return nil
}
return toUser(user, accessMode != perm.AccessModeNone, false)
return toUser(ctx, user, accessMode != perm.AccessModeNone, false)
}
// toUser convert user_model.User to api.User
// signed shall only be set if requester is logged in. authed shall only be set if user is site admin or user himself
func toUser(user *user_model.User, signed, authed bool) *api.User {
func toUser(ctx context.Context, user *user_model.User, signed, authed bool) *api.User {
result := &api.User{
ID: user.ID,
UserName: user.Name,
FullName: user.FullName,
Email: user.GetEmail(),
AvatarURL: user.AvatarLink(),
AvatarURL: user.AvatarLink(ctx),
Created: user.CreatedUnix.AsTime(),
Restricted: user.IsRestricted,
Location: user.Location,
@@ -97,9 +99,9 @@ func User2UserSettings(user *user_model.User) api.UserSettings {
}
// ToUserAndPermission return User and its collaboration permission for a repository
func ToUserAndPermission(user, doer *user_model.User, accessMode perm.AccessMode) api.RepoCollaboratorPermission {
func ToUserAndPermission(ctx context.Context, user, doer *user_model.User, accessMode perm.AccessMode) api.RepoCollaboratorPermission {
return api.RepoCollaboratorPermission{
User: ToUser(user, doer),
User: ToUser(ctx, user, doer),
Permission: accessMode.String(),
RoleName: accessMode.String(),
}

Some files were not shown because too many files have changed in this diff Show More