Feat: add preshared key check
This commit is contained in:
@@ -106,7 +106,8 @@ var serveCmd = &cobra.Command{
|
||||
|
||||
authGroup := backend.NewGroup("/auth")
|
||||
authGroup.POST("/login", auths.PostLogin)
|
||||
authGroup.POST("/gen-login-url", auths.PostGenLoginUrl)
|
||||
authGroup.POST("/gen-login-url",
|
||||
midHandlers.CheckPresharedKey(auths.PostGenLoginUrl))
|
||||
|
||||
if viper.GetBool("swagger") {
|
||||
backend.GET("/swagger/*any",
|
||||
@@ -127,6 +128,8 @@ func init() {
|
||||
String("external-url", "http://localhost:8080", "External url for login")
|
||||
serveCmd.Flags().
|
||||
String("cors-origin", "", "CORS origin")
|
||||
serveCmd.Flags().
|
||||
String("preshared-key", "poop", "Preshared key for Discord Bot")
|
||||
|
||||
serveCmd.Flags().
|
||||
Int64("access-token-timeout", 300, "Timeout of Access Token JWT")
|
||||
|
||||
32
middlewares/checkPresharedKey.go
Normal file
32
middlewares/checkPresharedKey.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"github.com/uptrace/bunrouter"
|
||||
)
|
||||
|
||||
func (self *Handlers) CheckPresharedKey(
|
||||
next bunrouter.HandlerFunc,
|
||||
) bunrouter.HandlerFunc {
|
||||
return func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||
authHeader := strings.Split(req.Header.Get("Authorization"), " ")
|
||||
if len(authHeader) != 2 || authHeader[0] != "Bearer" {
|
||||
return HTTPError{
|
||||
StatusCode: http.StatusUnauthorized,
|
||||
Message: "missing preshared key",
|
||||
}
|
||||
}
|
||||
|
||||
if authHeader[1] != viper.GetString("preshared-key") {
|
||||
return HTTPError{
|
||||
StatusCode: http.StatusUnauthorized,
|
||||
Message: "preshared key mismatched",
|
||||
}
|
||||
}
|
||||
|
||||
return next(w, req)
|
||||
}
|
||||
}
|
||||
@@ -21,9 +21,22 @@ type loginPayload struct {
|
||||
func Test_01_Login(t *testing.T) {
|
||||
client = resty.New()
|
||||
|
||||
t.Run("check preshared key failed", func(t *testing.T) {
|
||||
resp, err := client.R().
|
||||
SetBody(`{"userId": "testuser1"}`).
|
||||
Post("http://localhost:8080/auth/gen-login-url")
|
||||
if err != nil {
|
||||
t.Fatal("request failed")
|
||||
}
|
||||
if resp.StatusCode() != http.StatusUnauthorized {
|
||||
t.Fatal("preshared key check should failed")
|
||||
}
|
||||
})
|
||||
|
||||
var payload genLoginUrlPayload
|
||||
resp, err := client.R().
|
||||
SetBody(`{"userId": "testuser1"}`).
|
||||
SetAuthToken("poop").
|
||||
SetResult(&payload).
|
||||
Post("http://localhost:8080/auth/gen-login-url")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user