2018-06-30 16:20:54 +02:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
2018-07-26 14:14:23 +02:00
|
|
|
"github.com/google/uuid"
|
2018-06-30 16:20:54 +02:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
|
2018-07-26 14:14:23 +02:00
|
|
|
"dev.sum7.eu/genofire/golang-lib/websocket"
|
2018-06-30 16:20:54 +02:00
|
|
|
)
|
|
|
|
|
2018-07-26 14:14:23 +02:00
|
|
|
type Auth struct {
|
|
|
|
SessionID uuid.UUID
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ws *WebsocketServer) IsLoggedIn(msg *websocket.Message) bool {
|
|
|
|
auth := Auth{
|
|
|
|
SessionID: msg.Session,
|
|
|
|
}
|
|
|
|
err := ws.db.First(&auth)
|
|
|
|
return err.Error == nil
|
|
|
|
}
|
|
|
|
|
2018-06-30 16:20:54 +02:00
|
|
|
func (ws *WebsocketServer) loginHandler(logger *log.Entry, msg *websocket.Message) error {
|
2018-07-26 14:14:23 +02:00
|
|
|
auth := Auth{
|
|
|
|
SessionID: msg.Session,
|
|
|
|
}
|
|
|
|
err := ws.db.First(&auth)
|
|
|
|
if err.Error == nil {
|
2018-06-30 16:20:54 +02:00
|
|
|
msg.Answer(msg.Subject, true)
|
|
|
|
logger.Warn("already loggedIn")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
secret, ok := msg.Body.(string)
|
|
|
|
if !ok {
|
|
|
|
logger.Warn("invalid secret format")
|
|
|
|
msg.Answer(msg.Subject, false)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
ok = (ws.secret == secret)
|
|
|
|
if ok {
|
2018-07-26 14:14:23 +02:00
|
|
|
err = ws.db.Create(&auth)
|
|
|
|
if err.Error != nil {
|
|
|
|
log.Warnf("database error: %s", err.Error.Error())
|
|
|
|
msg.Answer(msg.Subject, false)
|
|
|
|
return err.Error
|
|
|
|
}
|
2018-06-30 16:20:54 +02:00
|
|
|
logger.Debug("done")
|
|
|
|
} else {
|
|
|
|
logger.Warn("wrong secret")
|
|
|
|
}
|
|
|
|
msg.Answer(msg.Subject, ok)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ws *WebsocketServer) authStatusHandler(logger *log.Entry, msg *websocket.Message) error {
|
|
|
|
defer logger.Debug("done")
|
2018-07-26 14:14:23 +02:00
|
|
|
|
|
|
|
msg.Answer(msg.Subject, ws.IsLoggedIn(msg))
|
2018-06-30 16:20:54 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
func (ws *WebsocketServer) logoutHandler(logger *log.Entry, msg *websocket.Message) error {
|
2018-07-26 14:14:23 +02:00
|
|
|
auth := Auth{
|
|
|
|
SessionID: msg.Session,
|
|
|
|
}
|
|
|
|
err := ws.db.First(&auth)
|
|
|
|
if err.Error != nil {
|
2018-06-30 16:20:54 +02:00
|
|
|
msg.Answer(msg.Subject, false)
|
|
|
|
logger.Warn("logout without login")
|
|
|
|
return nil
|
|
|
|
}
|
2018-07-26 14:14:23 +02:00
|
|
|
err = ws.db.Delete(&auth)
|
2018-06-30 16:20:54 +02:00
|
|
|
logger.Debug("done")
|
2018-07-26 14:14:23 +02:00
|
|
|
msg.Answer(msg.Subject, err.Error == nil)
|
|
|
|
return err.Error
|
2018-06-30 16:20:54 +02:00
|
|
|
}
|