Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

token.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "time"
  7. gouuid "github.com/satori/go.uuid"
  8. "code.gitea.io/gitea/modules/base"
  9. )
  10. // AccessToken represents a personal access token.
  11. type AccessToken struct {
  12. ID int64 `xorm:"pk autoincr"`
  13. UID int64 `xorm:"INDEX"`
  14. Name string
  15. Sha1 string `xorm:"UNIQUE VARCHAR(40)"`
  16. Created time.Time `xorm:"-"`
  17. CreatedUnix int64 `xorm:"INDEX created"`
  18. Updated time.Time `xorm:"-"`
  19. UpdatedUnix int64 `xorm:"INDEX updated"`
  20. HasRecentActivity bool `xorm:"-"`
  21. HasUsed bool `xorm:"-"`
  22. }
  23. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  24. func (t *AccessToken) AfterLoad() {
  25. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  26. t.Updated = time.Unix(t.UpdatedUnix, 0).Local()
  27. t.HasUsed = t.Updated.After(t.Created)
  28. t.HasRecentActivity = t.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  29. }
  30. // NewAccessToken creates new access token.
  31. func NewAccessToken(t *AccessToken) error {
  32. t.Sha1 = base.EncodeSha1(gouuid.NewV4().String())
  33. _, err := x.Insert(t)
  34. return err
  35. }
  36. // GetAccessTokenBySHA returns access token by given sha1.
  37. func GetAccessTokenBySHA(sha string) (*AccessToken, error) {
  38. if sha == "" {
  39. return nil, ErrAccessTokenEmpty{}
  40. }
  41. t := &AccessToken{Sha1: sha}
  42. has, err := x.Get(t)
  43. if err != nil {
  44. return nil, err
  45. } else if !has {
  46. return nil, ErrAccessTokenNotExist{sha}
  47. }
  48. return t, nil
  49. }
  50. // ListAccessTokens returns a list of access tokens belongs to given user.
  51. func ListAccessTokens(uid int64) ([]*AccessToken, error) {
  52. tokens := make([]*AccessToken, 0, 5)
  53. return tokens, x.
  54. Where("uid=?", uid).
  55. Desc("id").
  56. Find(&tokens)
  57. }
  58. // UpdateAccessToken updates information of access token.
  59. func UpdateAccessToken(t *AccessToken) error {
  60. _, err := x.ID(t.ID).AllCols().Update(t)
  61. return err
  62. }
  63. // DeleteAccessTokenByID deletes access token by given ID.
  64. func DeleteAccessTokenByID(id, userID int64) error {
  65. cnt, err := x.ID(id).Delete(&AccessToken{
  66. UID: userID,
  67. })
  68. if err != nil {
  69. return err
  70. } else if cnt != 1 {
  71. return ErrAccessTokenNotExist{}
  72. }
  73. return nil
  74. }