"Fossies" - the Fresh Open Source Software Archive

Member "gdrive-2.1.1/auth/file_source.go" (28 May 2021, 1462 Bytes) of package /linux/misc/gdrive-2.1.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Go source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 package auth
    2 
    3 import (
    4     "encoding/json"
    5     "golang.org/x/oauth2"
    6     "io/ioutil"
    7     "os"
    8 )
    9 
   10 func FileSource(path string, token *oauth2.Token, conf *oauth2.Config) oauth2.TokenSource {
   11     return &fileSource{
   12         tokenPath:   path,
   13         tokenSource: conf.TokenSource(oauth2.NoContext, token),
   14     }
   15 }
   16 
   17 type fileSource struct {
   18     tokenPath   string
   19     tokenSource oauth2.TokenSource
   20 }
   21 
   22 func (self *fileSource) Token() (*oauth2.Token, error) {
   23     token, err := self.tokenSource.Token()
   24     if err != nil {
   25         return token, err
   26     }
   27 
   28     // Save token to file
   29     SaveToken(self.tokenPath, token)
   30 
   31     return token, nil
   32 }
   33 
   34 func ReadFile(path string) ([]byte, bool, error) {
   35     if !fileExists(path) {
   36         return nil, false, nil
   37     }
   38 
   39     content, err := ioutil.ReadFile(path)
   40     if err != nil {
   41         return nil, true, err
   42     }
   43     return content, true, nil
   44 }
   45 
   46 
   47 func ReadToken(path string) (*oauth2.Token, bool, error) {
   48 
   49     content, exists, err := ReadFile(path)
   50     if err != nil || exists == false {
   51         return nil, exists, err
   52     }
   53 
   54     token := &oauth2.Token{}
   55     return token, exists, json.Unmarshal(content, token)
   56 }
   57 
   58 func SaveToken(path string, token *oauth2.Token) error {
   59     data, err := json.MarshalIndent(token, "", "  ")
   60     if err != nil {
   61         return err
   62     }
   63 
   64     if err = mkdir(path); err != nil {
   65         return err
   66     }
   67 
   68     // Write to temp file first
   69     tmpFile := path + ".tmp"
   70     err = ioutil.WriteFile(tmpFile, data, 0600)
   71     if err != nil {
   72         os.Remove(tmpFile)
   73         return err
   74     }
   75 
   76     // Move file to correct path
   77     return os.Rename(tmpFile, path)
   78 }