blasphem/pkg/wsapi/auth.go

82 lines
1.5 KiB
Go
Raw Normal View History

2022-12-19 19:24:01 -05:00
package wsapi
import (
2022-12-21 13:22:18 -05:00
"context"
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 {
2022-12-20 13:16:30 -05:00
authReq := &struct {
2022-12-19 19:24:01 -05:00
MsgBase
2022-12-20 20:11:11 -05:00
Version string `json:"ha_version"`
2022-12-19 19:24:01 -05:00
}{
2022-12-21 13:22:18 -05:00
MsgBase{Type: "auth_required"},
2022-12-19 19:24:01 -05:00
ws.b.Version(),
}
2022-12-21 13:22:18 -05:00
return ws.conn.WriteJSON(&authReq)
2022-12-19 19:24:01 -05:00
}
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
2022-12-20 19:05:45 -05:00
}
func (ap *authPhase) sendAuthOK() error {
2022-12-21 13:22:18 -05:00
return ap.conn.WriteJSON(struct {
2022-12-20 19:05:45 -05:00
Type string `json:"type"`
2022-12-20 20:11:11 -05:00
Version string `json:"ha_version"`
2022-12-20 19:05:45 -05:00
}{Type: "auth_ok", Version: ap.Blas().Version()})
2022-12-19 19:24:01 -05:00
}
2022-12-20 19:31:46 -05:00
func (ap *authPhase) sendAuthInvalid() error {
2022-12-21 13:22:18 -05:00
return ap.conn.WriteJSON(struct {
2022-12-20 19:31:46 -05:00
Type string `json:"type"`
Message string `json:"message"`
}{Type: "auth_ok", Message: "invalid auth"})
}
2022-12-21 13:22:18 -05:00
func (ap *authPhase) handleMsg(ctx context.Context, r io.Reader) error {
2022-12-20 11:34:25 -05:00
var authMsg authMsg
err := json.NewDecoder(r).Decode(&authMsg)
if err != nil {
return err
}
2022-12-21 13:22:18 -05:00
if err := ctx.Err(); err != nil {
return err
}
2022-12-19 19:24:01 -05:00
refreshToken := ap.b.ValidateAccessToken(authMsg.AccessToken)
if refreshToken != nil {
ap.finishAuth(refreshToken)
2022-12-20 19:05:45 -05:00
return ap.sendAuthOK()
2022-12-19 19:24:01 -05:00
}
log.Error().Str("remote", ap.ec.Request().RemoteAddr).Msg("websocket auth failed")
2022-12-21 13:22:18 -05:00
err = ap.sendAuthInvalid()
if err != nil {
return err
}
return AuthInvalidErr
2022-12-19 19:24:01 -05:00
}