netmaker/auth/google.go

137 lines
3.7 KiB
Go
Raw Normal View History

2021-10-21 02:17:31 +08:00
package auth
import (
"context"
2021-10-22 03:28:58 +08:00
"encoding/json"
2021-10-21 02:17:31 +08:00
"fmt"
2022-01-07 04:05:38 +08:00
"io"
2021-10-21 02:17:31 +08:00
"net/http"
2022-05-13 18:04:27 +08:00
"time"
2021-10-21 02:17:31 +08:00
2021-12-07 04:31:08 +08:00
"github.com/gravitl/netmaker/logger"
2021-10-22 03:28:58 +08:00
"github.com/gravitl/netmaker/logic"
2021-10-22 08:32:23 +08:00
"github.com/gravitl/netmaker/models"
2021-10-22 03:28:58 +08:00
"github.com/gravitl/netmaker/servercfg"
2021-10-21 02:17:31 +08:00
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var google_functions = map[string]interface{}{
init_provider: initGoogle,
2021-10-23 01:12:03 +08:00
get_user_info: getGoogleUserInfo,
2021-10-21 02:17:31 +08:00
handle_callback: handleGoogleCallback,
handle_login: handleGoogleLogin,
2021-10-22 03:28:58 +08:00
verify_user: verifyGoogleUser,
2021-10-21 02:17:31 +08:00
}
// == handle google authentication here ==
func initGoogle(redirectURL string, clientID string, clientSecret string) {
auth_provider = &oauth2.Config{
RedirectURL: redirectURL,
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: []string{"https://www.googleapis.com/auth/userinfo.email"},
Endpoint: google.Endpoint,
}
}
func handleGoogleLogin(w http.ResponseWriter, r *http.Request) {
2022-09-14 03:25:56 +08:00
var oauth_state_string = logic.RandomString(user_signin_length)
if auth_provider == nil {
handleOauthNotConfigured(w)
2021-10-22 21:47:29 +08:00
return
}
if err := logic.SetState(oauth_state_string); err != nil {
handleOauthNotConfigured(w)
return
}
2021-10-22 08:32:23 +08:00
var url = auth_provider.AuthCodeURL(oauth_state_string)
2021-10-21 02:17:31 +08:00
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func handleGoogleCallback(w http.ResponseWriter, r *http.Request) {
2022-09-14 03:25:56 +08:00
var rState, rCode = getStateAndCode(r)
var content, err = getGoogleUserInfo(rState, rCode)
2021-10-21 02:17:31 +08:00
if err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(1, "error when getting user info from google:", err.Error())
handleOauthNotConfigured(w)
2021-10-21 02:17:31 +08:00
return
}
2021-10-22 08:32:23 +08:00
_, err = logic.GetUser(content.Email)
if err != nil { // user must not exists, so try to make one
if err = addUser(content.Email); err != nil {
return
}
}
user, err := logic.GetUser(content.Email)
if err != nil {
handleOauthUserNotFound(w)
return
}
if !(user.IsSuperAdmin || user.IsAdmin) {
handleOauthUserNotAllowed(w)
return
}
2021-10-22 08:32:23 +08:00
var newPass, fetchErr = fetchPassValue("")
if fetchErr != nil {
return
}
// send a netmaker jwt token
var authRequest = models.UserAuthParams{
UserName: content.Email,
Password: newPass,
}
var jwt, jwtErr = logic.VerifyAuthRequest(authRequest)
if jwtErr != nil {
2021-12-07 04:31:08 +08:00
logger.Log(1, "could not parse jwt for user", authRequest.UserName)
2021-10-22 08:32:23 +08:00
return
}
2021-12-07 04:31:08 +08:00
logger.Log(1, "completed google OAuth sigin in for", content.Email)
2022-09-15 22:23:19 +08:00
http.Redirect(w, r, fmt.Sprintf("%s/login?login=%s&user=%s", servercfg.GetFrontendURL(), jwt, content.Email), http.StatusPermanentRedirect)
2021-10-21 02:17:31 +08:00
}
2022-09-14 03:25:56 +08:00
func getGoogleUserInfo(state string, code string) (*OAuthUser, error) {
oauth_state_string, isValid := logic.IsStateValid(state)
2022-09-14 03:25:56 +08:00
if (!isValid || state != oauth_state_string) && !isStateCached(state) {
return nil, fmt.Errorf("invalid oauth state")
2021-10-21 02:17:31 +08:00
}
var token, err = auth_provider.Exchange(context.Background(), code)
2021-10-21 02:17:31 +08:00
if err != nil {
return nil, fmt.Errorf("code exchange failed: %s", err.Error())
}
2021-10-22 03:28:58 +08:00
var data []byte
data, err = json.Marshal(token)
if err != nil {
return nil, fmt.Errorf("failed to convert token to json: %s", err.Error())
}
2022-05-13 18:04:27 +08:00
client := &http.Client{
Timeout: time.Second * 30,
}
response, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)
2021-10-21 02:17:31 +08:00
if err != nil {
return nil, fmt.Errorf("failed getting user info: %s", err.Error())
}
defer response.Body.Close()
2022-01-07 04:05:38 +08:00
contents, err := io.ReadAll(response.Body)
2021-10-21 02:17:31 +08:00
if err != nil {
return nil, fmt.Errorf("failed reading response body: %s", err.Error())
}
2022-09-14 03:25:56 +08:00
var userInfo = &OAuthUser{}
2021-10-22 03:28:58 +08:00
if err = json.Unmarshal(contents, userInfo); err != nil {
return nil, fmt.Errorf("failed parsing email from response data: %s", err.Error())
}
userInfo.AccessToken = string(data)
return userInfo, nil
}
func verifyGoogleUser(token *oauth2.Token) bool {
2021-10-22 21:47:29 +08:00
return token.Valid()
2021-10-21 02:17:31 +08:00
}