deprecated_overflow_gateway.../server/server_handlers.go
2017-09-20 12:56:06 +09:00

86 lines
2.5 KiB
Go

package server
import (
"context"
"fmt"
"time"
"git.loafle.net/commons_go/config"
"git.loafle.net/overflow/overflow_gateway_probe/conf"
jwt "github.com/dgrijalva/jwt-go"
"github.com/valyala/fasthttp"
ogw "git.loafle.net/overflow/overflow_gateway_websocket"
)
var ofSigningKey []byte
func newServerHandler(ctx context.Context) ogw.ServerHandler {
h := &serverHandlers{
ctx: ctx,
}
h.HandshakeTimeout = conf.Config.Websocket.HandshakeTimeout * time.Second
h.ReadBufferSize = conf.Config.Websocket.ReadBufferSize
h.WriteBufferSize = conf.Config.Websocket.WriteBufferSize
h.EnableCompression = conf.Config.Websocket.EnableCompression
return h
}
type serverHandlers struct {
ogw.ServerHandlers
ctx context.Context
cfg config.Configurator
}
func (h *serverHandlers) OnConnection(ctx *fasthttp.RequestCtx) bool {
return true
}
func (h *serverHandlers) OnConnected(soc ogw.Socket) {
// tokenString := string(soc.Conn().Headers().Cookie("AuthToken"))
tokenString := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJvdmVyRmxvdyIsImlhdCI6MTUwNDU5NTExOSwiZXhwIjoxNTM2MTMxMTE5LCJhdWQiOiJ3d3cub3ZlcmZsb3cuY2xvdWQiLCJzdWIiOiJvdmVyZmxvd0Bsb2FmbGUuY29tIn0.-WQi3OykPlJ9x8RcZGhWXEtGw4GhU6wmyJ_AWh2rMeUatQylfPzvmum2Xfp6pwKLMmcP76XoDPNyq06i7RKWNQ"
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return ofSigningKey, nil
})
path := soc.Path()
var uid string
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
uid = claims["sub"].(string)
} else {
fmt.Println(err)
return
}
AddSocket(path, uid, soc)
}
func (h *serverHandlers) OnDisconnected(soc ogw.Socket) {
path := soc.Path()
RemoveSocket(path, soc)
}
func (h *serverHandlers) OnCheckOrigin(ctx *fasthttp.RequestCtx) bool {
if origin := string(ctx.Request.Header.Peek("Origin")); origin != "" {
ctx.Response.Header.Set("Access-Control-Allow-Origin", origin)
if string(ctx.Method()) == "OPTIONS" && string(ctx.Request.Header.Peek("Access-Control-Request-Method")) != "" {
ctx.Response.Header.Set("Access-Control-Allow-Headers", "Content-Type, Accept")
ctx.Response.Header.Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE")
}
}
return true
}
func (h *serverHandlers) OnError(ctx *fasthttp.RequestCtx, status int, reason error) {
}