Newer
Older
/*
* Copyright (c) 2020 InterDigital Communications, Inc
*
* Licensed under the Apache License, Version 2.0 (the \"License\");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*
* AdvantEDGE Platform Controller REST API
*
* This API is the main Platform Controller API for scenario configuration & sandbox management <p>**Micro-service**<br>[meep-pfm-ctrl](https://github.com/InterDigitalInc/AdvantEDGE/tree/master/go-apps/meep-platform-ctrl) <p>**Type & Usage**<br>Platform main interface used by controller software to configure scenarios and manage sandboxes in the AdvantEDGE platform <p>**Details**<br>API details available at _your-AdvantEDGE-ip-address/api_
*
* API version: 1.0.0
* Contact: AdvantEDGE@InterDigital.com
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package server
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
dataModel "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-data-model"
sm "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-sessions"
users "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-users"
"github.com/google/go-github/github"
"github.com/xanzy/go-gitlab"
"golang.org/x/oauth2"
githuboauth "golang.org/x/oauth2/github"
gitlaboauth "golang.org/x/oauth2/gitlab"
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
const OAUTH_PROVIDER_GITHUB = "github"
const OAUTH_PROVIDER_GITLAB = "gitlab"
func initOAuth() {
// Get default platform URI
pfmCtrl.uri = strings.TrimSpace(os.Getenv("MEEP_PLATFORM_URI"))
// Initialize OAuth
pfmCtrl.oauthConfigs = make(map[string]*oauth2.Config)
pfmCtrl.loginRequests = make(map[string]*LoginRequest)
// Initialize Github config
githubClientId := strings.TrimSpace(os.Getenv("MEEP_OAUTH_GITHUB_CLIENT_ID"))
githubSecret := strings.TrimSpace(os.Getenv("MEEP_OAUTH_GITHUB_SECRET"))
githubRedirectUri := strings.TrimSpace(os.Getenv("MEEP_OAUTH_GITHUB_REDIRECT_URI"))
githubOauthConfig := &oauth2.Config{
ClientID: githubClientId,
ClientSecret: githubSecret,
RedirectURL: githubRedirectUri,
Scopes: []string{},
Endpoint: githuboauth.Endpoint,
}
pfmCtrl.oauthConfigs[OAUTH_PROVIDER_GITHUB] = githubOauthConfig
// Initialize Gitlab config
gitlabClientId := strings.TrimSpace(os.Getenv("MEEP_OAUTH_GITLAB_CLIENT_ID"))
gitlabSecret := strings.TrimSpace(os.Getenv("MEEP_OAUTH_GITLAB_SECRET"))
gitlabRedirectUri := strings.TrimSpace(os.Getenv("MEEP_OAUTH_GITLAB_REDIRECT_URI"))
gitlabOauthConfig := &oauth2.Config{
ClientID: gitlabClientId,
ClientSecret: gitlabSecret,
RedirectURL: gitlabRedirectUri,
Scopes: []string{"read_user"},
Endpoint: gitlaboauth.Endpoint,
}
pfmCtrl.oauthConfigs[OAUTH_PROVIDER_GITLAB] = gitlabOauthConfig
}
// Generate a random state string
func generateState(n int) (string, error) {
data := make([]byte, n)
if _, err := io.ReadFull(rand.Reader, data); err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(data), nil
}
func getUniqueState() (state string, err error) {
for i := 0; i < 3; i++ {
// Get random state
randState, err := generateState(20)
if err != nil {
log.Error(err.Error())
return "", err
}
// Make sure state is unique
if _, found := pfmCtrl.loginRequests[randState]; !found {
return randState, nil
}
}
return "", errors.New("Failed to generate a random state string")
}
func uaLoginOAuth(w http.ResponseWriter, r *http.Request) {
log.Info("----- OAUTH LOGIN -----")
// Retrieve query parameters
query := r.URL.Query()
provider := query.Get("provider")
// Get provider-specific OAuth config
config, found := pfmCtrl.oauthConfigs[provider]
if !found {
log.Error("Provider config not found for: ", provider)
http.Redirect(w, r, pfmCtrl.uri, http.StatusFound)
return
}
// Generate unique random state string
state, err := getUniqueState()
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, pfmCtrl.uri, http.StatusFound)
return
}
// Track oauth request
request := &LoginRequest{
provider: provider,
timestamp: time.Now(),
}
pfmCtrl.loginRequests[state] = request
// Generate provider-specific oauth redirect
uri := config.AuthCodeURL(state, oauth2.AccessTypeOnline)
http.Redirect(w, r, uri, http.StatusFound)
}
func uaAuthorize(w http.ResponseWriter, r *http.Request) {
// Retrieve query parameters
query := r.URL.Query()
code := query.Get("code")
state := query.Get("state")
// Validate request state
request, found := pfmCtrl.loginRequests[state]
if !found {
log.Error("Login request not found with provided state: ", state)
http.Redirect(w, r, pfmCtrl.uri, http.StatusFound)
return
}
// Get provider-specific OAuth config
config := pfmCtrl.oauthConfigs[request.provider]
// Retrieve access token
token, err := config.Exchange(context.Background(), code)
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, pfmCtrl.uri, http.StatusFound)
return
}
// Retrieve User ID
var userId string
switch request.provider {
case OAUTH_PROVIDER_GITHUB:
oauthClient := config.Client(context.Background(), token)
client := github.NewClient(oauthClient)
if client == nil {
err = errors.New("Failed to create new GitHub client")
log.Error(err.Error())
http.Redirect(w, r, pfmCtrl.uri, http.StatusFound)
return
}
user, _, err := client.Users.Get(context.Background(), "")
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, pfmCtrl.uri, http.StatusFound)
return
}
userId = *user.Login
case OAUTH_PROVIDER_GITLAB:
client, err := gitlab.NewOAuthClient(token.AccessToken)
if err != nil {
err = errors.New("Failed to create new GitLab client")
log.Error(err.Error())
http.Redirect(w, r, pfmCtrl.uri, http.StatusFound)
return
}
user, _, err := client.Users.CurrentUser()
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, pfmCtrl.uri, http.StatusFound)
return
}
userId = user.Username
default:
}
// Start user session
sandboxName, err, errCode := startSession(userId, w, r)
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, pfmCtrl.uri, errCode)
return
}
// Redirect user to sandbox
http.Redirect(w, r, pfmCtrl.uri+"?sbox="+sandboxName, http.StatusFound)
}
func uaLoginUser(w http.ResponseWriter, r *http.Request) {
log.Info("----- LOGIN -----")
// Get form data
username := r.FormValue("username")
password := r.FormValue("password")
// Validate user credentials
authenticated, err := pfmCtrl.userStore.AuthenticateUser(username, password)
if err != nil || !authenticated {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
// Start user session
sandboxName, err, errCode := startSession(username, w, r)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), errCode)
return
}
// Prepare response
var sandbox dataModel.Sandbox
sandbox.Name = sandboxName
// Format response
jsonResponse, err := json.Marshal(sandbox)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Send response
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, string(jsonResponse))
}
// Retrieve existing user session or create a new one
func startSession(username string, w http.ResponseWriter, r *http.Request) (sandboxName string, err error, code int) {
// Get existing session by user name, if any
sessionStore := pfmCtrl.sessionMgr.GetSessionStore()
session, err := sessionStore.GetByName(username)
// Check if max session count is reached before creating a new one
count := sessionStore.GetCount()
if count >= pfmCtrl.maxSessions {
err = errors.New("Maximum session count exceeded")
return "", err, http.StatusServiceUnavailable
// Get requested sandbox name & role from user profile, if any
role := users.RoleUser
Kevin Di Lallo
committed
user, err := pfmCtrl.userStore.GetUser(username)
if err == nil {
sandboxName = user.Sboxname
Kevin Di Lallo
committed
}
// Get a new unique sanbox name if not configured in user profile
Kevin Di Lallo
committed
sandboxName = getUniqueSandboxName()
if sandboxName == "" {
err = errors.New("Failed to generate a unique sandbox name")
return "", err, http.StatusInternalServerError
Kevin Di Lallo
committed
}
// Create sandbox in DB
var sandboxConfig dataModel.SandboxConfig
err = createSandbox(sandboxName, &sandboxConfig)
return "", err, http.StatusInternalServerError
session.ID = ""
session.Username = username
session.Sandbox = sandboxName
sandboxName = session.Sandbox
}
// Set session
err, code = sessionStore.Set(session, w, r)
if err != nil {
log.Error("Failed to set session with err: ", err.Error())
// Remove newly created sandbox on failure
if session.ID == "" {
deleteSandbox(sandboxName)
}
}
func uaLogoutUser(w http.ResponseWriter, r *http.Request) {
log.Info("----- LOGOUT -----")
sessionStore := pfmCtrl.sessionMgr.GetSessionStore()
session, err := sessionStore.Get(r)
if err == nil {
// Delete sandbox
deleteSandbox(session.Sandbox)
}
log.Error("Failed to delete session with err: ", err.Error())
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
}
Kevin Di Lallo
committed
func uaTriggerWatchdog(w http.ResponseWriter, r *http.Request) {
Kevin Di Lallo
committed
// Refresh session
sessionStore := pfmCtrl.sessionMgr.GetSessionStore()
Kevin Di Lallo
committed
if err != nil {
log.Error("Failed to refresh session with err: ", err.Error())
Kevin Di Lallo
committed
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
}