token.go 2.1 KB

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