diff --git a/controllers/auth.controller.go b/controllers/auth.controller.go index 447a4be..fcc1df5 100644 --- a/controllers/auth.controller.go +++ b/controllers/auth.controller.go @@ -79,68 +79,6 @@ func LogoutUser(ctx *gin.Context) { ctx.JSON(http.StatusOK, gin.H{"status": "success"}) } -func GoogleOAuth(ctx *gin.Context) { - code := ctx.Query("code") - var pathUrl string = "/" - - if ctx.Query("state") != "" { - pathUrl = ctx.Query("state") - } - - if code == "" { - ctx.JSON(http.StatusUnauthorized, gin.H{"status": "fail", "message": "Authorization code not provided!"}) - return - } - - tokenRes, err := utils.GetGoogleOauthToken(code) - - if err != nil { - ctx.JSON(http.StatusBadGateway, gin.H{"status": "fail", "message": err.Error()}) - return - } - - google_user, err := utils.GetGoogleUser(tokenRes.Access_token, tokenRes.Id_token) - - if err != nil { - ctx.JSON(http.StatusBadGateway, gin.H{"status": "fail", "message": err.Error()}) - return - } - - now := time.Now() - email := strings.ToLower(google_user.Email) - - user_data := models.User{ - Name: google_user.Name, - Email: email, - Password: "", - Photo: google_user.Picture, - Provider: "Google", - Role: "user", - Verified: true, - CreatedAt: now, - UpdatedAt: now, - } - - if initializers.DB.Model(&user_data).Where("email = ?", email).Updates(&user_data).RowsAffected == 0 { - initializers.DB.Create(&user_data) - } - - var user models.User - initializers.DB.First(&user, "email = ?", email) - - config, _ := initializers.LoadConfig(".") - - token, err := utils.GenerateToken(config.TokenExpiresIn, user.ID.String(), config.JWTTokenSecret) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"status": "fail", "message": err.Error()}) - return - } - - ctx.SetCookie("token", token, config.TokenMaxAge*60, "/", "localhost", false, true) - - ctx.Redirect(http.StatusTemporaryRedirect, fmt.Sprint(config.FrontEndOrigin, pathUrl)) -} - func GitHubOAuth(ctx *gin.Context) { code := ctx.Query("code") var pathUrl string = "/" diff --git a/example.env b/example.env index 4f8b6e1..24e4156 100644 --- a/example.env +++ b/example.env @@ -4,10 +4,6 @@ JWT_SECRET=my_ultra_secure_secret TOKEN_EXPIRED_IN=60m TOKEN_MAXAGE=60 -GOOGLE_OAUTH_CLIENT_ID= -GOOGLE_OAUTH_CLIENT_SECRET= -GOOGLE_OAUTH_REDIRECT_URL=http://localhost:8000/api/sessions/oauth/google - GITHUB_OAUTH_CLIENT_ID= GITHUB_OAUTH_CLIENT_SECRET= GITHUB_OAUTH_REDIRECT_URL=http://localhost:8000/api/sessions/oauth/github \ No newline at end of file diff --git a/main.go b/main.go index fcbe91d..bebc2cf 100644 --- a/main.go +++ b/main.go @@ -6,18 +6,15 @@ import ( "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" + "github.com/wpcodevo/google-github-oath2-golang/controllers" "github.com/wpcodevo/google-github-oath2-golang/initializers" - "github.com/wpcodevo/google-github-oath2-golang/routes" + "github.com/wpcodevo/google-github-oath2-golang/middleware" ) var server *gin.Engine func init() { initializers.ConnectDB() - // config, err := initializers.LoadConfig(".") - // if err != nil { - // panic(err) - // } server = gin.Default() } @@ -34,9 +31,13 @@ func main() { ctx.JSON(http.StatusOK, gin.H{"status": "success", "message": "Implement Google OAuth2 in Golang"}) }) - routes.AuthRoute(router) - routes.UserRoute(router) - routes.SessionRoute(router) + auth_router := router.Group("/auth") + auth_router.POST("/register", controllers.SignUpUser) + auth_router.POST("/login", controllers.SignInUser) + auth_router.GET("/logout", middleware.DeserializeUser(), controllers.LogoutUser) + + router.GET("/sessions/oauth/github", controllers.GitHubOAuth) + router.GET("/users/me", middleware.DeserializeUser(), controllers.GetMe) router.StaticFS("/images", http.Dir("public")) server.NoRoute(func(ctx *gin.Context) { diff --git a/routes/auth.routes.go b/routes/auth.routes.go deleted file mode 100644 index 656f289..0000000 --- a/routes/auth.routes.go +++ /dev/null @@ -1,15 +0,0 @@ -package routes - -import ( - "github.com/gin-gonic/gin" - "github.com/wpcodevo/google-github-oath2-golang/controllers" - "github.com/wpcodevo/google-github-oath2-golang/middleware" -) - -func AuthRoute(rg *gin.RouterGroup) { - router := rg.Group("/auth") - - router.POST("/register", controllers.SignUpUser) - router.POST("/login", controllers.SignInUser) - router.GET("/logout", middleware.DeserializeUser(), controllers.LogoutUser) -} diff --git a/routes/session.routes.go b/routes/session.routes.go deleted file mode 100644 index 7d87ae5..0000000 --- a/routes/session.routes.go +++ /dev/null @@ -1,13 +0,0 @@ -package routes - -import ( - "github.com/gin-gonic/gin" - "github.com/wpcodevo/google-github-oath2-golang/controllers" -) - -func SessionRoute(rg *gin.RouterGroup) { - router := rg.Group("/sessions/oauth") - - router.GET("/google", controllers.GoogleOAuth) - router.GET("/github", controllers.GitHubOAuth) -} diff --git a/routes/user.routes.go b/routes/user.routes.go deleted file mode 100644 index 4249d39..0000000 --- a/routes/user.routes.go +++ /dev/null @@ -1,14 +0,0 @@ -package routes - -import ( - "github.com/gin-gonic/gin" - "github.com/wpcodevo/google-github-oath2-golang/controllers" - "github.com/wpcodevo/google-github-oath2-golang/middleware" -) - -func UserRoute(rg *gin.RouterGroup) { - - router := rg.Group("users") - router.Use(middleware.DeserializeUser()) - router.GET("/me", controllers.GetMe) -} diff --git a/utils/githubOAuth.go b/utils/githubOAuth.go index b3ad41f..2eb303d 100644 --- a/utils/githubOAuth.go +++ b/utils/githubOAuth.go @@ -5,7 +5,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "time" @@ -54,12 +54,13 @@ func GetGitHubOauthToken(code string) (*GitHubOauthToken, error) { return nil, errors.New("could not retrieve token") } - resBody, err := ioutil.ReadAll(res.Body) + var resBody bytes.Buffer + _, err = io.Copy(&resBody, res.Body) if err != nil { return nil, err } - parsedQuery, err := url.ParseQuery(string(resBody)) + parsedQuery, err := url.ParseQuery(resBody.String()) if err != nil { return nil, err } @@ -94,14 +95,15 @@ func GetGitHubUser(access_token string) (*GitHubUserResult, error) { return nil, errors.New("could not retrieve user") } - resBody, err := ioutil.ReadAll(res.Body) + var resBody bytes.Buffer + _, err = io.Copy(&resBody, res.Body) if err != nil { return nil, err } var GitHubUserRes map[string]interface{} - if err := json.Unmarshal(resBody, &GitHubUserRes); err != nil { + if err := json.Unmarshal(resBody.Bytes(), &GitHubUserRes); err != nil { return nil, err } diff --git a/utils/googleOAuth.go b/utils/googleOAuth.go deleted file mode 100644 index 73c8b60..0000000 --- a/utils/googleOAuth.go +++ /dev/null @@ -1,128 +0,0 @@ -package utils - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "time" - - "github.com/wpcodevo/google-github-oath2-golang/initializers" -) - -type GoogleOauthToken struct { - Access_token string - Id_token string -} - -type GoogleUserResult struct { - Id string - Email string - Verified_email bool - Name string - Given_name string - Family_name string - Picture string - Locale string -} - -func GetGoogleOauthToken(code string) (*GoogleOauthToken, error) { - const rootURl = "https://oauth2.googleapis.com/token" - - config, _ := initializers.LoadConfig(".") - values := url.Values{} - values.Add("grant_type", "authorization_code") - values.Add("code", code) - values.Add("client_id", config.GoogleClientID) - values.Add("client_secret", config.GoogleClientSecret) - values.Add("redirect_uri", config.GoogleOAuthRedirectUrl) - - query := values.Encode() - - req, err := http.NewRequest("POST", rootURl, bytes.NewBufferString(query)) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - client := http.Client{ - Timeout: time.Second * 30, - } - - res, err := client.Do(req) - if err != nil { - return nil, err - } - - if res.StatusCode != http.StatusOK { - return nil, errors.New("could not retrieve token") - } - - resBody, err := ioutil.ReadAll(res.Body) - if err != nil { - return nil, err - } - - var GoogleOauthTokenRes map[string]interface{} - - if err := json.Unmarshal(resBody, &GoogleOauthTokenRes); err != nil { - return nil, err - } - - tokenBody := &GoogleOauthToken{ - Access_token: GoogleOauthTokenRes["access_token"].(string), - Id_token: GoogleOauthTokenRes["id_token"].(string), - } - - return tokenBody, nil -} - -func GetGoogleUser(access_token string, id_token string) (*GoogleUserResult, error) { - rootUrl := fmt.Sprintf("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=%s", access_token) - - req, err := http.NewRequest("GET", rootUrl, nil) - if err != nil { - return nil, err - } - - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", id_token)) - - client := http.Client{ - Timeout: time.Second * 30, - } - - res, err := client.Do(req) - if err != nil { - return nil, err - } - - if res.StatusCode != http.StatusOK { - return nil, errors.New("could not retrieve user") - } - - resBody, err := ioutil.ReadAll(res.Body) - if err != nil { - return nil, err - } - - var GoogleUserRes map[string]interface{} - - if err := json.Unmarshal(resBody, &GoogleUserRes); err != nil { - return nil, err - } - - userBody := &GoogleUserResult{ - Id: GoogleUserRes["id"].(string), - Email: GoogleUserRes["email"].(string), - Verified_email: GoogleUserRes["verified_email"].(bool), - Name: GoogleUserRes["name"].(string), - Given_name: GoogleUserRes["given_name"].(string), - Picture: GoogleUserRes["picture"].(string), - Locale: GoogleUserRes["locale"].(string), - } - - return userBody, nil -}