Created
March 29, 2020 09:42
-
-
Save NimaGhaedsharafi/fb68c1659f6aad8120d787aa3a5eb90c to your computer and use it in GitHub Desktop.
Firebase Middleware for Echo framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package auth | |
import ( | |
"context" | |
firebase "firebase.google.com/go" | |
"github.com/labstack/echo/v4" | |
"google.golang.org/api/option" | |
"net/http" | |
"strings" | |
) | |
func Client() *firebase.App { | |
opt := option.WithCredentialsFile("secure/firebase.json") | |
app, err := firebase.NewApp(context.Background(), nil, opt) | |
if err != nil { | |
return nil | |
} | |
return app | |
} | |
func Auth() echo.MiddlewareFunc { | |
return auth | |
} | |
func auth(next echo.HandlerFunc) echo.HandlerFunc { | |
return func(c echo.Context) error { | |
fb, err := Client().Auth(context.Background()) | |
if err != nil { | |
return nil | |
} | |
auth := c.Request().Header.Get("Authorization") | |
idToken := strings.Replace(auth, "Bearer ", "", 1) | |
token, err := fb.VerifyIDToken(context.Background(), idToken) | |
if err != nil { | |
return c.NoContent(http.StatusForbidden) | |
} | |
c.Set("token", token) | |
return next(c) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment