token.go 2.4 KB

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