You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. }