code.gitea.io/gitea@v1.21.7/models/user/redirect.go (about) 1 // Copyright 2020 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package user 5 6 import ( 7 "context" 8 "fmt" 9 "strings" 10 11 "code.gitea.io/gitea/models/db" 12 "code.gitea.io/gitea/modules/util" 13 ) 14 15 // ErrUserRedirectNotExist represents a "UserRedirectNotExist" kind of error. 16 type ErrUserRedirectNotExist struct { 17 Name string 18 } 19 20 // IsErrUserRedirectNotExist check if an error is an ErrUserRedirectNotExist. 21 func IsErrUserRedirectNotExist(err error) bool { 22 _, ok := err.(ErrUserRedirectNotExist) 23 return ok 24 } 25 26 func (err ErrUserRedirectNotExist) Error() string { 27 return fmt.Sprintf("user redirect does not exist [name: %s]", err.Name) 28 } 29 30 func (err ErrUserRedirectNotExist) Unwrap() error { 31 return util.ErrNotExist 32 } 33 34 // Redirect represents that a user name should be redirected to another 35 type Redirect struct { 36 ID int64 `xorm:"pk autoincr"` 37 LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"` 38 RedirectUserID int64 // userID to redirect to 39 } 40 41 // TableName provides the real table name 42 func (Redirect) TableName() string { 43 return "user_redirect" 44 } 45 46 func init() { 47 db.RegisterModel(new(Redirect)) 48 } 49 50 // LookupUserRedirect look up userID if a user has a redirect name 51 func LookupUserRedirect(ctx context.Context, userName string) (int64, error) { 52 userName = strings.ToLower(userName) 53 redirect := &Redirect{LowerName: userName} 54 if has, err := db.GetEngine(ctx).Get(redirect); err != nil { 55 return 0, err 56 } else if !has { 57 return 0, ErrUserRedirectNotExist{Name: userName} 58 } 59 return redirect.RedirectUserID, nil 60 } 61 62 // NewUserRedirect create a new user redirect 63 func NewUserRedirect(ctx context.Context, ID int64, oldUserName, newUserName string) error { 64 oldUserName = strings.ToLower(oldUserName) 65 newUserName = strings.ToLower(newUserName) 66 67 if err := DeleteUserRedirect(ctx, oldUserName); err != nil { 68 return err 69 } 70 71 if err := DeleteUserRedirect(ctx, newUserName); err != nil { 72 return err 73 } 74 75 return db.Insert(ctx, &Redirect{ 76 LowerName: oldUserName, 77 RedirectUserID: ID, 78 }) 79 } 80 81 // DeleteUserRedirect delete any redirect from the specified user name to 82 // anything else 83 func DeleteUserRedirect(ctx context.Context, userName string) error { 84 userName = strings.ToLower(userName) 85 _, err := db.GetEngine(ctx).Delete(&Redirect{LowerName: userName}) 86 return err 87 }