Skip to content

Commit

Permalink
feat: save token to repo
Browse files Browse the repository at this point in the history
  • Loading branch information
LinZexiao committed Feb 15, 2023
1 parent b960441 commit 71076c0
Show file tree
Hide file tree
Showing 10 changed files with 182 additions and 94 deletions.
10 changes: 5 additions & 5 deletions auth/app.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package auth

import (
"context"
"fmt"
"net/http"

Expand All @@ -17,7 +16,7 @@ import (
const DefaultAdminTokenName = "defaultLocalToken"

type OAuthApp interface {
verify(ctx context.Context, token string) (*JWTPayload, error)
verify(token string) (*JWTPayload, error)
GetDefaultAdminToken() (string, error)

Verify(c *gin.Context)
Expand Down Expand Up @@ -88,8 +87,9 @@ func Response(c *gin.Context, err error) {
c.AbortWithStatus(http.StatusOK)
}

func (o *oauthApp) verify(ctx context.Context, token string) (*JWTPayload, error) {
return o.srv.Verify(ctx, token)
// verify only called by inner, so use readCtx constant to bypass perm check
func (o *oauthApp) verify(token string) (*JWTPayload, error) {
return o.srv.Verify(readCtx, token)
}

func (o *oauthApp) GetDefaultAdminToken() (string, error) {
Expand All @@ -109,7 +109,7 @@ func (o *oauthApp) GetDefaultAdminToken() (string, error) {
Perm: core.PermAdmin,
})
if err != nil {
return "", fmt.Errorf("create default admin token : %w", err)
return "", fmt.Errorf("create default admin token: %w", err)
}

return ret, nil
Expand Down
2 changes: 1 addition & 1 deletion auth/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ func permMiddleWare(app OAuthApp) gin.HandlerFunc {

token = strings.TrimPrefix(token, "Bearer ")

jwtPayload, err := app.verify(adminCtx, token)
jwtPayload, err := app.verify(token)
if err != nil {
log.Warnf("verify token failed: %s", err)
c.Writer.WriteHeader(401)
Expand Down
25 changes: 11 additions & 14 deletions cli/api.go
Original file line number Diff line number Diff line change
@@ -1,31 +1,28 @@
package cli

import (
"path"
"fmt"

"github.com/filecoin-project/venus-auth/config"
"github.com/filecoin-project/venus-auth/jwtclient"
"github.com/mitchellh/go-homedir"
"github.com/urfave/cli/v2"
"golang.org/x/xerrors"
)

// nolint
func GetCli(ctx *cli.Context) (*jwtclient.AuthClient, error) {
p, err := homedir.Expand(ctx.String("repo"))
repo, err := NewFsRepo(ctx.String("repo"))
if err != nil {
return nil, xerrors.Errorf("could not expand home dir (repo): %w", err)
return nil, fmt.Errorf("create repo: %w", err)
}
cnfPath, err := homedir.Expand(ctx.String("config"))

cnf, err := repo.GetConfig()
if err != nil {
return nil, xerrors.Errorf("could not expand home dir (config): %w", err)
}
if len(cnfPath) == 0 {
cnfPath = path.Join(p, "config.toml")
return nil, fmt.Errorf("get config: %w", err)
}
cnf, err := config.DecodeConfig(cnfPath)

token, err := repo.GetToken()
if err != nil {
return nil, xerrors.Errorf("failed to decode config err: %w", err)
return nil, fmt.Errorf("get token: %w", err)
}
return jwtclient.NewAuthClient("http://localhost:"+cnf.Port, cnf.Token)

return jwtclient.NewAuthClient("http://localhost:"+cnf.Port, token)
}
140 changes: 140 additions & 0 deletions cli/repo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package cli

import (
"fmt"
"os"
"path"

"github.com/filecoin-project/venus-auth/config"
"github.com/mitchellh/go-homedir"
)

type Repo interface {
GetConfig() (*config.Config, error)
SaveConfig(*config.Config) error
GetToken() (string, error)
SaveToken(string) error
GetDataDir() (string, error)
}

const (
// DefaultConfigFile is the default config file name
DefaultConfigFile = "config.toml"
// DefaultDataDir is the default data directory name
DefaultDataDir = "data"
// DefaultTokenFile is the default token file name
DefaultTokenFile = "token"
)

type FsRepo struct {
repoPath string
// configPath is the relative path to the config file from the repoPath
configPath string
// dataPath is the relative path to the data directory from the repoPath
dataPath string
// tokenPath is the relative path to the token file from the repoPath
tokenPath string
}

func (r *FsRepo) GetConfig() (*config.Config, error) {
path := path.Join(r.repoPath, r.configPath)
exist, err := exist(path)
if err != nil {
return nil, fmt.Errorf("check config exist: %w", err)
}
if exist {
cnf, err := config.DecodeConfig(path)
if err != nil {
return nil, fmt.Errorf("decode config: %w", err)
}
return cnf, nil
}
cnf, err := config.DefaultConfig()
if err != nil {
return nil, fmt.Errorf("generate secret: %w", err)
}
err = config.Cover(path, cnf)
if err != nil {
return nil, fmt.Errorf("save config: %w", err)
}
return cnf, nil
}

func (r *FsRepo) SaveConfig(cnf *config.Config) error {
path := path.Join(r.repoPath, r.configPath)
return config.Cover(path, cnf)
}

func (r *FsRepo) GetToken() (string, error) {
path := path.Join(r.repoPath, r.tokenPath)
exist, err := exist(path)
if err != nil {
return "", fmt.Errorf("check token exist: %w", err)
}
if !exist {
return "", fmt.Errorf("token not exist")
}
token, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read token: %w", err)
}

return string(token), nil
}

func (r *FsRepo) SaveToken(token string) error {
path := path.Join(r.repoPath, r.tokenPath)
return os.WriteFile(path, []byte(token), os.ModePerm)
}

func (r *FsRepo) GetDataDir() (string, error) {
ret := path.Join(r.repoPath, r.dataPath)
err := makeDir(ret)
if err != nil {
return "", fmt.Errorf("make data dir: %w", err)
}
return ret, nil
}

func NewFsRepo(repoPath string) (Repo, error) {
afterExpand, err := homedir.Expand(repoPath)
if err != nil {
return nil, fmt.Errorf("expand home dir: %w", err)
}
ret := &FsRepo{
repoPath: afterExpand,
configPath: DefaultConfigFile,
dataPath: DefaultDataDir,
tokenPath: DefaultTokenFile,
}
return ret, nil
}

func makeDir(path string) error {
fi, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
err = os.MkdirAll(path, os.ModePerm)
if err != nil {
return fmt.Errorf("make dir: %w", err)
}
} else {
return fmt.Errorf("stat dir: %w", err)
}
} else {
if !fi.IsDir() {
return fmt.Errorf("path %s is not a dir", path)
}
}
return nil
}

func exist(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
} else if !os.IsNotExist(err) {
return false, err
}
return false, nil
}
80 changes: 23 additions & 57 deletions cli/run.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
package cli

import (
"fmt"
"net/http"
"path"

"github.com/filecoin-project/venus-auth/auth"
"github.com/filecoin-project/venus-auth/config"
"github.com/filecoin-project/venus-auth/log"
"github.com/gin-gonic/gin"
"github.com/ipfs-force-community/metrics"
"github.com/mitchellh/go-homedir"
"github.com/urfave/cli/v2"
"go.opencensus.io/plugin/ochttp"
)
Expand All @@ -36,57 +34,19 @@ var runCommand = &cli.Command{
Action: run,
}

func MakeDir(path string) {
exist, err := config.Exist(path)
if err != nil {
log.Fatalf("Failed to check file exist : %s", err)
}
if !exist {
err = config.MakeDir(path)
if err != nil {
log.Fatalf("Failed to crate dir : %s", err)
}
}
}
func run(cliCtx *cli.Context) error {
gin.SetMode(gin.ReleaseMode)

func configScan(path string) *config.Config {
exist, err := config.Exist(path)
if err != nil {
log.Fatalf("Failed to check file exist : %s", err)
}
if exist {
cnf, err := config.DecodeConfig(path)
if err != nil {
log.Fatalf("Failed to decode config : %s", err)
}
return cnf
}
cnf, err := config.DefaultConfig()
repoPath := cliCtx.String("repo")
repo, err := NewFsRepo(repoPath)
if err != nil {
log.Fatalf("Failed to generate secret : %s", err)
return fmt.Errorf("init repo: %s", err)
}
err = config.Cover(path, cnf)
cnf, err := repo.GetConfig()
if err != nil {
log.Fatalf("Failed to write config to home dir : %s", err)
return fmt.Errorf("get config: %s", err)
}
return cnf
}

func run(cliCtx *cli.Context) error {
gin.SetMode(gin.ReleaseMode)
cnfPath := cliCtx.String("config")
repo := cliCtx.String("repo")
repo, err := homedir.Expand(repo)
if err != nil {
log.Fatal(err)
}
if cnfPath == "" {
cnfPath = path.Join(repo, "config.toml")
}
MakeDir(repo)
dataPath := path.Join(repo, "data")
MakeDir(dataPath)
cnf := configScan(cnfPath)
log.InitLog(cnf.Log)

if cliCtx.IsSet("mysql-dsn") {
Expand All @@ -96,30 +56,36 @@ func run(cliCtx *cli.Context) error {
cnf.DB.Type = cliCtx.String("db-type")
}

dataPath, err := repo.GetDataDir()
if err != nil {
return fmt.Errorf("get data dir: %s", err)
}

app, err := auth.NewOAuthApp(cnf.Secret, dataPath, cnf.DB)
if err != nil {
log.Fatalf("Failed to init venus-auth: %s", err)
return fmt.Errorf("init oauth app: %s", err)
}

token, err := app.GetDefaultAdminToken()
if err != nil {
log.Fatalf("Failed to get default admin token: %s", err)
return fmt.Errorf("get default admin token: %s", err)
}
cnf.Token = token
err = config.Cover(cnfPath, cnf)

err = repo.SaveToken(token)
if err != nil {
log.Fatal(err)
return fmt.Errorf("save token: %s", err)
}

router := auth.InitRouter(app, !cliCtx.Bool("disable-perm-check"))

if cnf.Trace != nil && cnf.Trace.JaegerTracingEnabled {
log.Infof("register jaeger-tracing exporter to %s, with node-name:%s",
cnf.Trace.JaegerEndpoint, cnf.Trace.ServerName)
if exporter, err := metrics.RegisterJaeger("venus-auth", cnf.Trace); err != nil {
log.Fatalf("RegisterJaegerExporter failed:%s", err.Error())
} else {
defer metrics.UnregisterJaeger(exporter)
exporter, err := metrics.RegisterJaeger("venus-auth", cnf.Trace)
if err != nil {
return fmt.Errorf("RegisterJaegerExporter failed:%w", err)
}
defer metrics.UnregisterJaeger(exporter)
router = &ochttp.Handler{
Handler: router,
}
Expand Down
12 changes: 0 additions & 12 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
type Config struct {
Port string `json:"port"`
Secret string `json:"secret"`
Token string `json:"token"`
ReadTimeout time.Duration `json:"readTimeout"`
WriteTimeout time.Duration `json:"writeTimeout"`
IdleTimeout time.Duration `json:"idleTimeout"`
Expand Down Expand Up @@ -60,7 +59,6 @@ func DefaultConfig() (*Config, error) {
return &Config{
Port: "8989",
Secret: hex.EncodeToString(secret),
Token: "",
ReadTimeout: time.Minute,
WriteTimeout: time.Minute,
IdleTimeout: time.Minute,
Expand Down Expand Up @@ -123,16 +121,6 @@ func DecodeConfig(path string) (c *Config, err error) {
return
}

func Exist(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
} else if !os.IsNotExist(err) {
return false, err
}
return false, nil
}

func Cover(path string, config *Config) error {
c, err := os.Create(path)
if err != nil {
Expand Down
1 change: 0 additions & 1 deletion config/safeConfig.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
Port = "8989"
Secret = "88b8a61690ee648bef9bc73463b8a05917f1916df169c775a3896719466be04a"
Token = ""
ReadTimeout = 60000000000
WriteTimeout = 60000000000
IdleTimeout = 60000000000
Expand Down
Loading

0 comments on commit 71076c0

Please sign in to comment.