token.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package models
  2. import (
  3. "gitote/gitote/pkg/tool"
  4. "time"
  5. "github.com/go-xorm/xorm"
  6. gouuid "github.com/satori/go.uuid"
  7. )
  8. // AccessToken represents a personal access token.
  9. type AccessToken struct {
  10. ID int64
  11. UID int64 `xorm:"INDEX"`
  12. Name string
  13. Sha1 string `xorm:"UNIQUE VARCHAR(40)"`
  14. Created time.Time `xorm:"-" json:"-"`
  15. CreatedUnix int64
  16. Updated time.Time `xorm:"-" json:"-"` // Note: Updated must below Created for AfterSet.
  17. UpdatedUnix int64
  18. HasRecentActivity bool `xorm:"-" json:"-"`
  19. HasUsed bool `xorm:"-" json:"-"`
  20. }
  21. func (t *AccessToken) BeforeInsert() {
  22. t.CreatedUnix = time.Now().Unix()
  23. }
  24. func (t *AccessToken) BeforeUpdate() {
  25. t.UpdatedUnix = time.Now().Unix()
  26. }
  27. func (t *AccessToken) AfterSet(colName string, _ xorm.Cell) {
  28. switch colName {
  29. case "created_unix":
  30. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  31. case "updated_unix":
  32. t.Updated = time.Unix(t.UpdatedUnix, 0).Local()
  33. t.HasUsed = t.Updated.After(t.Created)
  34. t.HasRecentActivity = t.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  35. }
  36. }
  37. // NewAccessToken creates new access token.
  38. func NewAccessToken(t *AccessToken) error {
  39. t.Sha1 = tool.SHA1(gouuid.NewV4().String())
  40. _, err := x.Insert(t)
  41. return err
  42. }
  43. // GetAccessTokenBySHA returns access token by given sha1.
  44. func GetAccessTokenBySHA(sha string) (*AccessToken, error) {
  45. if sha == "" {
  46. return nil, ErrAccessTokenEmpty{}
  47. }
  48. t := &AccessToken{Sha1: sha}
  49. has, err := x.Get(t)
  50. if err != nil {
  51. return nil, err
  52. } else if !has {
  53. return nil, ErrAccessTokenNotExist{sha}
  54. }
  55. return t, nil
  56. }
  57. // ListAccessTokens returns a list of access tokens belongs to given user.
  58. func ListAccessTokens(uid int64) ([]*AccessToken, error) {
  59. tokens := make([]*AccessToken, 0, 5)
  60. return tokens, x.Where("uid=?", uid).Desc("id").Find(&tokens)
  61. }
  62. // UpdateAccessToken updates information of access token.
  63. func UpdateAccessToken(t *AccessToken) error {
  64. _, err := x.Id(t.ID).AllCols().Update(t)
  65. return err
  66. }
  67. // DeleteAccessTokenOfUserByID deletes access token by given ID.
  68. func DeleteAccessTokenOfUserByID(userID, id int64) error {
  69. _, err := x.Delete(&AccessToken{
  70. ID: id,
  71. UID: userID,
  72. })
  73. return err
  74. }