Browse Source

init

master
tangmingyou 4 years ago
commit
073ecf4fd4
  1. 28
      .gitignore
  2. 60
      cmd/main.go
  3. 7
      etc/config.toml
  4. 0
      etc/config.yaml
  5. 32
      go.mod
  6. 98
      go.sum
  7. 61
      internal/game/card.go
  8. 12
      internal/model/message.go
  9. 96
      internal/server/auth.go
  10. 21
      internal/server/server.go
  11. 24
      internal/server/session.go
  12. 80
      internal/server/ws.go
  13. 12
      internal/service/auth.go
  14. 45
      internal/service/service.go
  15. 12
      internal/subject/net_account.go
  16. 25
      internal/subject/net_client.go
  17. 6
      internal/subject/player.go
  18. 117
      tool/security/aes.go
  19. 7
      tool/security/rsa.go

28
.gitignore vendored

@ -0,0 +1,28 @@
# IDE ignore
.idea/
*.ipr
*.iml
*.iws
.vscode/
# temp ignore
*.log
*.cache
*.diff
*.exe
*.exe~
*.patch
*.tmp
*.swp
# system ignore
.DS_Store
Thumbs.db
# build
/cmd/comet/comet
/cmd/logic/logic
/cmd/job/job
/target
/configs
/dist

60
cmd/main.go

@ -0,0 +1,60 @@
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/json"
"flag"
"fmt"
"texas-poker-bk/internal/model"
"time"
)
var confPath string
func init() {
flag.StringVar(&confPath, "conf", "comet-example.toml", "default config path.")
}
func main() {
// testRsa()
}
func testToml() {
}
func testRsa() {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
publicKey := privateKey.PublicKey
encryptBytes, err := rsa.EncryptOAEP(
sha256.New(),
rand.Reader,
&publicKey,
[]byte("super secret message"),
nil,
)
fmt.Println(publicKey)
fmt.Println(encryptBytes)
}
func testMsgCodec() {
identity := &model.Identity{Token: "12312312asahjasd"}
bytes, _ := json.Marshal(identity)
// msg: int32:route:msg
msg := &model.Message{T: "identity", Ms: time.Now().UnixMilli(), D: bytes}
b, _ := json.Marshal(msg)
fmt.Println(msg)
fmt.Println(b)
}
func codecMsg(t string, msg any) []byte {
return nil
}

7
etc/config.toml

@ -0,0 +1,7 @@
[auth]
ignoreUrl = [
"/ws",
"/auth/captcha"
]

0
etc/config.yaml

32
go.mod

@ -0,0 +1,32 @@
module texas-poker-bk
go 1.19
require (
github.com/BurntSushi/toml v1.2.1 // indirect
github.com/dchest/captcha v1.0.0 // indirect
github.com/gin-contrib/sessions v0.0.5 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.8.2 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-playground/validator/v10 v10.11.1 // indirect
github.com/goccy/go-json v0.9.11 // indirect
github.com/gorilla/context v1.1.1 // indirect
github.com/gorilla/securecookie v1.1.1 // indirect
github.com/gorilla/sessions v1.2.1 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/ugorji/go/codec v1.2.7 // indirect
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 // indirect
golang.org/x/net v0.4.0 // indirect
golang.org/x/sys v0.3.0 // indirect
golang.org/x/text v0.5.0 // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

98
go.sum

@ -0,0 +1,98 @@
github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak=
github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dchest/captcha v1.0.0 h1:vw+bm/qMFvTgcjQlYVTuQBJkarm5R0YSsDKhm1HZI2o=
github.com/dchest/captcha v1.0.0/go.mod h1:7zoElIawLp7GUMLcj54K9kbw+jEyvz2K0FDdRRYhvWo=
github.com/gin-contrib/sessions v0.0.5 h1:CATtfHmLMQrMNpJRgzjWXD7worTh7g7ritsQfmF+0jE=
github.com/gin-contrib/sessions v0.0.5/go.mod h1:vYAuaUPqie3WUSsft6HUlCjlwwoJQs97miaG2+7neKY=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.8.2 h1:UzKToD9/PoFj/V4rvlKqTRKnQYyz8Sc1MJlv4JHPtvY=
github.com/gin-gonic/gin v1.8.2/go.mod h1:qw5AYuDrzRTnhvusDsrov+fDIxp9Dleuu12h8nfB398=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU=
github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs=
github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho=
github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA=
github.com/go-playground/validator/v10 v10.11.1 h1:prmOlTVv+YjZjmRmNSF3VmspqJIxJWXmqUsHwfTRRkQ=
github.com/go-playground/validator/v10 v10.11.1/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU=
github.com/goccy/go-json v0.9.11 h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk=
github.com/goccy/go-json v0.9.11/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8=
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI=
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU=
github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M=
github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=
github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 h1:0es+/5331RGQPcXlMfP+WrnIIS6dNnNRe0WB02W0F4M=
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.4.0 h1:Q5QPcMlvfxFTAPV0+07Xz/MpK9NTXu2VDUuy0FeMfaU=
golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM=
golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

61
internal/game/card.go

@ -0,0 +1,61 @@
package card
type Card struct {
Dot PokerDot // 点数
Suit PokerSuit // 花色
}
// Compare 比较点数和花色
// return (-n: c < c2); (0: c == c2); (+n: c > c2)
func (c *Card) Compare(c2 *Card) int {
dot, suit := int(c.Dot)-int(c2.Dot), int(c.Suit)-int(c2.Suit)
return dot*10 + suit
}
// CompareWithDot 只比较点数
// return (-n: c < c2); (0: c == c2); (+n: c > c2)
func (c *Card) CompareWithDot(c2 *Card) int {
return int(c.Dot) - int(c2.Dot)
}
type PokerSuit int
func (c PokerSuit) String() string {
return colors[c]
}
// 常量在编译期就要确定值,只能将一些基本类型声明为常量
var colors = [4]string{"diamond", "club", "heart", "spade"}
const (
Diamond PokerSuit = iota // 方块
Club PokerSuit = iota // 梅花
Heart PokerSuit = iota // 红桃
Spade PokerSuit = iota // 黑桃
)
type PokerDot int
func (n PokerDot) String() string {
return pokers[n]
}
var pokers = [13]string{"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"}
const (
Poker2 PokerDot = iota
Poker3 PokerDot = iota
Poker4 PokerDot = iota
Poker5 PokerDot = iota
Poker6 PokerDot = iota
Poker7 PokerDot = iota
Poker8 PokerDot = iota
Poker9 PokerDot = iota
Poker10 PokerDot = iota
PokerJ PokerDot = iota
PokerQ PokerDot = iota
PokerK PokerDot = iota
PokerA PokerDot = iota
PokerBlackJoker PokerDot = iota
PokerRedJoker PokerDot = iota
)

12
internal/model/message.go

@ -0,0 +1,12 @@
package model
type Message struct {
T string `json:"t"` // action 时间主题
Ms int64 `json:"ms"` // 毫秒时间戳
D []byte `json:"d"` // 消息数据
}
// Identity 身份认证消息
type Identity struct {
Token string `json:"t"`
}

96
internal/server/auth.go

@ -0,0 +1,96 @@
package server
import (
"encoding/base64"
"encoding/json"
"github.com/gin-gonic/gin"
"net/http"
"texas-poker-bk/tool/security"
)
var (
SubjectKey = "auth:subject"
sc = &scEtc{} // 加密配置
)
// Subject 认证对象
type Subject struct {
Id int64 `json:"id,omitempty"` // 用户id
Name string `json:"name,omitempty"` // 用户名
Time int64 `json:"time,omitempty"` // 生成时间戳
}
type scEtc struct {
securityKey string
keyBytes []byte
}
func init() {
sc.securityKey = "9Nz3Y6DES3msAFndz4QsJAECUIFkf+KKaRa+jRnNALk="
keyBytes, err := base64.URLEncoding.DecodeString(sc.securityKey)
if err != nil {
panic(err)
}
sc.keyBytes = keyBytes
}
// SubjectAuthFilter 认证过滤器
func SubjectAuthFilter(ctx *gin.Context) {
auth := ctx.GetHeader("Authorization")
if auth == "" {
// TODO config ignore urls
//if isIgnoreUrl(ctx.Request.URL.Path) {
// return
//}
ctx.JSON(http.StatusUnauthorized, gin.H{"msg": "请登录后进行操作"})
ctx.Abort()
return
}
defer func() {
// 捕获aes解析错误
if r := recover(); r != nil {
ctx.JSON(http.StatusUnauthorized, gin.H{"msg": "认证失败,请重新登录"})
ctx.Abort()
}
}()
// TODO 这里返回 error,不然后捕获后续执行 handler 的 panic
subject := DecodeSubject(auth)
ctx.Set(SubjectKey, subject)
}
// EncodeSubject 对subject对象aesCBC加密并返回base64Std编码的 token
// subject 客户端对象
func EncodeSubject(subject *Subject) string {
bytes, err := json.Marshal(subject)
if err != nil {
panic(err)
}
encode := security.EncryptAesCBC(bytes, sc.keyBytes)
return base64.URLEncoding.EncodeToString(encode)
}
// DecodeSubject 解码并解密token返回subject对象
// auth base64Std 编码的 token
func DecodeSubject(auth string) *Subject {
bytes, err := base64.URLEncoding.DecodeString(auth)
if err != nil {
panic(err)
}
decode := security.DecryptAesCBC(bytes, sc.keyBytes)
subject := &Subject{}
err = json.Unmarshal(decode, subject)
if err != nil {
panic(err)
}
return subject
}
// GetSubject 从请求上下文中获取客户端对象, 请求经过了认证过滤器
func GetSubject(ctx *gin.Context) *Subject {
subject, exists := ctx.Get(SubjectKey)
if !exists {
return nil
}
return subject.(*Subject)
}

21
internal/server/server.go

@ -0,0 +1,21 @@
package server
import (
"github.com/gin-gonic/gin"
"texas-poker-bk/internal/service"
)
func Start() *gin.Engine {
server := gin.Default()
// websocket
server.GET("/ws", Upgrade)
auth := server.Group("/auth")
auth.GET("/captcha", service.Captcha) // 验证码
// session storage
server.Use(SessionStore("golang-tech-stack"))
return server
}

24
internal/server/session.go

@ -0,0 +1,24 @@
package server
import (
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
)
// SessionStore 中间件,处理 session
func SessionStore(keyPairs string) gin.HandlerFunc {
store := sessionConfig()
return sessions.Sessions(keyPairs, store)
}
func sessionConfig() sessions.Store {
sessionMaxAge := 3600
sessionSecret := "golang-tech-stack"
store := cookie.NewStore([]byte(sessionSecret))
store.Options(sessions.Options{
MaxAge: sessionMaxAge,
Path: "/",
})
return store
}

80
internal/server/ws.go

@ -0,0 +1,80 @@
package server
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"log"
"net/http"
"texas-poker-bk/internal/model"
"texas-poker-bk/internal/subject"
"time"
)
func Upgrade(ctx *gin.Context) {
conn, err := upgradeWs(ctx.Writer, ctx.Request)
if err != nil {
fmt.Println(err)
http.Error(ctx.Writer, "Not a websocket handshake", 400)
return
}
client := subject.NewNetClient(conn)
go handleNetClient(client)
}
func upgradeWs(resWriter http.ResponseWriter, req *http.Request) (*websocket.Conn, error) {
upgrader := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
HandshakeTimeout: 3 * time.Second,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
return upgrader.Upgrade(resWriter, req, nil)
}
// 处理新建的websocket
func handleNetClient(client *subject.NetClient) {
//defer (func() {
// client.Close("conn finish")
//})()
// TODO 1分钟后过期
for {
// 阻塞读取消息
_, bytes, err := client.Conn.ReadMessage()
if err != nil {
// 读失败
log.Println("ReadMessage", err)
client.Close("read conn err:" + err.Error())
return
}
msg := &model.Message{}
err = json.Unmarshal(bytes, msg)
if err != nil {
log.Println("反序列化json消息失败", err)
continue
}
// TODO 认证消息(return -> account msg route)
switch msg.T {
case "identify":
param := &model.Identity{}
_ = json.Unmarshal(msg.D, param)
default:
client.Close("wrong message")
}
// TODO other,timeout -> close
}
}
// handleIdentity TODO 通过 token 认证连接的身份
func handleIdentity(identity *model.Identity, client *subject.NetClient) {
}

12
internal/service/auth.go

@ -0,0 +1,12 @@
package service
import "github.com/gin-gonic/gin"
// Login 登录或注册
func Login(ctx *gin.Context) {
}
func Register() {
}

45
internal/service/service.go

@ -0,0 +1,45 @@
package service
import (
"bytes"
"github.com/dchest/captcha"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
// Captcha 获取验证码
func Captcha(ctx *gin.Context) {
l, w, h := 4, 107, 36
captchaId := captcha.NewLen(l)
session := sessions.Default(ctx)
session.Set("captcha", captchaId)
_ = session.Save()
_ = Serve(ctx.Writer, ctx.Request, captchaId, ".png", "zh", false, w, h)
}
func Serve(w http.ResponseWriter, r *http.Request, id, ext, lang string, download bool, width, height int) error {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
var content bytes.Buffer
switch ext {
case ".png":
w.Header().Set("Content-Type", "image/png")
_ = captcha.WriteImage(&content, id, width, height)
// 音频验证码
case ".wav":
w.Header().Set("Content-Type", "audio/x-wav")
_ = captcha.WriteAudio(&content, id, lang)
default:
return captcha.ErrNotFound
}
if download {
w.Header().Set("Content-Type", "application/octet-stream")
}
http.ServeContent(w, r, id+ext, time.Time{}, bytes.NewReader(content.Bytes()))
return nil
}

12
internal/subject/net_account.go

@ -0,0 +1,12 @@
package subject
// NetAccount 已认证的长连接用户
type NetAccount struct {
Id int64
UserName string
Client *NetClient
}
func NewNetAccount() {
}

25
internal/subject/net_client.go

@ -0,0 +1,25 @@
package subject
import (
"github.com/gorilla/websocket"
"log"
)
// NetClient 长连接客户端
type NetClient struct {
Id int64
Conn *websocket.Conn
}
func (c *NetClient) Close(reason string) {
err := c.Conn.Close()
if err != nil {
log.Println("Close Error", err)
}
}
func NewNetClient(conn *websocket.Conn) *NetClient {
return &NetClient{
Conn: conn,
}
}

6
internal/subject/player.go

@ -0,0 +1,6 @@
package subject
// Player 玩家: table,balance,(hand card)
type Player struct {
Account *NetAccount
}

117
tool/security/aes.go

@ -0,0 +1,117 @@
package security
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"reflect"
)
// 参考:https://www.yisu.com/zixun/696240.html
func TestAes() {
defer func() {
if r := recover(); r != nil {
fmt.Println("recover...", r.(error).Error(), reflect.TypeOf(r))
}
}()
// aesKeyStr := GetAesKey256()
aesKeyStr := "YYNLVy4qZ+WwkyG7r4kUhMfZu6g9e+" // 0uiba5DAgINl8=
fmt.Println(aesKeyStr)
key, _ := base64.StdEncoding.DecodeString(aesKeyStr)
fmt.Println(key)
text := []byte("you are my sunshine!")
encrypt := EncryptAesCBC(text, key)
fmt.Println(encrypt)
fmt.Println(base64.URLEncoding.EncodeToString(text))
result := DecryptAesCBC(encrypt, key)
fmt.Println(string(result))
}
func GetAesKey256() string {
key := getAesKey(256)
return base64.StdEncoding.EncodeToString(key)
}
func getAesKey(keySize int) []byte {
var key = make([]byte, keySize/8)
_, err := rand.Read(key)
if err != nil {
panic(err)
}
return key
}
// EncryptAesCBC
// src -> 要加密的原文
// key -> 秘钥, 和加密秘钥相同, 大小为: 8byte
func EncryptAesCBC(src, key []byte) []byte {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
blockSize := block.BlockSize()
// 对最后一个明文分组进行数据填充
src = pkcs5Padding(src, blockSize)
// 3.创建一个密码分组为链接模式的,底层使用 DES 加密的 BlockMode 接口
// 参数 iv 的长度,必须等于 b 的块尺寸
iv := make([]byte, blockSize, blockSize)
copy(iv, key)
blackMode := cipher.NewCBCEncrypter(block, iv)
// 5.加密连续的数据块
dst := make([]byte, len(src))
blackMode.CryptBlocks(dst, src)
return dst
}
// DecryptAesCBC
// src -> 要解密的密文
// key -> 秘钥, 和加密秘钥相同, 大小为: 8byte
func DecryptAesCBC(src, key []byte) []byte {
// 1. 创建并返回一个使用DES算法的cipher.Block接口
block, err := aes.NewCipher(key)
blockSize := block.BlockSize()
// 2. 判断是否创建成功
if err != nil {
panic(err)
}
// 3. 创建一个密码分组为链接模式的, 底层使用DES解密的BlockMode接口
iv := make([]byte, blockSize, blockSize)
copy(iv, key)
blockMode := cipher.NewCBCDecrypter(block, iv)
// 4. 解密数据
dst := src
blockMode.CryptBlocks(src, dst)
// 5. 去掉最后一组填充的数据
dst = pkcs5UnPadding(dst)
// 6. 返回结果
return dst
}
// PKCS5Padding 使用pks5的方式填充
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
// 1. 计算最后一个分组缺多少个字节
padding := blockSize - (len(ciphertext) % blockSize)
// 2. 创建一个大小为padding的切片, 每个字节的值为padding
padText := bytes.Repeat([]byte{byte(padding)}, padding)
// 3. 将padText添加到原始数据的后边, 将最后一个分组缺少的字节数补齐
newText := append(ciphertext, padText...)
return newText
}
// PKCS5UnPadding 删除pks5填充的尾部数据
func pkcs5UnPadding(origData []byte) []byte {
// 1. 计算数据的总长度
length := len(origData)
// 2. 根据填充的字节值得到填充的次数
number := int(origData[length-1])
// 3. 将尾部填充的number个字节去掉
return origData[:(length - number)]
}

7
tool/security/rsa.go

@ -0,0 +1,7 @@
package security
// https://mp.weixin.qq.com/s/njYAfq0yaCFD2NB6kzmveg
func aa() {
}
Loading…
Cancel
Save