2014-05-21 09:55:21 -04:00
|
|
|
// Copyright 2014 The oauth2 Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
2014-05-18 18:14:56 -04:00
|
|
|
|
|
|
|
package oauth2
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io/ioutil"
|
2014-05-26 05:53:51 -04:00
|
|
|
"os"
|
2014-05-18 18:14:56 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// Cache represents a token cacher.
|
|
|
|
type Cache interface {
|
2014-05-26 05:53:51 -04:00
|
|
|
// Token returns the initial token retrieved from the cache,
|
|
|
|
// if there is no existing token nil value is returned.
|
|
|
|
Token() (token *Token)
|
2014-05-18 18:14:56 -04:00
|
|
|
// Write writes a token to the specified file.
|
2014-05-21 09:56:44 -04:00
|
|
|
Write(token *Token)
|
2014-05-18 18:14:56 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewFileCache creates a new file cache.
|
2014-05-26 05:53:51 -04:00
|
|
|
func NewFileCache(filename string) (cache *FileCache, err error) {
|
|
|
|
data, err := ioutil.ReadFile(filename)
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
// no token has cached before, skip reading
|
|
|
|
return &FileCache{filename: filename}, nil
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
var token Token
|
|
|
|
if err = json.Unmarshal(data, &token); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
cache = &FileCache{filename: filename, initialToken: &token}
|
|
|
|
return
|
2014-05-18 18:14:56 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// FileCache represents a file based token cacher.
|
|
|
|
type FileCache struct {
|
2014-05-22 08:33:36 -04:00
|
|
|
// Handler to be invoked if an error occurs
|
|
|
|
// during read or write operations.
|
|
|
|
ErrorHandler func(error)
|
|
|
|
|
2014-05-26 05:53:51 -04:00
|
|
|
initialToken *Token
|
|
|
|
filename string
|
2014-05-18 18:14:56 -04:00
|
|
|
}
|
|
|
|
|
2014-05-26 05:53:51 -04:00
|
|
|
// Token returns the initial token read from the cache. It should be used to
|
|
|
|
// warm the authorization mechanism, token refreshes and later writes don't
|
|
|
|
// change the returned value. If no token is cached before, returns nil.
|
|
|
|
func (f *FileCache) Token() (token *Token) {
|
|
|
|
return f.initialToken
|
2014-05-18 18:14:56 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Write writes a token to the specified file.
|
2014-05-21 09:56:44 -04:00
|
|
|
func (f *FileCache) Write(token *Token) {
|
2014-05-18 18:14:56 -04:00
|
|
|
data, err := json.Marshal(token)
|
2014-05-21 09:56:44 -04:00
|
|
|
if err == nil {
|
|
|
|
err = ioutil.WriteFile(f.filename, data, 0644)
|
|
|
|
}
|
2014-05-22 08:33:36 -04:00
|
|
|
if f.ErrorHandler != nil {
|
|
|
|
f.ErrorHandler(err)
|
2014-05-18 18:14:56 -04:00
|
|
|
}
|
|
|
|
}
|