blasphem/pkg/wsapi/auth.go
2022-12-20 19:05:45 -05:00

67 lines
1.3 KiB
Go

package wsapi
import (
"encoding/json"
"io"
"dynatron.me/x/blasphem/pkg/auth"
"github.com/rs/zerolog/log"
)
type authPhase struct {
*wsSession
}
func (ws *wsSession) sendAuthRequired() error {
authReq := &struct {
MsgBase
Version string `json:"version"`
}{
MsgBase{"auth_required"},
ws.b.Version(),
}
return ws.WriteJSON(&authReq)
}
type authMsg struct {
MsgBase
AccessToken auth.AccessToken `json:"access_token"`
}
func (ap *authPhase) msgSchema() interface{} {
return &authMsg{}
}
func (ap *authPhase) finishAuth(rt *auth.RefreshToken) {
ap.user = rt.User
ap.refreshToken = rt
ap.h = &cmdHandler{ap.wsSession}
ap.sendAuthOK()
}
func (ap *authPhase) sendAuthOK() error {
return ap.WriteJSON(struct {
Type string `json:"type"`
Version string `json:"version"`
}{Type: "auth_ok", Version: ap.Blas().Version()})
}
func (ap *authPhase) handleMsg(r io.Reader) error {
log.Debug().Interface("ap", ap).Msg("auth handlemsg")
var authMsg authMsg
err := json.NewDecoder(r).Decode(&authMsg)
if err != nil {
return err
}
refreshToken := ap.b.ValidateAccessToken(authMsg.AccessToken)
if refreshToken != nil {
ap.finishAuth(refreshToken)
return ap.sendAuthOK()
}
log.Error().Str("remote", ap.ec.Request().RemoteAddr).Msg("websocket auth failed")
return auth.ErrInvalidAuth
}