token.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package auth
  2. import (
  3. "errors"
  4. "net/http"
  5. "time"
  6. uuid "github.com/satori/go.uuid"
  7. )
  8. /*
  9. Token Login Handler
  10. This module support the API request via a user session login token
  11. */
  12. type token struct {
  13. Owner string
  14. CreationTime int64
  15. }
  16. //Create a new token based on the given HTTP request
  17. func (a *AuthAgent) NewTokenFromRequest(w http.ResponseWriter, r *http.Request) (string, error) {
  18. if !a.CheckAuth(r) {
  19. return "", errors.New("User not logged in")
  20. } else {
  21. //Generate a token for this request
  22. username, _ := a.GetUserName(w, r)
  23. newToken := a.NewToken(username)
  24. //Append it to the token storage
  25. return newToken, nil
  26. }
  27. }
  28. //Generate and return a new token that will be valid for the given time
  29. func (a *AuthAgent) NewToken(owner string) string {
  30. //Generate a new token
  31. newToken := uuid.NewV4().String()
  32. //Add token to tokenStore
  33. a.tokenStore.Store(newToken, token{
  34. Owner: owner,
  35. CreationTime: time.Now().Unix(),
  36. })
  37. //Return the new token
  38. return newToken
  39. }
  40. //Get the token owner from the given token
  41. func (a *AuthAgent) GetTokenOwner(tokenString string) (string, error) {
  42. if val, ok := a.tokenStore.Load(tokenString); ok {
  43. return val.(token).Owner, nil
  44. } else {
  45. return "", errors.New("Token not exists")
  46. }
  47. }
  48. //validate if the given token is valid
  49. func (a *AuthAgent) TokenValid(tokenString string) bool {
  50. //Check if the token validation is disabled
  51. if a.ExpireTime == 0 {
  52. return false
  53. }
  54. //Check if key exists
  55. if val, ok := a.tokenStore.Load(tokenString); ok {
  56. //Exists. Check if the time fits
  57. if time.Now().Unix()-val.(token).CreationTime < a.ExpireTime {
  58. return true
  59. } else {
  60. //Expired
  61. a.tokenStore.Delete(tokenString)
  62. return false
  63. }
  64. }
  65. //Token not found
  66. return false
  67. }
  68. //Run a token store scan and remove all expired tokens
  69. func (a *AuthAgent) ClearTokenStore() {
  70. currentTime := time.Now().Unix()
  71. a.tokenStore.Range(func(k interface{}, v interface{}) bool {
  72. if currentTime-v.(token).CreationTime > a.ExpireTime {
  73. a.tokenStore.Delete(k)
  74. }
  75. return true
  76. })
  77. }