This repository has been archived by the owner on Dec 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
feat: 認証機構 #23
Merged
Merged
feat: 認証機構 #23
Changes from 22 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
4f29712
feat: move model to server/models
Daaaai0809 3ccf6e7
feat: add auth funcs
Daaaai0809 58f81e6
feat: Implemented OAuth Sys
Daaaai0809 db79708
feat: create authentication mechanism
Daaaai0809 7236b22
feat: move authorization to gateway
Daaaai0809 2ffbfb7
feat: add gen-secret
Daaaai0809 d4bc03c
feat: add group
Daaaai0809 6a819c4
feat: delete not used funcs + add envs for github oauth
Daaaai0809 df2ee54
feat: change status to unauthorized
Daaaai0809 e36205a
feat: add cookie settings + fix errors
Daaaai0809 8058fd6
feat: add route group 'auth'
Daaaai0809 31be3ae
feat: modify review points
Daaaai0809 2c7d816
feat: modified reviewed points + add ImageURL column for users
Daaaai0809 b51e647
feat: undo gateway
Daaaai0809 c6222e9
feat: modified review points
Daaaai0809 301eb2b
feat: rename Auth* to OAuth*
Daaaai0809 cdaf67f
feat: rename to GithubOAuthInteractor
Daaaai0809 42a02b5
feat: modified oauthHandler struct
Daaaai0809 946f415
feat: replace to UPPER_SNAKE
Daaaai0809 b7e5350
feat: removed secure, SameSite attr
Daaaai0809 371020f
feat: fix any bugs
Daaaai0809 89de572
feat: fix typo + change token expire for 1week
Daaaai0809 cd34c52
feat: typoしましたすみません
Daaaai0809 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,3 +2,12 @@ MYSQL_ROOT_PASSWORD="test-root-pass" | |
MYSQL_DATABASE="test-db" | ||
MYSQL_USER="test-taro" | ||
MYSQL_PASSWORD="test-pass" | ||
|
||
GITHUB_CLIENT_ID="" | ||
GITHUB_CLIENT_SECRET="" | ||
|
||
JWT_SECRET="test-jwt-secret" | ||
|
||
ENV="development" | ||
# ENV="prod" | ||
FRONT_CALLBACK_URL="http://localhost/ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. FRONT_CALLBACK_URL="http://localhost/" |
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
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
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
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
package gateway | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"os" | ||
"time" | ||
|
||
jwt "github.com/dgrijalva/jwt-go" | ||
"github.com/labstack/echo/v4" | ||
"github.com/saitamau-maximum/meline/usecase" | ||
) | ||
|
||
type AuthGateway struct { | ||
userInteractor usecase.IUserInteractor | ||
} | ||
|
||
func NewAuthGateway(userInteractor usecase.IUserInteractor) *AuthGateway { | ||
return &AuthGateway{ | ||
userInteractor: userInteractor, | ||
} | ||
} | ||
|
||
func (h *AuthGateway) Auth(next echo.HandlerFunc) echo.HandlerFunc { | ||
return func(c echo.Context) error { | ||
ctx := c.Request().Context() | ||
|
||
// Get Access Token | ||
cookie, err := c.Cookie("access_token") | ||
if err != nil { | ||
return c.JSON(http.StatusUnauthorized, err) | ||
} | ||
|
||
token, err := jwt.Parse(cookie.Value, func(token *jwt.Token) (interface{}, error) { | ||
if token.Method.Alg() != "HS256" { | ||
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) | ||
} | ||
|
||
jwtSecret := os.Getenv("JWT_SECRET") | ||
if jwtSecret == "" { | ||
os.Exit(1) | ||
} | ||
|
||
return []byte(jwtSecret), nil | ||
}) | ||
if err != nil { | ||
return c.JSON(http.StatusUnauthorized, err) | ||
} | ||
|
||
claims, ok := token.Claims.(jwt.MapClaims) | ||
if !ok || !token.Valid { | ||
return c.JSON(http.StatusUnauthorized, err) | ||
} | ||
|
||
// Get User | ||
userId := claims["user_id"].(float64) | ||
|
||
user, err := h.userInteractor.GetUserByID(ctx, uint64(userId)) | ||
if err != nil { | ||
return c.JSON(http.StatusUnauthorized, err) | ||
} | ||
|
||
c.Set("user", user) | ||
|
||
exp := claims["exp"].(float64) | ||
if int64(exp) < time.Now().Unix() { | ||
return c.JSON(http.StatusForbidden, err) | ||
} | ||
|
||
return next(c) | ||
} | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
package handler | ||
|
||
import ( | ||
"database/sql" | ||
"log" | ||
"net/http" | ||
"os" | ||
"time" | ||
|
||
"github.com/labstack/echo/v4" | ||
"github.com/saitamau-maximum/meline/usecase" | ||
) | ||
|
||
const ( | ||
STATE_LENGTH = 32 | ||
) | ||
|
||
var ( | ||
isDev = os.Getenv("ENV") == "dev" | ||
) | ||
|
||
type OAuthHandler struct { | ||
githubOAuthInteractor usecase.IGithubOAuthInteractor | ||
userInteractor usecase.IUserInteractor | ||
} | ||
|
||
func NewOAuthHandler(authGroup *echo.Group, githubOAuthInteractor usecase.IGithubOAuthInteractor, userInteractor usecase.IUserInteractor) { | ||
oAuthHandler := &OAuthHandler{ | ||
githubOAuthInteractor: githubOAuthInteractor, | ||
userInteractor: userInteractor, | ||
} | ||
|
||
authGroup.GET("/login", oAuthHandler.Login) | ||
authGroup.GET("/callback", oAuthHandler.CallBack) | ||
} | ||
|
||
func (h *OAuthHandler) Login(c echo.Context) error { | ||
ctx := c.Request().Context() | ||
|
||
state := h.githubOAuthInteractor.GenerateState(STATE_LENGTH) | ||
|
||
cookie := new(http.Cookie) | ||
cookie.Name = "state" | ||
cookie.Value = state | ||
cookie.Path = "/" | ||
cookie.HttpOnly = true | ||
cookie.SameSite = http.SameSiteLaxMode | ||
cookie.Secure = !isDev | ||
|
||
c.SetCookie(cookie) | ||
|
||
url := h.githubOAuthInteractor.GetGithubOAuthURL(ctx, state) | ||
|
||
return c.Redirect(http.StatusTemporaryRedirect, url) | ||
} | ||
|
||
func (h *OAuthHandler) CallBack(c echo.Context) error { | ||
ctx := c.Request().Context() | ||
|
||
// Check State | ||
state := c.QueryParam("state") | ||
cookie, err := c.Cookie("state") | ||
if err != nil { | ||
log.Default().Println(err) | ||
return c.JSON(http.StatusUnauthorized, err) | ||
} | ||
|
||
if state != cookie.Value { | ||
log.Default().Println(err) | ||
return c.JSON(http.StatusUnauthorized, err) | ||
} | ||
|
||
code := c.QueryParam("code") | ||
gitToken, err := h.githubOAuthInteractor.GetGithubOAuthToken(ctx, code) | ||
if err != nil { | ||
log.Default().Println(err) | ||
return c.JSON(http.StatusUnauthorized, err) | ||
} | ||
|
||
userRes, err := h.githubOAuthInteractor.GetGithubUser(ctx, gitToken) | ||
if err != nil { | ||
log.Default().Println(err) | ||
return c.JSON(http.StatusUnauthorized, err) | ||
} | ||
|
||
user, err := h.userInteractor.GetUserByGithubID(ctx, userRes.OAuthUserID) | ||
if err != nil { | ||
if (err == sql.ErrNoRows) { | ||
user, err = h.userInteractor.CreateUser(ctx, userRes.OAuthUserID, userRes.Name, userRes.ImageURL) | ||
if err != nil { | ||
log.Default().Println(err) | ||
return c.JSON(http.StatusInternalServerError, err) | ||
} | ||
} else { | ||
log.Default().Println(err) | ||
return c.JSON(http.StatusInternalServerError, err) | ||
} | ||
} | ||
|
||
// Set Access Token | ||
token, err := h.githubOAuthInteractor.CreateAccessToken(ctx, user) | ||
if err != nil { | ||
log.Default().Println(err) | ||
return c.JSON(http.StatusInternalServerError, err) | ||
} | ||
|
||
newCookie := new(http.Cookie) | ||
newCookie.Name = "access_token" | ||
newCookie.Value = token | ||
newCookie.Path = "/" | ||
newCookie.HttpOnly = true | ||
newCookie.SameSite = http.SameSiteLaxMode | ||
newCookie.Secure = !isDev | ||
newCookie.Expires = time.Now().Add(3 * time.Hour) | ||
|
||
c.SetCookie(newCookie) | ||
|
||
return c.Redirect(http.StatusTemporaryRedirect, os.Getenv("FRONT_CALLBACK_URL")) | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
package entity | ||
|
||
type OAuthUserResponse struct { | ||
OAuthUserID string `json:"user_id"` | ||
Name string `json:"name"` | ||
ImageURL string `json:"image_url"` | ||
} |
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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
prod -> production