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 10:47:46 -04:00
|
|
|
// Reads a cached token. It may return nil if none is cached.
|
2014-06-22 18:19:44 -04:00
|
|
|
Read() (*Token, error)
|
2014-05-26 10:47:46 -04:00
|
|
|
// Write writes a token to the cache.
|
2014-06-22 18:19:44 -04:00
|
|
|
Write(*Token) error
|
2014-05-18 18:14:56 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewFileCache creates a new file cache.
|
2014-05-26 08:45:41 -04:00
|
|
|
func NewFileCache(filename string) (cache *FileCache) {
|
|
|
|
return &FileCache{filename: filename}
|
|
|
|
}
|
|
|
|
|
|
|
|
// FileCache represents a file based token cacher.
|
|
|
|
type FileCache struct {
|
|
|
|
filename string
|
|
|
|
}
|
|
|
|
|
2014-05-26 10:47:46 -04:00
|
|
|
// Read reads the token from the cache file. If there exists no cache
|
|
|
|
// file, it returns nil for the token.
|
2014-05-26 08:45:41 -04:00
|
|
|
func (f *FileCache) Read() (token *Token, err error) {
|
|
|
|
data, err := ioutil.ReadFile(f.filename)
|
2014-05-26 05:53:51 -04:00
|
|
|
if os.IsNotExist(err) {
|
|
|
|
// no token has cached before, skip reading
|
2014-05-26 08:45:41 -04:00
|
|
|
return nil, nil
|
2014-05-26 05:53:51 -04:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if err = json.Unmarshal(data, &token); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
return
|
2014-05-18 18:14:56 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Write writes a token to the specified file.
|
2014-06-22 18:19:44 -04:00
|
|
|
func (f *FileCache) Write(token *Token) error {
|
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-06-22 18:19:44 -04:00
|
|
|
return err
|
2014-05-18 18:14:56 -04:00
|
|
|
}
|