token.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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/modules/base"
  10. )
  11. // AccessToken represents a personal access token.
  12. type AccessToken struct {
  13. ID int64 `xorm:"pk autoincr"`
  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().UTC().Unix()
  26. }
  27. func (t *AccessToken) BeforeUpdate() {
  28. t.UpdatedUnix = time.Now().UTC().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 = base.EncodeSha1(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. 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. // DeleteAccessTokenByID deletes access token by given ID.
  68. func DeleteAccessTokenByID(id int64) error {
  69. _, err := x.Id(id).Delete(new(AccessToken))
  70. return err
  71. }