2022-12-19 19:24:01 -05:00
|
|
|
package wsapi
|
|
|
|
|
|
|
|
import (
|
2022-12-20 11:34:25 -05:00
|
|
|
"encoding/json"
|
|
|
|
"io"
|
|
|
|
|
2022-12-19 19:24:01 -05:00
|
|
|
"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}
|
|
|
|
}
|
|
|
|
|
2022-12-20 11:34:25 -05:00
|
|
|
func (ap *authPhase) handleMsg(r io.Reader) error {
|
|
|
|
var authMsg authMsg
|
|
|
|
err := json.NewDecoder(r).Decode(&authMsg)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-12-19 19:24:01 -05:00
|
|
|
refreshToken := ap.b.ValidateAccessToken(authMsg.AccessToken)
|
|
|
|
if refreshToken != nil {
|
|
|
|
ap.finishAuth(refreshToken)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Error().Str("remote", ap.ec.Request().RemoteAddr).Msg("websocket auth failed")
|
|
|
|
|
|
|
|
|
|
|
|
return auth.ErrInvalidAuth
|
|
|
|
}
|
|
|
|
|