diff options
author | Frode Aannevik <frode.aa@gmail.com> | 2019-10-15 23:09:47 +0200 |
---|---|---|
committer | Unknwon <u@gogs.io> | 2019-10-15 14:09:47 -0700 |
commit | ffbb0f6a60a000e42f26fd1e08925de1f2ff90be (patch) | |
tree | 2da6d91b9cdc3410b718a40cf98eddb3a4e1ddad /models | |
parent | 1c82c42cb357b4d1c190a30346f52e11427e8470 (diff) |
token: disallow multiple tokens with same name (#5820)
* api/v1: don't allow multiple tokens with same name
Fail with 422 Unprocessable Entity if the token name
already exist
ref: https://github.com/gogs/gogs/issues/5587
* Move new token error type to models/errors/token
* Remove "useless" ListAccessTokensByName function
* Add an i18n entry for token_name_exists
Diffstat (limited to 'models')
-rw-r--r-- | models/errors/token.go | 16 | ||||
-rw-r--r-- | models/token.go | 18 |
2 files changed, 31 insertions, 3 deletions
diff --git a/models/errors/token.go b/models/errors/token.go new file mode 100644 index 00000000..d6a4577a --- /dev/null +++ b/models/errors/token.go @@ -0,0 +1,16 @@ +package errors + +import "fmt" + +type AccessTokenNameAlreadyExist struct { + Name string +} + +func IsAccessTokenNameAlreadyExist(err error) bool { + _, ok := err.(AccessTokenNameAlreadyExist) + return ok +} + +func (err AccessTokenNameAlreadyExist) Error() string { + return fmt.Sprintf("access token already exist [name: %s]", err.Name) +} diff --git a/models/token.go b/models/token.go index 7e1dc166..b757c7d7 100644 --- a/models/token.go +++ b/models/token.go @@ -5,12 +5,13 @@ package models import ( + "fmt" "time" "github.com/go-xorm/xorm" - gouuid "github.com/satori/go.uuid" - + "github.com/gogs/gogs/models/errors" "github.com/gogs/gogs/pkg/tool" + gouuid "github.com/satori/go.uuid" ) // AccessToken represents a personal access token. @@ -47,10 +48,21 @@ func (t *AccessToken) AfterSet(colName string, _ xorm.Cell) { } } +func isAccessTokenNameExist(uid int64, name string) (bool, error) { + return x.Where("uid=?", uid).And("name=?", name).Get(&AccessToken{}) +} + // NewAccessToken creates new access token. func NewAccessToken(t *AccessToken) error { t.Sha1 = tool.SHA1(gouuid.NewV4().String()) - _, err := x.Insert(t) + has, err := isAccessTokenNameExist(t.UID, t.Name) + if err != nil { + return fmt.Errorf("IsAccessTokenNameExists: %v", err) + } else if has { + return errors.AccessTokenNameAlreadyExist{t.Name} + } + + _, err = x.Insert(t) return err } |