token.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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/gogits/gogs/modules/base"
  8. "github.com/gogits/gogs/modules/uuid"
  9. )
  10. // AccessToken represents a personal access token.
  11. type AccessToken struct {
  12. ID int64 `xorm:"pk autoincr"`
  13. UID int64 `xorm:"INDEX"`
  14. Name string
  15. Sha1 string `xorm:"UNIQUE VARCHAR(40)"`
  16. Created time.Time `xorm:"CREATED"`
  17. Updated time.Time
  18. HasRecentActivity bool `xorm:"-"`
  19. HasUsed bool `xorm:"-"`
  20. }
  21. // NewAccessToken creates new access token.
  22. func NewAccessToken(t *AccessToken) error {
  23. t.Sha1 = base.EncodeSha1(uuid.NewV4().String())
  24. _, err := x.Insert(t)
  25. return err
  26. }
  27. // GetAccessTokenBySHA returns access token by given sha1.
  28. func GetAccessTokenBySHA(sha string) (*AccessToken, error) {
  29. t := &AccessToken{Sha1: sha}
  30. has, err := x.Get(t)
  31. if err != nil {
  32. return nil, err
  33. } else if !has {
  34. return nil, ErrAccessTokenNotExist{sha}
  35. }
  36. return t, nil
  37. }
  38. // ListAccessTokens returns a list of access tokens belongs to given user.
  39. func ListAccessTokens(uid int64) ([]*AccessToken, error) {
  40. tokens := make([]*AccessToken, 0, 5)
  41. err := x.Where("uid=?", uid).Desc("id").Find(&tokens)
  42. if err != nil {
  43. return nil, err
  44. }
  45. for _, t := range tokens {
  46. t.HasUsed = t.Updated.After(t.Created)
  47. t.HasRecentActivity = t.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  48. }
  49. return tokens, nil
  50. }
  51. // UpdateAccessToekn updates information of access token.
  52. func UpdateAccessToekn(t *AccessToken) error {
  53. _, err := x.Id(t.ID).AllCols().Update(t)
  54. return err
  55. }
  56. // DeleteAccessTokenByID deletes access token by given ID.
  57. func DeleteAccessTokenByID(id int64) error {
  58. _, err := x.Id(id).Delete(new(AccessToken))
  59. return err
  60. }