token.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "errors"
  7. "time"
  8. "github.com/gogits/gogs/modules/base"
  9. "github.com/gogits/gogs/modules/uuid"
  10. )
  11. var (
  12. ErrAccessTokenNotExist = errors.New("Access token does not exist")
  13. )
  14. // AccessToken represents a personal access token.
  15. type AccessToken struct {
  16. ID int64 `xorm:"pk autoincr"`
  17. UID int64 `xorm:"uid INDEX"`
  18. Name string
  19. Sha1 string `xorm:"UNIQUE VARCHAR(40)"`
  20. Created time.Time `xorm:"CREATED"`
  21. Updated time.Time
  22. HasRecentActivity bool `xorm:"-"`
  23. HasUsed bool `xorm:"-"`
  24. }
  25. // NewAccessToken creates new access token.
  26. func NewAccessToken(t *AccessToken) error {
  27. t.Sha1 = base.EncodeSha1(uuid.NewV4().String())
  28. _, err := x.Insert(t)
  29. return err
  30. }
  31. // GetAccessTokenBySHA returns access token by given sha1.
  32. func GetAccessTokenBySHA(sha string) (*AccessToken, error) {
  33. t := &AccessToken{Sha1: sha}
  34. has, err := x.Get(t)
  35. if err != nil {
  36. return nil, err
  37. } else if !has {
  38. return nil, ErrAccessTokenNotExist
  39. }
  40. return t, nil
  41. }
  42. // ListAccessTokens returns a list of access tokens belongs to given user.
  43. func ListAccessTokens(uid int64) ([]*AccessToken, error) {
  44. tokens := make([]*AccessToken, 0, 5)
  45. err := x.Where("uid=?", uid).Desc("id").Find(&tokens)
  46. if err != nil {
  47. return nil, err
  48. }
  49. for _, t := range tokens {
  50. t.HasUsed = t.Updated.After(t.Created)
  51. t.HasRecentActivity = t.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  52. }
  53. return tokens, nil
  54. }
  55. // UpdateAccessToekn updates information of access token.
  56. func UpdateAccessToekn(t *AccessToken) error {
  57. _, err := x.Id(t.ID).AllCols().Update(t)
  58. return err
  59. }
  60. // DeleteAccessTokenByID deletes access token by given ID.
  61. func DeleteAccessTokenByID(id int64) error {
  62. _, err := x.Id(id).Delete(new(AccessToken))
  63. return err
  64. }