Skip to content

Commit

Permalink
auth api clean
Browse files Browse the repository at this point in the history
  • Loading branch information
olebeck committed Jul 14, 2024
1 parent b30e3ab commit efbf09a
Show file tree
Hide file tree
Showing 10 changed files with 94 additions and 95 deletions.
2 changes: 1 addition & 1 deletion cmd/bedrocktool/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ func (c *TransCMD) Execute(ctx context.Context) error {
if utils.Auth.LoggedIn() {
logrus.Info("Already Logged in")
} else {
utils.Auth.Login(ctx, nil)
utils.Auth.Login(ctx)
}
}
fmt.Println(BlackFg + Bold + Blue + " Trans " + Pink + " Rights " + White + " Are " + Pink + " Human " + Blue + " Rights " + Reset)
Expand Down
2 changes: 1 addition & 1 deletion subcommands/realms-list.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func (*RealmListCMD) Synopsis() string { return locale.Loc("list_realm
func (c *RealmListCMD) SetFlags(f *flag.FlagSet) {}
func (c *RealmListCMD) Execute(ctx context.Context) error {
if !utils.Auth.LoggedIn() {
err := utils.Auth.Login(ctx, nil)
err := utils.Auth.Login(ctx)
if err != nil {
return err
}
Expand Down
4 changes: 2 additions & 2 deletions ui/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ func (c *CLI) HandleMessage(msg *messages.Message) *messages.Message {
switch data := msg.Data.(type) {
case messages.RequestLogin:
if data.Wait {
utils.Auth.Login(c.ctx, nil)
utils.Auth.Login(c.ctx)
} else {
go utils.Auth.Login(c.ctx, nil)
go utils.Auth.Login(c.ctx)
}
}
return nil
Expand Down
17 changes: 9 additions & 8 deletions ui/gui/gui.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,7 @@ func (g *GUI) Init() bool {
Axis: layout.Vertical,
},
}
g.router = pages.NewRouter(g)
g.router.Register(settings.New, settings.ID)
g.router.Register(worlds.New, worlds.ID)
g.router.Register(skins.New, skins.ID)
g.router.Register(packs.New, packs.ID)
g.logger.router = g.router
g.router.LogWidget = g.logger.Layout

return true
}

Expand All @@ -64,7 +58,14 @@ var paletteDark = material.Palette{
}

func (g *GUI) Start(ctx context.Context, cancel context.CancelCauseFunc) (err error) {
g.router.Ctx = ctx
g.router = pages.NewRouter(g, ctx)
g.router.Register(settings.New, settings.ID)
g.router.Register(worlds.New, worlds.ID)
g.router.Register(skins.New, skins.ID)
g.router.Register(packs.New, packs.ID)
g.logger.router = g.router
g.router.LogWidget = g.logger.Layout

g.ctx = ctx
g.cancel = cancel

Expand Down
58 changes: 40 additions & 18 deletions ui/gui/pages/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,17 @@ import (
)

type Router struct {
ui ui.UI
th *material.Theme
Ctx context.Context
ui ui.UI
th *material.Theme
auth *authHandler

ctx context.Context
cmdCtx context.Context
cmdCtxCancel context.CancelFunc
Wg sync.WaitGroup
Invalidate func()
LogWidget func(layout.Context, *material.Theme) layout.Dimensions

Wg sync.WaitGroup
Invalidate func()
LogWidget func(layout.Context, *material.Theme) layout.Dimensions

pages map[string]func(invalidate func()) Page
currentPage Page
Expand All @@ -58,12 +61,13 @@ type Router struct {
ShuttingDown bool
}

func NewRouter(uii ui.UI) *Router {
func NewRouter(ui ui.UI, ctx context.Context) *Router {
modal := component.NewModal()
nav := component.NewNav("Navigation Drawer", "This is an example.")

r := &Router{
ui: uii,
ctx: ctx,
ui: ui,
pages: make(map[string]func(invalidate func()) Page),
ModalLayer: modal,
ModalNavDrawer: component.ModalNavFrom(&nav, modal),
Expand All @@ -74,9 +78,33 @@ func NewRouter(uii ui.UI) *Router {
},
}

r.auth = &authHandler{r: r}
utils.Auth.SetHandler(r.auth)

return r
}

type authHandler struct {
r *Router

cancel context.CancelFunc
}

func (a *authHandler) AuthCode(uri, code string) {
loginPopup := popups.NewGuiAuth(a.r.Invalidate, uri, code)
a.r.PushPopup(loginPopup)
}

func (a *authHandler) Finished(err error) {
a.cancel()
a.r.RemovePopup("ms-auth")
if err != nil {
if !errors.Is(err, context.Canceled) {
a.r.PushPopup(popups.NewErrorPopup(err, nil, false))
}
}
}

func (r *Router) Register(p func(invalidate func()) Page, id string) {
r.pages[id] = p
}
Expand Down Expand Up @@ -265,17 +293,11 @@ func (r *Router) HandleMessage(msg *messages.Message) *messages.Message {
break
}
r.loggingIn = true
ctx, cancel := context.WithCancel(r.Ctx)
loginPopup := popups.NewGuiAuth(r.Invalidate, cancel, func(err error) {})
r.PushPopup(loginPopup)
ctx, cancel := context.WithCancel(r.ctx)
r.auth.cancel = cancel
c := make(chan struct{})
go func() {
err := utils.Auth.Login(ctx, loginPopup)
if err != nil {
if !errors.Is(err, context.Canceled) {
r.PushPopup(popups.NewErrorPopup(err, nil, false))
}
}
_ = utils.Auth.Login(ctx)
r.loggingIn = false
r.Invalidate()
close(c)
Expand All @@ -301,7 +323,7 @@ func (r *Router) Execute(cmd commands.Command) {
r.Wg.Add(1)
go func() {
defer r.Wg.Done()
r.cmdCtx, r.cmdCtxCancel = context.WithCancel(r.Ctx)
r.cmdCtx, r.cmdCtxCancel = context.WithCancel(r.ctx)

recovery.ErrorHandler = func(err error) {
utils.PrintPanic(err)
Expand Down
27 changes: 2 additions & 25 deletions ui/gui/popups/authpopup.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,36 +9,16 @@ import (
)

type guiAuth struct {
invalidate func()
cancel func()
onError func(error)
uri string
click widget.Clickable
code string
codeSelect widget.Selectable
close widget.Clickable
}

func (g *guiAuth) AuthCode(uri string, code string) {
g.uri = uri
g.code = code
g.invalidate()
}

func (g *guiAuth) Finished(err error) {
if err != nil {
g.onError(err)
}
messages.Router.Handle(&messages.Message{
Source: "ui",
Target: "ui",
Data: messages.Close{Type: "popup", ID: g.ID()},
})
g.cancel()
}

func NewGuiAuth(invalidate func(), cancel func(), onError func(error)) *guiAuth {
return &guiAuth{invalidate: invalidate, cancel: cancel, onError: onError}
func NewGuiAuth(cancel func(), uri, code string) *guiAuth {
return &guiAuth{cancel: cancel, uri: uri, code: code}
}

func (guiAuth) ID() string {
Expand All @@ -65,9 +45,6 @@ func (g *guiAuth) Layout(gtx layout.Context, th *material.Theme) layout.Dimensio
}.Layout(gtx,
layout.Flexed(1, func(gtx C) D {
return layout.Center.Layout(gtx, func(gtx C) D {
if g.code == "" {
return material.Body1(th, "Loading").Layout(gtx)
}
return layout.Flex{Axis: layout.Vertical, Alignment: layout.Middle}.Layout(gtx,
layout.Rigid(func(gtx C) D {
return layout.Flex{
Expand Down
5 changes: 3 additions & 2 deletions ui/tui/tui.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func (c *TUI) Init() bool {

func (c *TUI) Start(ctx context.Context, cancel context.CancelCauseFunc) error {
c.ctx = ctx
utils.Auth.SetHandler(nil)
isDebug := updater.Version == ""
if !isDebug {
go updater.UpdateCheck(c)
Expand Down Expand Up @@ -74,9 +75,9 @@ func (c *TUI) HandleMessage(msg *messages.Message) *messages.Message {
switch msg := msg.Data.(type) {
case messages.RequestLogin:
if msg.Wait {
utils.Auth.Login(c.ctx, nil)
utils.Auth.Login(c.ctx)
} else {
go utils.Auth.Login(c.ctx, nil)
go utils.Auth.Login(c.ctx)
}
case *messages.ServerInput:
_ = msg
Expand Down
62 changes: 33 additions & 29 deletions utils/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ import (
const TokenFile = "token.json"

type authsrv struct {
liveToken *oauth2.Token
tokenSource oauth2.TokenSource
realms *realms.Client
log *logrus.Entry
log *logrus.Entry
handler auth.MSAuthHandler
liveToken *oauth2.Token
realms *realms.Client
}

var Auth authsrv = authsrv{
var Auth *authsrv = &authsrv{
log: logrus.WithField("part", "Auth"),
}

Expand All @@ -35,57 +35,55 @@ func (a *authsrv) Startup() (err error) {
if err != nil {
return err
}
a.tokenSource = auth.RefreshTokenSource(a.liveToken)
a.realms = realms.NewClient(a.tokenSource)
_, err = a.TokenSource()
if err != nil {
return err
}
a.realms = realms.NewClient(a)
return nil
}

// if the user is currently logged in or not
func (a *authsrv) LoggedIn() bool {
return a.tokenSource != nil
return a.liveToken != nil
}

// performs microsoft login using the handler passed
func (a *authsrv) Login(ctx context.Context, handler auth.MSAuthHandler) (err error) {
a.liveToken, err = auth.RequestLiveTokenWriter(ctx, handler)
func (a *authsrv) SetHandler(handler auth.MSAuthHandler) (err error) {
a.handler = handler
return nil
}

func (a *authsrv) Login(ctx context.Context) (err error) {
a.liveToken, err = auth.RequestLiveTokenWriter(ctx, a.handler)
if err != nil {
return err
}
err = a.writeToken(a.liveToken)
if err != nil {
return err
}
a.tokenSource = auth.RefreshTokenSource(a.liveToken)
a.realms = realms.NewClient(a.tokenSource)

return nil
}

func (a *authsrv) Logout() {
a.liveToken = nil
a.tokenSource = nil
a.realms = nil
os.Remove(TokenFile)
}

func (a *authsrv) refreshLiveToken() (err error) {
if a.liveToken.Valid() {
return nil
}

a.log.Info("Refreshing Microsoft Token")
a.liveToken, err = a.tokenSource.Token()

a.liveToken, err = auth.RefreshToken(a.liveToken)
if err != nil {
return err
}

err = a.writeToken(a.liveToken)
if err != nil {
return err
}
a.tokenSource = auth.RefreshTokenSource(a.liveToken)
a.realms = realms.NewClient(a.tokenSource)
return nil
}

Expand Down Expand Up @@ -128,28 +126,34 @@ func (a *authsrv) readToken() (*oauth2.Token, error) {
}
return &token, nil
case '1':
return Ver1token(f)
if Ver1token != nil {
return Ver1token(f)
}
}

return nil, errors.New("unsupported token file")
}

var ErrNotLoggedIn = errors.New("not logged in")

func (a *authsrv) TokenSource() (src oauth2.TokenSource, err error) {
if a.tokenSource == nil {
// Token implements oauth2.TokenSource, returns ErrNotLoggedIn if there is no token, refreshes it if it expired
func (a *authsrv) Token() (t *oauth2.Token, err error) {
if a.liveToken == nil {
return nil, ErrNotLoggedIn
}
err = a.refreshLiveToken()
if err != nil {
return nil, err
if !a.liveToken.Valid() {
err = a.refreshLiveToken()
if err != nil {
return nil, err
}
}
return a.tokenSource, nil
return a.liveToken, nil
}

func (a *authsrv) Realms() (*realms.Client, error) {
if a.realms != nil {
return a.realms, nil
}
return nil, ErrNotLoggedIn
a.realms = realms.NewClient(a)
return a.realms, nil
}
6 changes: 3 additions & 3 deletions utils/proxy/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/bedrock-tool/bedrocktool/locale"
"github.com/bedrock-tool/bedrocktool/ui/messages"
"github.com/bedrock-tool/bedrocktool/utils"
"github.com/sandertv/gophertunnel/minecraft"
"github.com/sandertv/gophertunnel/minecraft/protocol/login"
"github.com/sandertv/gophertunnel/minecraft/protocol/packet"
Expand Down Expand Up @@ -60,8 +61,7 @@ func (p *Context) connectServer(ctx context.Context) (err error) {
})
logrus.Info(locale.Loc("connecting", locale.Strmap{"Address": p.serverAddress}))
d := minecraft.Dialer{
TokenSource: p.tokenSource,
PacketFunc: p.packetFunc,
PacketFunc: p.packetFunc,
GetClientData: func() login.ClientData {
if p.withClient {
select {
Expand All @@ -78,7 +78,7 @@ func (p *Context) connectServer(ctx context.Context) (err error) {
},
}
for retry := 0; retry < 3; retry++ {
d.ChainKey, d.ChainData, err = minecraft.CreateChain(ctx, p.tokenSource)
d.ChainKey, d.ChainData, err = minecraft.CreateChain(ctx, utils.Auth)
if err != nil {
continue
}
Expand Down
Loading

0 comments on commit efbf09a

Please sign in to comment.