I’m trying to build a two factor authentication in golang by gorilla/websocket
step1:
enter username and password
step2:
when server has checked the user and passed first auth, server would send email or sms to client and browser would redirect to a page let client enter the code
I watched tutorial on the web, the most common tutorial is like
// /handler/websocket.go
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func WsPing(ctx *gin.Context) {
ws, err := upGrader.Upgrade(ctx.Writer, ctx.Request, nil)
if err != nil {
return
}
defer ws.Close()
for {
mt, message, err := ws.ReadMessage()
fmt.Println(string(message))
if err != nil {
break
}
if string(message) == "ping" {
message = []byte("pong")
} else {
ws.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintln("got it : "+string(message))))
}
err = ws.WriteMessage(mt, message)
if err != nil {
break
}
}
}
// /router/router.go
var (
mongoClient = db.StartMongoDB()
userRepository repository.UserRepository = repository.NewUserRepository(mongoClient)
userService service.UserService = service.NewUserService(userRepository)
userHandler handler.UserHandler = handler.NewUserHandler(userService)
)
func StartGinRouter() *gin.Engine {
r := gin.Default()
r.GET("/ping", handler.WsPing)
userRoute := r.Group("/user")
{
userRoute.POST("/login", userHandler.OneAuth)
}
return r
}
But the feature I need is that when userHandler.OneAuth was implemented then socket would send a signal to frontend let the page redirect automatically.
According to the code above, I couldn't create a connection pool and import it into userHandler.OneAuth when the handler was triggered and implement the code below after server side sent message to client
err = ws.WriteMessage(mt, message)
if err != nil {
break
}
How can I achieve this goal?