token.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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
  17. Uid int64
  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. // DeleteAccessTokenById deletes access token by given ID.
  56. func DeleteAccessTokenById(id int64) error {
  57. _, err := x.Id(id).Delete(new(AccessToken))
  58. return err
  59. }