Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sandbox auth #211

Merged
merged 4 commits into from
Jun 26, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
"K8S_NAMESPACE": "memphis",
"LOGS_RETENTION_IN_DAYS": "30",
"JWT_SECRET": "35nhvjfosfklgmfg56+fdsgzvfnjksacvbhfksfkgofadsjfgjkoldsdkfvpl'jbgio;dfsjgkl;'XZFVMifobd;dlgjv[sfvjmiodfkvs2fh;fhk44gfdhksdkfdffk",
"REFRESH_JWT_SECRET": "35c7b3eb969db065bfa3c66b38e4323e8f73113f3965dfb55c6bc585dcb0ba62bd399e2588fdc8f709ae0b63fb24be32590f134506ca1d7a4314339f11b8045a"
"REFRESH_JWT_SECRET": "35c7b3eb969db065bfa3c66b38e4323e8f73113f3965dfb55c6bc585dcb0ba62bd399e2588fdc8f709ae0b63fb24be32590f134506ca1d7a4314339f11b8045a",
"GOOGLE_CLIENT_ID": "916272522459-u0f4n2lh9llsielb3l5rob3dnt1fco76.apps.googleusercontent.com"
}
}
]
Expand Down
1 change: 1 addition & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ type Configuration struct {
ANALYTICS_TOKEN string
K8S_NAMESPACE string
LOGS_RETENTION_IN_DAYS string
GOOGLE_CLIENT_ID string
}

func GetConfig() Configuration {
Expand Down
21 changes: 13 additions & 8 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ require (
)

require (
cloud.google.com/go/compute v1.6.1 // indirect
github.com/PuerkitoBio/purell v1.1.1 // indirect
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/cenkalti/backoff/v4 v4.1.2 // indirect
Expand All @@ -39,11 +40,13 @@ require (
github.com/go-stack/stack v1.8.0 // indirect
github.com/gofrs/uuid v4.0.0+incompatible // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/golang/snappy v0.0.3 // indirect
github.com/gomodule/redigo v1.8.4 // indirect
github.com/google/gnostic v0.5.7-v3refs // indirect
github.com/google/gofuzz v1.1.0 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.0.0-20220520183353-fd19c99a87aa // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
github.com/imdario/mergo v0.3.5 // indirect
Expand Down Expand Up @@ -73,6 +76,7 @@ require (
github.com/xdg-go/stringprep v1.0.2 // indirect
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
github.com/yusufpapurcu/wmi v1.2.2 // indirect
go.opencensus.io v0.23.0 // indirect
go.opentelemetry.io/contrib/instrumentation/host v0.29.0 // indirect
go.opentelemetry.io/contrib/instrumentation/runtime v0.29.0 // indirect
go.opentelemetry.io/contrib/propagators/b3 v1.4.0 // indirect
Expand All @@ -87,17 +91,18 @@ require (
go.opentelemetry.io/otel/sdk/metric v0.27.0 // indirect
go.opentelemetry.io/otel/trace v1.5.0 // indirect
go.opentelemetry.io/proto/otlp v0.12.0 // indirect
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20220209214540-3681064d5158 // indirect
golang.org/x/net v0.0.0-20220607020251-c690dde0001d // indirect
golang.org/x/oauth2 v0.0.0-20220608161450-d0670ef3b1eb // indirect
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect
golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d // indirect
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 // indirect
google.golang.org/api v0.84.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20220112215332-a9c7c0acf9f2 // indirect
google.golang.org/grpc v1.45.0 // indirect
google.golang.org/protobuf v1.27.1 // indirect
google.golang.org/genproto v0.0.0-20220608133413-ed9918b62aac // indirect
google.golang.org/grpc v1.47.0 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
Expand Down
143 changes: 143 additions & 0 deletions go.sum

Large diffs are not rendered by default.

180 changes: 180 additions & 0 deletions handlers/sandbox.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
// Copyright 2021-2022 The Memphis Authors
// Licensed under the GNU General Public License v3.0 (the “License”);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.gnu.org/licenses/gpl-3.0.en.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package handlers

import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"memphis-broker/logger"
"memphis-broker/models"
"memphis-broker/utils"
"net/http"
"time"

"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)

type SandboxHandler struct{}

func (sbh SandboxHandler) Login(c *gin.Context) {
var body models.SandboxLoginSchema
ok := utils.Validate(c, &body, false, nil)
if !ok {
return
}
google_token := body.Google_token
claims, err := ValidateGoogleJWT(google_token)
if err != nil {
logger.Error("ValidateGoogleJWT: " + err.Error())
c.AbortWithStatusJSON(500, gin.H{"message": "Server error"})
return
}
exist, user, err := IsUserExist(claims.Email)
if err != nil {
logger.Error("IsUserExist: " + err.Error())
shay23b marked this conversation as resolved.
Show resolved Hide resolved
c.AbortWithStatusJSON(500, gin.H{"message": "Server error"})
return
}

if !exist {
user = models.User{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create sandbox user and not the regular user

ID: primitive.NewObjectID(),
Username: claims.Email,
Password: claims.FirstName + "." + claims.LastName,
HubUsername: "",
HubPassword: "",
UserType: "management",
CreationDate: time.Now(),
AlreadyLoggedIn: false,
AvatarId: 1,
}
_, err = usersCollection.InsertOne(context.TODO(), user)
if err != nil {
logger.Error("InsertOne: " + err.Error())
shay23b marked this conversation as resolved.
Show resolved Hide resolved
c.AbortWithStatusJSON(500, gin.H{"message": "Server error"})
return
}

}

token, refreshToken, err := createTokens(user)
if err != nil {
logger.Error("createTokens: " + err.Error())
shay23b marked this conversation as resolved.
Show resolved Hide resolved
c.AbortWithStatusJSON(500, gin.H{"message": "Server error"})
return
}

if err != nil {
shay23b marked this conversation as resolved.
Show resolved Hide resolved
logger.Error("Login error: " + err.Error())
c.AbortWithStatusJSON(500, gin.H{"message": "Server error"})
return
}
if !user.AlreadyLoggedIn {
usersCollection.UpdateOne(context.TODO(),
bson.M{"_id": user.ID},
bson.M{"$set": bson.M{"already_logged_in": true}},
)
}
domain := ""
secure := false
c.SetCookie("jwt-refresh-token", refreshToken, configuration.REFRESH_JWT_EXPIRES_IN_MINUTES*60*1000, "/", domain, secure, true)
c.IndentedJSON(200, gin.H{
"jwt": token,
"expires_in": configuration.JWT_EXPIRES_IN_MINUTES * 60 * 1000,
"user_id": user.ID,
"username": user.Username,
"user_type": user.UserType,
"creation_date": user.CreationDate,
"already_logged_in": user.AlreadyLoggedIn,
"avatar_id": user.AvatarId,
})
}

type GoogleClaims struct {
shay23b marked this conversation as resolved.
Show resolved Hide resolved
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
FirstName string `json:"given_name"`
LastName string `json:"family_name"`
jwt.StandardClaims
}

func getGooglePublicKey(keyID string) (string, error) {
resp, err := http.Get("https://www.googleapis.com/oauth2/v1/certs")
if err != nil {
return "", err
}
dat, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}

myResp := map[string]string{}
err = json.Unmarshal(dat, &myResp)
if err != nil {
return "", err
}
key, ok := myResp[keyID]
if !ok {
return "", errors.New("key not found")
}
return key, nil
}

func ValidateGoogleJWT(tokenString string) (GoogleClaims, error) {
claimsStruct := GoogleClaims{}

token, err := jwt.ParseWithClaims(
tokenString,
&claimsStruct,
func(token *jwt.Token) (interface{}, error) {
pem, err := getGooglePublicKey(fmt.Sprintf("%s", token.Header["kid"]))
if err != nil {
return nil, err
}
key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(pem))
if err != nil {
return nil, err
}
return key, nil
},
)
if err != nil {
return GoogleClaims{}, err
}

claims, ok := token.Claims.(*GoogleClaims)
if !ok {
return GoogleClaims{}, errors.New("invalid Google JWT")
}

if claims.Issuer != "accounts.google.com" && claims.Issuer != "https://accounts.google.com" {
return GoogleClaims{}, errors.New("iss is invalid")
}

if claims.Audience != configuration.GOOGLE_CLIENT_ID {
return GoogleClaims{}, errors.New("aud is invalid")
}

if claims.ExpiresAt < time.Now().UTC().Unix() {
return GoogleClaims{}, errors.New("JWT is expired")
}

return *claims, nil
}
3 changes: 2 additions & 1 deletion http_server/routes/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (lw loggerWriter) Write(p []byte) (int, error) {
log := string(p)
splitted := strings.Split(log, "| ")
statusCode := strings.Trim(splitted[1], " ")
if statusCode != "200" && statusCode != "204" {
if statusCode != "200" && statusCode != "204" {
logger.Error(log)
}
return len(p), nil
Expand Down Expand Up @@ -61,6 +61,7 @@ func InitializeHttpRoutes() *gin.Engine {
InitializeConsumersRoutes(mainRouter)
InitializeMonitoringRoutes(mainRouter)
InitializeSysLogsRoutes(mainRouter)
InitializeSendboxRoutes(mainRouter)
shay23b marked this conversation as resolved.
Show resolved Hide resolved
mainRouter.GET("/status", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Ok",
Expand Down
26 changes: 26 additions & 0 deletions http_server/routes/sandbox.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright 2021-2022 The Memphis Authors
// Licensed under the GNU General Public License v3.0 (the “License”);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.gnu.org/licenses/gpl-3.0.en.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package routes

import (
"memphis-broker/handlers"

"github.com/gin-gonic/gin"
)

func InitializeSendboxRoutes(router *gin.RouterGroup) {
sandboxHandler := handlers.SandboxHandler{}
sandboxRoutes := router.Group("/sandbox")
sandboxRoutes.POST("/login", sandboxHandler.Login)
}
1 change: 1 addition & 0 deletions middlewares/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ var noNeedAuthRoutes = []string{
"/api/usermgmt/refreshtoken",
"/api/monitoring/writesyslog",
"/api/status",
"/api/sandbox/login",
}

var refreshTokenRoute string = "/api/usermgmt/refreshtoken"
Expand Down
18 changes: 18 additions & 0 deletions models/sandbox.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright 2021-2022 The Memphis Authors
// Licensed under the GNU General Public License v3.0 (the “License”);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.gnu.org/licenses/gpl-3.0.en.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package models

type SandboxLoginSchema struct {
Google_token string `json: "google_token" binding:"required"`
}