[MM-37772] Idiomatic naming (URL, URI, API) (#18128)

* s/Url/URL/g & s/Uri/URI/g

* s/Api/API/g
Этот коммит содержится в:
Ben Schumacher
2021-08-16 19:46:44 +02:00
коммит произвёл GitHub
родитель a7f5512ff3
Коммит 757dc96461
155 изменённых файлов: 1680 добавлений и 1681 удалений

Просмотреть файл

@@ -209,8 +209,8 @@ func (c *Context) SetInvalidParam(parameter string) {
c.Err = NewInvalidParamError(parameter)
}
func (c *Context) SetInvalidUrlParam(parameter string) {
c.Err = NewInvalidUrlParamError(parameter)
func (c *Context) SetInvalidURLParam(parameter string) {
c.Err = NewInvalidURLParamError(parameter)
}
func (c *Context) SetServerBusyError() {
@@ -257,7 +257,7 @@ func NewInvalidParamError(parameter string) *model.AppError {
err := model.NewAppError("Context", "api.context.invalid_body_param.app_error", map[string]interface{}{"Name": parameter}, "", http.StatusBadRequest)
return err
}
func NewInvalidUrlParamError(parameter string) *model.AppError {
func NewInvalidURLParamError(parameter string) *model.AppError {
err := model.NewAppError("Context", "api.context.invalid_url_param.app_error", map[string]interface{}{"Name": parameter}, "", http.StatusBadRequest)
return err
}
@@ -303,7 +303,7 @@ func (c *Context) RequireUserId() *Context {
}
if !model.IsValidId(c.Params.UserId) {
c.SetInvalidUrlParam("user_id")
c.SetInvalidURLParam("user_id")
}
return c
}
@@ -314,7 +314,7 @@ func (c *Context) RequireTeamId() *Context {
}
if !model.IsValidId(c.Params.TeamId) {
c.SetInvalidUrlParam("team_id")
c.SetInvalidURLParam("team_id")
}
return c
}
@@ -325,7 +325,7 @@ func (c *Context) RequireCategoryId() *Context {
}
if !model.IsValidCategoryId(c.Params.CategoryId) {
c.SetInvalidUrlParam("category_id")
c.SetInvalidURLParam("category_id")
}
return c
}
@@ -336,7 +336,7 @@ func (c *Context) RequireInviteId() *Context {
}
if c.Params.InviteId == "" {
c.SetInvalidUrlParam("invite_id")
c.SetInvalidURLParam("invite_id")
}
return c
}
@@ -347,7 +347,7 @@ func (c *Context) RequireTokenId() *Context {
}
if !model.IsValidId(c.Params.TokenId) {
c.SetInvalidUrlParam("token_id")
c.SetInvalidURLParam("token_id")
}
return c
}
@@ -358,7 +358,7 @@ func (c *Context) RequireThreadId() *Context {
}
if !model.IsValidId(c.Params.ThreadId) {
c.SetInvalidUrlParam("thread_id")
c.SetInvalidURLParam("thread_id")
}
return c
}
@@ -369,7 +369,7 @@ func (c *Context) RequireTimestamp() *Context {
}
if c.Params.Timestamp == 0 {
c.SetInvalidUrlParam("timestamp")
c.SetInvalidURLParam("timestamp")
}
return c
}
@@ -380,7 +380,7 @@ func (c *Context) RequireChannelId() *Context {
}
if !model.IsValidId(c.Params.ChannelId) {
c.SetInvalidUrlParam("channel_id")
c.SetInvalidURLParam("channel_id")
}
return c
}
@@ -403,7 +403,7 @@ func (c *Context) RequirePostId() *Context {
}
if !model.IsValidId(c.Params.PostId) {
c.SetInvalidUrlParam("post_id")
c.SetInvalidURLParam("post_id")
}
return c
}
@@ -414,7 +414,7 @@ func (c *Context) RequirePolicyId() *Context {
}
if !model.IsValidId(c.Params.PolicyId) {
c.SetInvalidUrlParam("policy_id")
c.SetInvalidURLParam("policy_id")
}
return c
}
@@ -425,7 +425,7 @@ func (c *Context) RequireAppId() *Context {
}
if !model.IsValidId(c.Params.AppId) {
c.SetInvalidUrlParam("app_id")
c.SetInvalidURLParam("app_id")
}
return c
}
@@ -436,7 +436,7 @@ func (c *Context) RequireFileId() *Context {
}
if !model.IsValidId(c.Params.FileId) {
c.SetInvalidUrlParam("file_id")
c.SetInvalidURLParam("file_id")
}
return c
@@ -448,7 +448,7 @@ func (c *Context) RequireUploadId() *Context {
}
if !model.IsValidId(c.Params.UploadId) {
c.SetInvalidUrlParam("upload_id")
c.SetInvalidURLParam("upload_id")
}
return c
@@ -460,7 +460,7 @@ func (c *Context) RequireFilename() *Context {
}
if c.Params.Filename == "" {
c.SetInvalidUrlParam("filename")
c.SetInvalidURLParam("filename")
}
return c
@@ -472,7 +472,7 @@ func (c *Context) RequirePluginId() *Context {
}
if c.Params.PluginId == "" {
c.SetInvalidUrlParam("plugin_id")
c.SetInvalidURLParam("plugin_id")
}
return c
@@ -484,7 +484,7 @@ func (c *Context) RequireReportId() *Context {
}
if !model.IsValidId(c.Params.ReportId) {
c.SetInvalidUrlParam("report_id")
c.SetInvalidURLParam("report_id")
}
return c
}
@@ -495,7 +495,7 @@ func (c *Context) RequireEmojiId() *Context {
}
if !model.IsValidId(c.Params.EmojiId) {
c.SetInvalidUrlParam("emoji_id")
c.SetInvalidURLParam("emoji_id")
}
return c
}
@@ -506,7 +506,7 @@ func (c *Context) RequireTeamName() *Context {
}
if !model.IsValidTeamName(c.Params.TeamName) {
c.SetInvalidUrlParam("team_name")
c.SetInvalidURLParam("team_name")
}
return c
@@ -518,7 +518,7 @@ func (c *Context) RequireChannelName() *Context {
}
if !model.IsValidChannelIdentifier(c.Params.ChannelName) {
c.SetInvalidUrlParam("channel_name")
c.SetInvalidURLParam("channel_name")
}
return c
@@ -530,7 +530,7 @@ func (c *Context) SanitizeEmail() *Context {
}
c.Params.Email = strings.ToLower(c.Params.Email)
if !model.IsValidEmail(c.Params.Email) {
c.SetInvalidUrlParam("email")
c.SetInvalidURLParam("email")
}
return c
@@ -542,7 +542,7 @@ func (c *Context) RequireCategory() *Context {
}
if !model.IsValidAlphaNumHyphenUnderscore(c.Params.Category, true) {
c.SetInvalidUrlParam("category")
c.SetInvalidURLParam("category")
}
return c
@@ -554,7 +554,7 @@ func (c *Context) RequireService() *Context {
}
if c.Params.Service == "" {
c.SetInvalidUrlParam("service")
c.SetInvalidURLParam("service")
}
return c
@@ -566,7 +566,7 @@ func (c *Context) RequirePreferenceName() *Context {
}
if !model.IsValidAlphaNumHyphenUnderscore(c.Params.PreferenceName, true) {
c.SetInvalidUrlParam("preference_name")
c.SetInvalidURLParam("preference_name")
}
return c
@@ -580,7 +580,7 @@ func (c *Context) RequireEmojiName() *Context {
validName := regexp.MustCompile(`^[a-zA-Z0-9\-\+_]+$`)
if c.Params.EmojiName == "" || len(c.Params.EmojiName) > model.EmojiNameMaxLength || !validName.MatchString(c.Params.EmojiName) {
c.SetInvalidUrlParam("emoji_name")
c.SetInvalidURLParam("emoji_name")
}
return c
@@ -592,7 +592,7 @@ func (c *Context) RequireHookId() *Context {
}
if !model.IsValidId(c.Params.HookId) {
c.SetInvalidUrlParam("hook_id")
c.SetInvalidURLParam("hook_id")
}
return c
@@ -604,7 +604,7 @@ func (c *Context) RequireCommandId() *Context {
}
if !model.IsValidId(c.Params.CommandId) {
c.SetInvalidUrlParam("command_id")
c.SetInvalidURLParam("command_id")
}
return c
}
@@ -615,7 +615,7 @@ func (c *Context) RequireJobId() *Context {
}
if !model.IsValidId(c.Params.JobId) {
c.SetInvalidUrlParam("job_id")
c.SetInvalidURLParam("job_id")
}
return c
}
@@ -626,7 +626,7 @@ func (c *Context) RequireJobType() *Context {
}
if c.Params.JobType == "" || len(c.Params.JobType) > 32 {
c.SetInvalidUrlParam("job_type")
c.SetInvalidURLParam("job_type")
}
return c
}
@@ -637,7 +637,7 @@ func (c *Context) RequireRoleId() *Context {
}
if !model.IsValidId(c.Params.RoleId) {
c.SetInvalidUrlParam("role_id")
c.SetInvalidURLParam("role_id")
}
return c
}
@@ -648,7 +648,7 @@ func (c *Context) RequireSchemeId() *Context {
}
if !model.IsValidId(c.Params.SchemeId) {
c.SetInvalidUrlParam("scheme_id")
c.SetInvalidURLParam("scheme_id")
}
return c
}
@@ -659,7 +659,7 @@ func (c *Context) RequireRoleName() *Context {
}
if !model.IsValidRoleName(c.Params.RoleName) {
c.SetInvalidUrlParam("role_name")
c.SetInvalidURLParam("role_name")
}
return c
@@ -671,7 +671,7 @@ func (c *Context) RequireGroupId() *Context {
}
if !model.IsValidId(c.Params.GroupId) {
c.SetInvalidUrlParam("group_id")
c.SetInvalidURLParam("group_id")
}
return c
}
@@ -682,7 +682,7 @@ func (c *Context) RequireRemoteId() *Context {
}
if c.Params.RemoteId == "" {
c.SetInvalidUrlParam("remote_id")
c.SetInvalidURLParam("remote_id")
}
return c
}
@@ -693,7 +693,7 @@ func (c *Context) RequireSyncableId() *Context {
}
if !model.IsValidId(c.Params.SyncableId) {
c.SetInvalidUrlParam("syncable_id")
c.SetInvalidURLParam("syncable_id")
}
return c
}
@@ -704,7 +704,7 @@ func (c *Context) RequireSyncableType() *Context {
}
if c.Params.SyncableType != model.GroupSyncableTypeTeam && c.Params.SyncableType != model.GroupSyncableTypeChannel {
c.SetInvalidUrlParam("syncable_type")
c.SetInvalidURLParam("syncable_type")
}
return c
}
@@ -715,7 +715,7 @@ func (c *Context) RequireBotUserId() *Context {
}
if !model.IsValidId(c.Params.BotUserId) {
c.SetInvalidUrlParam("bot_user_id")
c.SetInvalidURLParam("bot_user_id")
}
return c
}
@@ -726,7 +726,7 @@ func (c *Context) RequireInvoiceId() *Context {
}
if len(c.Params.InvoiceId) != 27 {
c.SetInvalidUrlParam("invoice_id")
c.SetInvalidURLParam("invoice_id")
}
return c

Просмотреть файл

@@ -320,7 +320,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c.Err.IsOAuth = false
}
if IsApiCall(c.App, r) || IsWebhookCall(c.App, r) || IsOAuthApiCall(c.App, r) || r.Header.Get("X-Mobile-App") != "" {
if IsAPICall(c.App, r) || IsWebhookCall(c.App, r) || IsOAuthAPICall(c.App, r) || r.Header.Get("X-Mobile-App") != "" {
w.WriteHeader(c.Err.StatusCode)
w.Write([]byte(c.Err.ToJson()))
} else {
@@ -336,9 +336,9 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if c.App.Metrics() != nil {
c.App.Metrics().IncrementHTTPRequest()
if r.URL.Path != model.ApiUrlSuffix+"/websocket" {
if r.URL.Path != model.APIURLSuffix+"/websocket" {
elapsed := float64(time.Since(now)) / float64(time.Second)
c.App.Metrics().ObserveApiEndpointDuration(h.HandlerName, r.Method, statusCode, elapsed)
c.App.Metrics().ObserveAPIEndpointDuration(h.HandlerName, r.Method, statusCode, elapsed)
}
}
}
@@ -390,9 +390,9 @@ func (h *Handler) checkCSRFToken(c *Context, r *http.Request, token string, toke
return csrfCheckNeeded, csrfCheckPassed
}
// ApiHandler provides a handler for API endpoints which do not require the user to be logged in order for access to be
// APIHandler provides a handler for API endpoints which do not require the user to be logged in order for access to be
// granted.
func (w *Web) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
func (w *Web) APIHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
handler := &Handler{
App: w.app,
HandleFunc: h,
@@ -409,10 +409,10 @@ func (w *Web) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) h
return handler
}
// ApiHandlerTrustRequester provides a handler for API endpoints which do not require the user to be logged in and are
// APIHandlerTrustRequester provides a handler for API endpoints which do not require the user to be logged in and are
// allowed to be requested directly rather than via javascript/XMLHttpRequest, such as site branding images or the
// websocket.
func (w *Web) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
func (w *Web) APIHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
handler := &Handler{
App: w.app,
HandleFunc: h,
@@ -429,9 +429,9 @@ func (w *Web) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *ht
return handler
}
// ApiSessionRequired provides a handler for API endpoints which require the user to be logged in in order for access to
// APISessionRequired provides a handler for API endpoints which require the user to be logged in in order for access to
// be granted.
func (w *Web) ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
func (w *Web) APISessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler {
handler := &Handler{
App: w.app,
HandleFunc: h,

Просмотреть файл

@@ -22,22 +22,22 @@ import (
func (w *Web) InitOAuth() {
// API version independent OAuth 2.0 as a service provider endpoints
w.MainRouter.Handle("/oauth/authorize", w.ApiHandlerTrustRequester(authorizeOAuthPage)).Methods("GET")
w.MainRouter.Handle("/oauth/authorize", w.ApiSessionRequired(authorizeOAuthApp)).Methods("POST")
w.MainRouter.Handle("/oauth/deauthorize", w.ApiSessionRequired(deauthorizeOAuthApp)).Methods("POST")
w.MainRouter.Handle("/oauth/access_token", w.ApiHandlerTrustRequester(getAccessToken)).Methods("POST")
w.MainRouter.Handle("/oauth/authorize", w.APIHandlerTrustRequester(authorizeOAuthPage)).Methods("GET")
w.MainRouter.Handle("/oauth/authorize", w.APISessionRequired(authorizeOAuthApp)).Methods("POST")
w.MainRouter.Handle("/oauth/deauthorize", w.APISessionRequired(deauthorizeOAuthApp)).Methods("POST")
w.MainRouter.Handle("/oauth/access_token", w.APIHandlerTrustRequester(getAccessToken)).Methods("POST")
// API version independent OAuth as a client endpoints
w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/complete", w.ApiHandler(completeOAuth)).Methods("GET")
w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/login", w.ApiHandler(loginWithOAuth)).Methods("GET")
w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/mobile_login", w.ApiHandler(mobileLoginWithOAuth)).Methods("GET")
w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/signup", w.ApiHandler(signupWithOAuth)).Methods("GET")
w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/complete", w.APIHandler(completeOAuth)).Methods("GET")
w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/login", w.APIHandler(loginWithOAuth)).Methods("GET")
w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/mobile_login", w.APIHandler(mobileLoginWithOAuth)).Methods("GET")
w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/signup", w.APIHandler(signupWithOAuth)).Methods("GET")
// Old endpoints for backwards compatibility, needed to not break SSO for any old setups
w.MainRouter.Handle("/api/v3/oauth/{service:[A-Za-z0-9]+}/complete", w.ApiHandler(completeOAuth)).Methods("GET")
w.MainRouter.Handle("/signup/{service:[A-Za-z0-9]+}/complete", w.ApiHandler(completeOAuth)).Methods("GET")
w.MainRouter.Handle("/login/{service:[A-Za-z0-9]+}/complete", w.ApiHandler(completeOAuth)).Methods("GET")
w.MainRouter.Handle("/api/v4/oauth_test", w.ApiSessionRequired(testHandler)).Methods("GET")
w.MainRouter.Handle("/api/v3/oauth/{service:[A-Za-z0-9]+}/complete", w.APIHandler(completeOAuth)).Methods("GET")
w.MainRouter.Handle("/signup/{service:[A-Za-z0-9]+}/complete", w.APIHandler(completeOAuth)).Methods("GET")
w.MainRouter.Handle("/login/{service:[A-Za-z0-9]+}/complete", w.APIHandler(completeOAuth)).Methods("GET")
w.MainRouter.Handle("/api/v4/oauth_test", w.APISessionRequired(testHandler)).Methods("GET")
}
func testHandler(c *Context, w http.ResponseWriter, r *http.Request) {
@@ -67,7 +67,7 @@ func authorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) {
defer c.LogAuditRec(auditRec)
c.LogAudit("attempt")
redirectUrl, appErr := c.App.AllowOAuthAppAccessToUser(c.AppContext.Session().UserId, authRequest)
redirectURL, appErr := c.App.AllowOAuthAppAccessToUser(c.AppContext.Session().UserId, authRequest)
if appErr != nil {
c.Err = appErr
return
@@ -76,7 +76,7 @@ func authorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) {
auditRec.Success()
c.LogAudit("")
w.Write([]byte(model.MapToJson(map[string]string{"redirect": redirectUrl})))
w.Write([]byte(model.MapToJson(map[string]string{"redirect": redirectURL})))
}
func deauthorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) {
@@ -113,7 +113,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) {
authRequest := &model.AuthorizeRequest{
ResponseType: r.URL.Query().Get("response_type"),
ClientId: r.URL.Query().Get("client_id"),
RedirectUri: r.URL.Query().Get("redirect_uri"),
RedirectURI: r.URL.Query().Get("redirect_uri"),
Scope: r.URL.Query().Get("scope"),
State: r.URL.Query().Get("state"),
}
@@ -145,7 +145,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
if !oauthApp.IsValidRedirectURL(authRequest.RedirectUri) {
if !oauthApp.IsValidRedirectURL(authRequest.RedirectURI) {
err := model.NewAppError("authorizeOAuthPage", "api.oauth.allow_oauth.redirect_callback.app_error", nil, "", http.StatusBadRequest)
utils.RenderWebError(c.App.Config(), w, r, err.StatusCode,
url.Values{
@@ -164,14 +164,14 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) {
// Automatically allow if the app is trusted
if oauthApp.IsTrusted || isAuthorized {
redirectUrl, err := c.App.AllowOAuthAppAccessToUser(c.AppContext.Session().UserId, authRequest)
redirectURL, err := c.App.AllowOAuthAppAccessToUser(c.AppContext.Session().UserId, authRequest)
if err != nil {
utils.RenderWebAppError(c.App.Config(), w, r, err, c.App.AsymmetricSigningKey())
return
}
http.Redirect(w, r, redirectUrl, http.StatusFound)
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
@@ -219,7 +219,7 @@ func getAccessToken(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
redirectUri := r.FormValue("redirect_uri")
redirectURI := r.FormValue("redirect_uri")
auditRec := c.MakeAuditRecord("getAccessToken", audit.Fail)
defer c.LogAuditRec(auditRec)
@@ -227,7 +227,7 @@ func getAccessToken(c *Context, w http.ResponseWriter, r *http.Request) {
auditRec.AddMeta("client_id", clientId)
c.LogAudit("attempt")
accessRsp, err := c.App.GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, code, secret, refreshToken)
accessRsp, err := c.App.GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectURI, code, secret, refreshToken)
if err != nil {
c.Err = err
return
@@ -373,13 +373,13 @@ func loginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
authUrl, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionLogin, redirectURL, loginHint, false)
authURL, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionLogin, redirectURL, loginHint, false)
if err != nil {
c.Err = err
return
}
http.Redirect(w, r, authUrl, http.StatusFound)
http.Redirect(w, r, authURL, http.StatusFound)
}
func mobileLoginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
@@ -402,13 +402,13 @@ func mobileLoginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
authUrl, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionMobile, redirectURL, "", true)
authURL, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionMobile, redirectURL, "", true)
if err != nil {
c.Err = err
return
}
http.Redirect(w, r, authUrl, http.StatusFound)
http.Redirect(w, r, authURL, http.StatusFound)
}
func signupWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
@@ -430,11 +430,11 @@ func signupWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
authUrl, err := c.App.GetOAuthSignupEndpoint(w, r, c.Params.Service, teamId)
authURL, err := c.App.GetOAuthSignupEndpoint(w, r, c.Params.Service, teamId)
if err != nil {
c.Err = err
return
}
http.Redirect(w, r, authUrl, http.StatusFound)
http.Redirect(w, r, authURL, http.StatusFound)
}

Просмотреть файл

@@ -52,7 +52,7 @@ func TestOAuthComplete_AccessDenied(t *testing.T) {
func TestAuthorizeOAuthApp(t *testing.T) {
th := Setup(t).InitBasic()
th.Login(ApiClient, th.SystemAdminUser)
th.Login(apiClient, th.SystemAdminUser)
defer th.TearDown()
enableOAuth := *th.App.Config().ServiceSettings.EnableOAuthServiceProvider
@@ -76,13 +76,13 @@ func TestAuthorizeOAuthApp(t *testing.T) {
authRequest := &model.AuthorizeRequest{
ResponseType: model.AuthCodeResponseType,
ClientId: rapp.Id,
RedirectUri: rapp.CallbackUrls[0],
RedirectURI: rapp.CallbackUrls[0],
Scope: "",
State: "123",
}
// Test auth code flow
ruri, _, err := ApiClient.AuthorizeOAuthApp(authRequest)
ruri, _, err := apiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
require.NotEmpty(t, ruri, "redirect url should be set")
@@ -94,7 +94,7 @@ func TestAuthorizeOAuthApp(t *testing.T) {
// Test implicit flow
authRequest.ResponseType = model.ImplicitResponseType
ruri, _, err = ApiClient.AuthorizeOAuthApp(authRequest)
ruri, _, err = apiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
require.False(t, ruri == "", "redirect url should be set")
@@ -105,45 +105,45 @@ func TestAuthorizeOAuthApp(t *testing.T) {
assert.False(t, values.Get("access_token") == "", "access_token not returned")
assert.Equal(t, authRequest.State, values.Get("state"), "returned state doesn't match")
oldToken := ApiClient.AuthToken
ApiClient.AuthToken = values.Get("access_token")
_, resp, err := ApiClient.AuthorizeOAuthApp(authRequest)
oldToken := apiClient.AuthToken
apiClient.AuthToken = values.Get("access_token")
_, resp, err := apiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
ApiClient.AuthToken = oldToken
apiClient.AuthToken = oldToken
authRequest.RedirectUri = ""
_, resp, err = ApiClient.AuthorizeOAuthApp(authRequest)
authRequest.RedirectURI = ""
_, resp, err = apiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
authRequest.RedirectUri = "http://somewhereelse.com"
_, resp, err = ApiClient.AuthorizeOAuthApp(authRequest)
authRequest.RedirectURI = "http://somewhereelse.com"
_, resp, err = apiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
authRequest.RedirectUri = rapp.CallbackUrls[0]
authRequest.RedirectURI = rapp.CallbackUrls[0]
authRequest.ResponseType = ""
_, resp, err = ApiClient.AuthorizeOAuthApp(authRequest)
_, resp, err = apiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
authRequest.ResponseType = model.AuthCodeResponseType
authRequest.ClientId = ""
_, resp, err = ApiClient.AuthorizeOAuthApp(authRequest)
_, resp, err = apiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
authRequest.ClientId = model.NewId()
_, resp, err = ApiClient.AuthorizeOAuthApp(authRequest)
_, resp, err = apiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
}
func TestDeauthorizeOAuthApp(t *testing.T) {
th := Setup(t).InitBasic()
th.Login(ApiClient, th.SystemAdminUser)
th.Login(apiClient, th.SystemAdminUser)
defer th.TearDown()
enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
@@ -166,26 +166,26 @@ func TestDeauthorizeOAuthApp(t *testing.T) {
authRequest := &model.AuthorizeRequest{
ResponseType: model.AuthCodeResponseType,
ClientId: rapp.Id,
RedirectUri: rapp.CallbackUrls[0],
RedirectURI: rapp.CallbackUrls[0],
Scope: "",
State: "123",
}
_, _, err := ApiClient.AuthorizeOAuthApp(authRequest)
_, _, err := apiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
_, err = ApiClient.DeauthorizeOAuthApp(rapp.Id)
_, err = apiClient.DeauthorizeOAuthApp(rapp.Id)
require.NoError(t, err)
resp, err := ApiClient.DeauthorizeOAuthApp("junk")
resp, err := apiClient.DeauthorizeOAuthApp("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, err = ApiClient.DeauthorizeOAuthApp(model.NewId())
_, err = apiClient.DeauthorizeOAuthApp(model.NewId())
require.NoError(t, err)
th.Logout(ApiClient)
resp, err = ApiClient.DeauthorizeOAuthApp(rapp.Id)
th.Logout(apiClient)
resp, err = apiClient.DeauthorizeOAuthApp(rapp.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
@@ -196,7 +196,7 @@ func TestOAuthAccessToken(t *testing.T) {
}
th := Setup(t).InitBasic()
th.Login(ApiClient, th.SystemAdminUser)
th.Login(apiClient, th.SystemAdminUser)
defer th.TearDown()
enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
@@ -225,59 +225,59 @@ func TestOAuthAccessToken(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = false })
data := url.Values{"grant_type": []string{"junk"}, "client_id": []string{"12345678901234567890123456"}, "client_secret": []string{"12345678901234567890123456"}, "code": []string{"junk"}, "redirect_uri": []string{oauthApp.CallbackUrls[0]}}
_, _, err := ApiClient.GetOAuthAccessToken(data)
_, _, err := apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - oauth providing turned off")
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true })
authRequest := &model.AuthorizeRequest{
ResponseType: model.AuthCodeResponseType,
ClientId: oauthApp.Id,
RedirectUri: oauthApp.CallbackUrls[0],
RedirectURI: oauthApp.CallbackUrls[0],
Scope: "all",
State: "123",
}
redirect, _, err := ApiClient.AuthorizeOAuthApp(authRequest)
redirect, _, err := apiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ := url.Parse(redirect)
ApiClient.Logout()
apiClient.Logout()
data = url.Values{"grant_type": []string{"junk"}, "client_id": []string{oauthApp.Id}, "client_secret": []string{oauthApp.ClientSecret}, "code": []string{rurl.Query().Get("code")}, "redirect_uri": []string{oauthApp.CallbackUrls[0]}}
_, _, err = ApiClient.GetOAuthAccessToken(data)
_, _, err = apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - bad grant type")
data.Set("grant_type", model.AccessTokenGrantType)
data.Set("client_id", "")
_, _, err = ApiClient.GetOAuthAccessToken(data)
_, _, err = apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - missing client id")
data.Set("client_id", "junk")
_, _, err = ApiClient.GetOAuthAccessToken(data)
_, _, err = apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - bad client id")
data.Set("client_id", oauthApp.Id)
data.Set("client_secret", "")
_, _, err = ApiClient.GetOAuthAccessToken(data)
_, _, err = apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - missing client secret")
data.Set("client_secret", "junk")
_, _, err = ApiClient.GetOAuthAccessToken(data)
_, _, err = apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - bad client secret")
data.Set("client_secret", oauthApp.ClientSecret)
data.Set("code", "")
_, _, err = ApiClient.GetOAuthAccessToken(data)
_, _, err = apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - missing code")
data.Set("code", "junk")
_, _, err = ApiClient.GetOAuthAccessToken(data)
_, _, err = apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - bad code")
data.Set("code", rurl.Query().Get("code"))
data.Set("redirect_uri", "junk")
_, _, err = ApiClient.GetOAuthAccessToken(data)
_, _, err = apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - non-matching redirect uri")
// reset data for successful request
@@ -289,29 +289,29 @@ func TestOAuthAccessToken(t *testing.T) {
token := ""
refreshToken := ""
rsp, _, err := ApiClient.GetOAuthAccessToken(data)
rsp, _, err := apiClient.GetOAuthAccessToken(data)
require.NoError(t, err)
require.NotEmpty(t, rsp.AccessToken, "access token not returned")
require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned")
token, refreshToken = rsp.AccessToken, rsp.RefreshToken
require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect")
_, err = ApiClient.DoApiGet("/oauth_test", "")
_, err = apiClient.DoAPIGet("/oauth_test", "")
require.NoError(t, err)
ApiClient.SetOAuthToken("")
_, err = ApiClient.DoApiGet("/oauth_test", "")
apiClient.SetOAuthToken("")
_, err = apiClient.DoAPIGet("/oauth_test", "")
require.Error(t, err, "should have failed - no access token provided")
ApiClient.SetOAuthToken("badtoken")
_, err = ApiClient.DoApiGet("/oauth_test", "")
apiClient.SetOAuthToken("badtoken")
_, err = apiClient.DoAPIGet("/oauth_test", "")
require.Error(t, err, "should have failed - bad token provided")
ApiClient.SetOAuthToken(token)
_, err = ApiClient.DoApiGet("/oauth_test", "")
apiClient.SetOAuthToken(token)
_, err = apiClient.DoAPIGet("/oauth_test", "")
require.NoError(t, err)
_, _, err = ApiClient.GetOAuthAccessToken(data)
_, _, err = apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - tried to reuse auth code")
data.Set("grant_type", model.RefreshTokenGrantType)
@@ -320,31 +320,31 @@ func TestOAuthAccessToken(t *testing.T) {
data.Set("refresh_token", "")
data.Set("redirect_uri", oauthApp.CallbackUrls[0])
data.Del("code")
_, _, err = ApiClient.GetOAuthAccessToken(data)
_, _, err = apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "Should have failed - refresh token empty")
data.Set("refresh_token", refreshToken)
rsp, _, err = ApiClient.GetOAuthAccessToken(data)
rsp, _, err = apiClient.GetOAuthAccessToken(data)
require.NoError(t, err)
require.NotEmpty(t, rsp.AccessToken, "access token not returned")
require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned")
require.NotEqual(t, rsp.RefreshToken, refreshToken, "refresh token did not update")
require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect")
ApiClient.SetOAuthToken(rsp.AccessToken)
_, err = ApiClient.DoApiGet("/oauth_test", "")
apiClient.SetOAuthToken(rsp.AccessToken)
_, err = apiClient.DoAPIGet("/oauth_test", "")
require.NoError(t, err)
data.Set("refresh_token", rsp.RefreshToken)
rsp, _, err = ApiClient.GetOAuthAccessToken(data)
rsp, _, err = apiClient.GetOAuthAccessToken(data)
require.NoError(t, err)
require.NotEmpty(t, rsp.AccessToken, "access token not returned")
require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned")
require.NotEqual(t, rsp.RefreshToken, refreshToken, "refresh token did not update")
require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect")
ApiClient.SetOAuthToken(rsp.AccessToken)
_, err = ApiClient.DoApiGet("/oauth_test", "")
apiClient.SetOAuthToken(rsp.AccessToken)
_, err = apiClient.DoAPIGet("/oauth_test", "")
require.NoError(t, err)
authData := &model.AuthData{ClientId: oauthApp.Id, RedirectUri: oauthApp.CallbackUrls[0], UserId: th.BasicUser.Id, Code: model.NewId(), ExpiresIn: -1}
@@ -357,10 +357,10 @@ func TestOAuthAccessToken(t *testing.T) {
data.Set("redirect_uri", oauthApp.CallbackUrls[0])
data.Set("code", authData.Code)
data.Del("refresh_token")
_, _, err = ApiClient.GetOAuthAccessToken(data)
_, _, err = apiClient.GetOAuthAccessToken(data)
require.Error(t, err, "Should have failed - code is expired")
ApiClient.ClearOAuthToken()
apiClient.ClearOAuthToken()
}
func TestMobileLoginWithOAuth(t *testing.T) {
@@ -415,7 +415,7 @@ func TestOAuthComplete(t *testing.T) {
}
th := Setup(t).InitBasic()
th.Login(ApiClient, th.SystemAdminUser)
th.Login(apiClient, th.SystemAdminUser)
defer th.TearDown()
gitLabSettingsEnable := th.App.Config().GitLabSettings.Enable
@@ -423,7 +423,7 @@ func TestOAuthComplete(t *testing.T) {
gitLabSettingsId := th.App.Config().GitLabSettings.Id
gitLabSettingsSecret := th.App.Config().GitLabSettings.Secret
gitLabSettingsTokenEndpoint := th.App.Config().GitLabSettings.TokenEndpoint
gitLabSettingsUserApiEndpoint := th.App.Config().GitLabSettings.UserApiEndpoint
gitLabSettingsUserAPIEndpoint := th.App.Config().GitLabSettings.UserAPIEndpoint
enableOAuthServiceProvider := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
defer func() {
th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Enable = gitLabSettingsEnable })
@@ -431,20 +431,20 @@ func TestOAuthComplete(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Id = gitLabSettingsId })
th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Secret = gitLabSettingsSecret })
th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.TokenEndpoint = gitLabSettingsTokenEndpoint })
th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.UserApiEndpoint = gitLabSettingsUserApiEndpoint })
th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.UserAPIEndpoint = gitLabSettingsUserAPIEndpoint })
th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuthServiceProvider })
}()
r, err := HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123", ApiClient.HTTPClient, "", true)
r, err := HTTPGet(apiClient.URL+"/login/gitlab/complete?code=123", apiClient.HTTPClient, "", true)
assert.Error(t, err)
closeBody(r)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Enable = true })
r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state=!#$#F@#Yˆ&~ñ", ApiClient.HTTPClient, "", true)
r, err = HTTPGet(apiClient.URL+"/login/gitlab/complete?code=123&state=!#$#F@#Yˆ&~ñ", apiClient.HTTPClient, "", true)
assert.Error(t, err)
closeBody(r)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.AuthEndpoint = ApiClient.Url + "/oauth/authorize" })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.AuthEndpoint = apiClient.URL + "/oauth/authorize" })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Id = model.NewId() })
stateProps := map[string]string{}
@@ -453,13 +453,13 @@ func TestOAuthComplete(t *testing.T) {
stateProps["redirect_to"] = *th.App.Config().GitLabSettings.AuthEndpoint
state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", true)
r, err = HTTPGet(apiClient.URL+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), apiClient.HTTPClient, "", true)
assert.Error(t, err)
closeBody(r)
stateProps["hash"] = utils.HashSha256(*th.App.Config().GitLabSettings.Id)
state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", true)
r, err = HTTPGet(apiClient.URL+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), apiClient.HTTPClient, "", true)
assert.Error(t, err)
closeBody(r)
@@ -478,8 +478,8 @@ func TestOAuthComplete(t *testing.T) {
Homepage: "https://nowhere.com",
Description: "test",
CallbackUrls: []string{
ApiClient.Url + "/signup/" + model.ServiceGitlab + "/complete",
ApiClient.Url + "/login/" + model.ServiceGitlab + "/complete",
apiClient.URL + "/signup/" + model.ServiceGitlab + "/complete",
apiClient.URL + "/login/" + model.ServiceGitlab + "/complete",
},
CreatorId: th.SystemAdminUser.Id,
IsTrusted: true,
@@ -489,21 +489,21 @@ func TestOAuthComplete(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Id = oauthApp.Id })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Secret = oauthApp.ClientSecret })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.AuthEndpoint = ApiClient.Url + "/oauth/authorize" })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.TokenEndpoint = ApiClient.Url + "/oauth/access_token" })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.UserApiEndpoint = ApiClient.ApiUrl + "/users/me" })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.AuthEndpoint = apiClient.URL + "/oauth/authorize" })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.TokenEndpoint = apiClient.URL + "/oauth/access_token" })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.UserAPIEndpoint = apiClient.APIURL + "/users/me" })
provider := &MattermostTestProvider{}
authRequest := &model.AuthorizeRequest{
ResponseType: model.AuthCodeResponseType,
ClientId: oauthApp.Id,
RedirectUri: oauthApp.CallbackUrls[0],
RedirectURI: oauthApp.CallbackUrls[0],
Scope: "all",
State: "123",
}
redirect, _, err := ApiClient.AuthorizeOAuthApp(authRequest)
redirect, _, err := apiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ := url.Parse(redirect)
@@ -514,19 +514,19 @@ func TestOAuthComplete(t *testing.T) {
stateProps["hash"] = utils.HashSha256(*th.App.Config().GitLabSettings.Id)
stateProps["redirect_to"] = "/oauth/authorize"
state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false)
r, err = HTTPGet(apiClient.URL+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), apiClient.HTTPClient, "", false)
if err == nil {
closeBody(r)
}
einterfaces.RegisterOAuthProvider(model.ServiceGitlab, provider)
redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest)
redirect, _, err = apiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ = url.Parse(redirect)
code = rurl.Query().Get("code")
r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false)
r, err = HTTPGet(apiClient.URL+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), apiClient.HTTPClient, "", false)
if err == nil {
closeBody(r)
}
@@ -535,36 +535,36 @@ func TestOAuthComplete(t *testing.T) {
th.BasicUser.Id, model.ServiceGitlab, &th.BasicUser.Email, th.BasicUser.Email, true)
require.NoError(t, nErr)
redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest)
redirect, _, err = apiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ = url.Parse(redirect)
code = rurl.Query().Get("code")
stateProps["action"] = model.OAuthActionLogin
state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
if r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil {
if r, err = HTTPGet(apiClient.URL+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), apiClient.HTTPClient, "", false); err == nil {
closeBody(r)
}
redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest)
redirect, _, err = apiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ = url.Parse(redirect)
code = rurl.Query().Get("code")
delete(stateProps, "action")
state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
if r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil {
if r, err = HTTPGet(apiClient.URL+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), apiClient.HTTPClient, "", false); err == nil {
closeBody(r)
}
redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest)
redirect, _, err = apiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ = url.Parse(redirect)
code = rurl.Query().Get("code")
stateProps["action"] = model.OAuthActionSignup
state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
if r, err := HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil {
if r, err := HTTPGet(apiClient.URL+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), apiClient.HTTPClient, "", false); err == nil {
closeBody(r)
}
}

Просмотреть файл

@@ -17,8 +17,8 @@ import (
)
func (w *Web) InitSaml() {
w.MainRouter.Handle("/login/sso/saml", w.ApiHandler(loginWithSaml)).Methods("GET")
w.MainRouter.Handle("/login/sso/saml", w.ApiHandlerTrustRequester(completeSaml)).Methods("POST")
w.MainRouter.Handle("/login/sso/saml", w.APIHandler(loginWithSaml)).Methods("GET")
w.MainRouter.Handle("/login/sso/saml", w.APIHandlerTrustRequester(completeSaml)).Methods("POST")
}
func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) {

Просмотреть файл

@@ -65,7 +65,7 @@ func root(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
if IsApiCall(c.App, r) {
if IsAPICall(c.App, r) {
Handle404(c.App, w, r)
return
}

Просмотреть файл

@@ -62,7 +62,7 @@ func Handle404(a app.AppIface, w http.ResponseWriter, r *http.Request) {
ipAddress := utils.GetIPAddress(r, a.Config().ServiceSettings.TrustedProxyIPHeader)
mlog.Debug("not found handler triggered", mlog.String("path", r.URL.Path), mlog.Int("code", 404), mlog.String("ip", ipAddress))
if IsApiCall(a, r) {
if IsAPICall(a, r) {
w.WriteHeader(err.StatusCode)
err.DetailedError = "There doesn't appear to be an api call for the url='" + r.URL.Path + "'. Typo? are you missing a team_id or user_id as part of the url?"
w.Write([]byte(err.ToJson()))
@@ -73,7 +73,7 @@ func Handle404(a app.AppIface, w http.ResponseWriter, r *http.Request) {
}
}
func IsApiCall(a app.AppIface, r *http.Request) bool {
func IsAPICall(a app.AppIface, r *http.Request) bool {
subpath, _ := utils.GetSubpathFromConfig(a.Config())
return strings.HasPrefix(r.URL.Path, path.Join(subpath, "api")+"/")
@@ -85,7 +85,7 @@ func IsWebhookCall(a app.AppIface, r *http.Request) bool {
return strings.HasPrefix(r.URL.Path, path.Join(subpath, "hooks")+"/")
}
func IsOAuthApiCall(a app.AppIface, r *http.Request) bool {
func IsOAuthAPICall(a app.AppIface, r *http.Request) bool {
subpath, _ := utils.GetSubpathFromConfig(a.Config())
if r.Method == "POST" && r.URL.Path == path.Join(subpath, "oauth", "authorize") {

Просмотреть файл

@@ -27,7 +27,7 @@ import (
"github.com/mattermost/mattermost-server/v6/utils"
)
var ApiClient *model.Client4
var apiClient *model.Client4
var URL string
type TestHelper struct {
@@ -115,7 +115,7 @@ func setupTestHelper(includeCacheLayer bool) *TestHelper {
web := New(a, s.Router)
URL = fmt.Sprintf("http://localhost:%v", s.ListenAddr.Port)
ApiClient = model.NewAPIv4Client(URL)
apiClient = model.NewAPIv4Client(URL)
s.Store.MarkSystemRanUnitTests()

Просмотреть файл

@@ -21,7 +21,7 @@ func TestIncomingWebhook(t *testing.T) {
defer th.TearDown()
if !*th.App.Config().ServiceSettings.EnableIncomingWebhooks {
_, err := http.Post(ApiClient.Url+"/hooks/123", "", strings.NewReader("123"))
_, err := http.Post(apiClient.URL+"/hooks/123", "", strings.NewReader("123"))
assert.Error(t, err, "should have errored - webhooks turned off")
return
}
@@ -29,7 +29,7 @@ func TestIncomingWebhook(t *testing.T) {
hook, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id})
require.Nil(t, err)
url := ApiClient.Url + "/hooks/" + hook.Id
url := apiClient.URL + "/hooks/" + hook.Id
tooLongText := ""
for i := 0; i < 8200; i++ {
@@ -53,7 +53,7 @@ func TestIncomingWebhook(t *testing.T) {
assert.NotEqual(t, http.StatusOK, resp.StatusCode, "should have errored - bad channel")
payload = "payload={\"text\": \"test text\"}"
resp, err = http.Post(ApiClient.Url+"/hooks/abc123", "application/x-www-form-urlencoded", strings.NewReader(payload))
resp, err = http.Post(apiClient.URL+"/hooks/abc123", "application/x-www-form-urlencoded", strings.NewReader(payload))
require.NoError(t, err)
assert.NotEqual(t, http.StatusOK, resp.StatusCode, "should have errored - bad hook")
@@ -116,7 +116,7 @@ func TestIncomingWebhook(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
payloadMultiPart := "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\nwebhook-bot\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"text\"\r\n\r\nthis is a test :tada:\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
resp, err = http.Post(ApiClient.Url+"/hooks/"+hook.Id, "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", strings.NewReader(payloadMultiPart))
resp, err = http.Post(apiClient.URL+"/hooks/"+hook.Id, "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", strings.NewReader(payloadMultiPart))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
@@ -146,9 +146,9 @@ func TestIncomingWebhook(t *testing.T) {
// System-Admin Owned Hook
adminHook, appErr := th.App.CreateIncomingWebhookForChannel(th.SystemAdminUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id})
require.Nil(t, appErr)
adminUrl := ApiClient.Url + "/hooks/" + adminHook.Id
adminURL := apiClient.URL + "/hooks/" + adminHook.Id
resp, err = http.Post(adminUrl, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DefaultChannelName)))
resp, err = http.Post(adminURL, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DefaultChannelName)))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
@@ -239,18 +239,18 @@ func TestIncomingWebhook(t *testing.T) {
require.Nil(t, err)
require.NotNil(t, hook)
apiHookUrl := ApiClient.Url + "/hooks/" + hook.Id
apiHookURL := apiClient.URL + "/hooks/" + hook.Id
payload := "payload={\"text\": \"test text\"}"
resp, err2 := http.Post(apiHookUrl, "application/x-www-form-urlencoded", strings.NewReader(payload))
resp, err2 := http.Post(apiHookURL, "application/x-www-form-urlencoded", strings.NewReader(payload))
require.NoError(t, err2)
assert.True(t, resp.StatusCode == http.StatusOK)
resp, err2 = http.Post(apiHookUrl, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", th.BasicChannel.Name)))
resp, err2 = http.Post(apiHookURL, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", th.BasicChannel.Name)))
require.NoError(t, err2)
assert.True(t, resp.StatusCode == http.StatusOK)
resp, err2 = http.Post(apiHookUrl, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", channel.Name)))
resp, err2 = http.Post(apiHookURL, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", channel.Name)))
require.NoError(t, err2)
assert.True(t, resp.StatusCode == http.StatusForbidden)
})
@@ -284,20 +284,20 @@ func TestCommandWebhooks(t *testing.T) {
hook, appErr := th.App.CreateCommandWebhook(cmd.Id, args)
require.Nil(t, appErr)
resp, err := http.Post(ApiClient.Url+"/hooks/commands/123123123123", "application/json", bytes.NewBufferString(`{"text":"this is a test"}`))
resp, err := http.Post(apiClient.URL+"/hooks/commands/123123123123", "application/json", bytes.NewBufferString(`{"text":"this is a test"}`))
require.NoError(t, err)
assert.Equal(t, http.StatusNotFound, resp.StatusCode, "expected not-found for non-existent hook")
resp, err = http.Post(ApiClient.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"invalid`))
resp, err = http.Post(apiClient.URL+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"invalid`))
require.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
for i := 0; i < 5; i++ {
response, err2 := http.Post(ApiClient.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`))
response, err2 := http.Post(apiClient.URL+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`))
require.NoError(t, err2)
require.Equal(t, http.StatusOK, response.StatusCode)
}
resp, _ = http.Post(ApiClient.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`))
resp, _ = http.Post(apiClient.URL+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`))
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
}