Skip to content

Commit

Permalink
auth 用のエンドポイントを追加しました (#2)
Browse files Browse the repository at this point in the history
* feature: auth 用のエンドポイントを追加しました

* fix: checkout を追加した

* fix: これでどうですか??
  • Loading branch information
kei01234kei authored Nov 10, 2023
1 parent c397749 commit 3fddd03
Show file tree
Hide file tree
Showing 5 changed files with 133 additions and 9 deletions.
29 changes: 20 additions & 9 deletions .github/workflows/reviewdog.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,26 @@ name: reviewdog
on: [pull_request]

jobs:
reviewdog:
name: reviewdog
staticcheck:
name: runner / staticcheck
runs-on: ubuntu-latest
steps:
- uses: reviewdog/action-setup@v1
# checkout code
- uses: actions/checkout@v4

# If you want to use the specific version of Go,
# you need actions/setup-go@v4 action.
- uses: actions/setup-go@v4
with:
go-version: "1.21"

# run staticcheck
- uses: reviewdog/action-staticcheck@v1
with:
reviewdog_version: latest # Optional. [latest,nightly,v.X.Y.Z]
- name: Run reviewdog
env:
REVIEWDOG_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
reviewdog -reporter=github-pr-review -runners=golint,govet
github_token: ${{ secrets.github_token }}
# Change reviewdog reporter if you need [github-pr-check,github-check,github-pr-review].
reporter: github-pr-review
# Report all results.
filter_mode: diff_context
# Exit with 1 when it find at least one finding.
fail_on_error: true
25 changes: 25 additions & 0 deletions infrastructure/firebase/firebase.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package firebase

import (
"context"
"log"
"os"

firebase "firebase.google.com/go"
"google.golang.org/api/option"
)

var firebaseApp *firebase.App

func init() {
opt := option.WithCredentialsJSON([]byte(os.Getenv("FIREBASE_KEYFILE_JSON")))
var err error
firebaseApp, err = firebase.NewApp(context.Background(), nil, opt)
if err != nil {
log.Fatalf("firebase app の初期化に失敗しました: %v", err)
}
}

func GetFirebaseApp() *firebase.App {
return firebaseApp
}
24 changes: 24 additions & 0 deletions lib/library.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package lib

import (
"net/http"
"strings"

"golang.org/x/xerrors"
)

func GetAuthorizationBarerTokenFromHeader(header http.Header) (string, error) {
authHeader := header.Get("Authorization")
if authHeader == "" {
return "", xerrors.Errorf("Authorization ヘッダーが設定されていません。")
}

splitToken := strings.Split(authHeader, "Bearer ")
if len(splitToken) != 2 {
return "", xerrors.Errorf("token の形式が不正です。")
}

barerToken := splitToken[1]

return barerToken, nil
}
18 changes: 18 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (

"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"

Middleware "github.com/recordex/backend/middleware"
)

func main() {
Expand All @@ -15,8 +17,20 @@ func main() {
e.Use(middleware.Logger())
e.Use(middleware.Recover())

// CORSのミドルウェアを全許可の設定で追加
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*"},
AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},
AllowHeaders: []string{"*"},
AllowCredentials: true,
}))

auth := e.Group("")
auth.Use(Middleware.FirebaseAuth())

// Routes
e.GET("/health", health)
auth.GET("/auth", authorization)

// Start server
e.Logger.Fatal(e.Start(":1323"))
Expand All @@ -26,3 +40,7 @@ func main() {
func health(c echo.Context) error {
return c.String(http.StatusOK, "Healthy.")
}

func authorization(c echo.Context) error {
return c.String(http.StatusOK, "Authorized.")
}
46 changes: 46 additions & 0 deletions middleware/jwt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package middleware

import (
"fmt"
"log"
"net/http"

"github.com/labstack/echo/v4"

FirebaseInfrastructure "github.com/recordex/backend/infrastructure/firebase"
"github.com/recordex/backend/lib"
)

func FirebaseAuth() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
ctx := c.Request().Context()
firebaseApp := FirebaseInfrastructure.GetFirebaseApp()
authClient, err := firebaseApp.Auth(ctx)
if err != nil {
fmt.Println("firebaseApp.Auth(ctx) でエラーが発生しました。")
return c.JSON(http.StatusInternalServerError, map[string]string{
"message": err.Error(),
})
}

barerToken, err := lib.GetAuthorizationBarerTokenFromHeader(c.Request().Header)
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{
"message": err.Error(),
})
}

token, err := authClient.VerifyIDToken(ctx, barerToken)
if err != nil {
return c.JSON(http.StatusUnauthorized, map[string]string{
"message": err.Error(),
})
}

log.Printf("idToken の検証に成功しました。uid -> %s", token.UID)
c.Set("userId", token.UID)
return next(c)
}
}
}

0 comments on commit 3fddd03

Please sign in to comment.