token.go 2.3 KB

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