瀏覽代碼

Save authenticated user information in JSON

Instead of using an INI file for the access token, this stores it and
other user information in a single JSON file.
pull/20/head
Matt Baer 5 年之前
父節點
當前提交
97f29319ee
共有 3 個檔案被更改,包括 50 行新增8 行删除
  1. +7
    -4
      cmd/writeas/api.go
  2. +3
    -3
      cmd/writeas/commands.go
  3. +40
    -1
      cmd/writeas/userconfig.go

+ 7
- 4
cmd/writeas/api.go 查看文件

@@ -129,7 +129,7 @@ func DoDelete(c *cli.Context, friendlyID, token string, tor bool) error {
return nil
}

func DoLogIn(c *cli.Context, uc *UserConfig, username, password string) error {
func DoLogIn(c *cli.Context, username, password string) error {
cl := client(userAgent(c), isTor(c))

u, err := cl.LogIn(username, password)
@@ -140,7 +140,10 @@ func DoLogIn(c *cli.Context, uc *UserConfig, username, password string) error {
return err
}

uc.API.Token = u.AccessToken
Info(c, "Success.")
return saveConfig(uc)
err = saveUser(u)
if err != nil {
return err
}
fmt.Printf("Logged in as %s.\n", u.User.Username)
return nil
}

+ 3
- 3
cmd/writeas/commands.go 查看文件

@@ -156,11 +156,11 @@ func cmdList(c *cli.Context) error {

func cmdAuth(c *cli.Context) error {
// Check configuration
uc, err := loadConfig()
u, err := loadUser()
if err != nil {
return cli.NewExitError(fmt.Sprintf("couldn't load config: %v", err), 1)
}
if uc != nil && uc.API.Token != "" {
if u != nil && u.AccessToken != "" {
return cli.NewExitError("You're already authenticated.", 1)
}

@@ -180,5 +180,5 @@ func cmdAuth(c *cli.Context) error {
if len(pass) == 0 {
return cli.NewExitError("Please enter your password.", 1)
}
return DoLogIn(c, uc, username, string(pass))
return DoLogIn(c, username, string(pass))
}

+ 40
- 1
cmd/writeas/userconfig.go 查看文件

@@ -1,17 +1,21 @@
package main

import (
"encoding/json"
"github.com/writeas/go-writeas"
"github.com/writeas/writeas-cli/fileutils"
"gopkg.in/ini.v1"
"io/ioutil"
"path/filepath"
)

const (
userConfigFile = "config.ini"
userFile = "user.json"
)

type (
APIConfig struct {
Token string `ini:"token"`
}

UserConfig struct {
@@ -43,3 +47,38 @@ func saveConfig(uc *UserConfig) error {

return cfg.SaveTo(filepath.Join(userDataDir(), userConfigFile))
}

func loadUser() (*writeas.AuthUser, error) {
fname := filepath.Join(userDataDir(), userFile)
userJSON, err := ioutil.ReadFile(fname)
if err != nil {
if !fileutils.Exists(fname) {
// Don't return a file-not-found error
return nil, nil
}
return nil, err
}

// Parse JSON file
u := &writeas.AuthUser{}
err = json.Unmarshal(userJSON, u)
if err != nil {
return nil, err
}
return u, nil
}

func saveUser(u *writeas.AuthUser) error {
// Marshal struct into pretty-printed JSON
userJSON, err := json.MarshalIndent(u, "", " ")
if err != nil {
return err
}

// Save file
err = ioutil.WriteFile(filepath.Join(userDataDir(), userFile), userJSON, 0600)
if err != nil {
return err
}
return nil
}

Loading…
取消
儲存