Этот коммит содержится в:
Ben Schumacher
2021-07-12 20:05:36 +02:00
коммит произвёл Claudio Costa
родитель 953eebdef4
Коммит 97ccf0bdf6
472 изменённых файлов: 9126 добавлений и 9132 удалений

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

@@ -107,13 +107,13 @@ func (c *Context) LogErrorByCode(err *model.AppError) {
}
func (c *Context) IsSystemAdmin() bool {
return c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM)
return c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem)
}
func (c *Context) SessionRequired() {
if !*c.App.Config().ServiceSettings.EnableUserAccessTokens &&
c.AppContext.Session().Props[model.SESSION_PROP_TYPE] == model.SESSION_TYPE_USER_ACCESS_TOKEN &&
c.AppContext.Session().Props[model.SESSION_PROP_IS_BOT] != model.SESSION_PROP_IS_BOT_VALUE {
c.AppContext.Session().Props[model.SessionPropType] == model.SessionTypeUserAccessToken &&
c.AppContext.Session().Props[model.SessionPropIsBot] != model.SessionPropIsBotValue {
c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "UserAccessToken", http.StatusUnauthorized)
return
@@ -126,14 +126,14 @@ func (c *Context) SessionRequired() {
}
func (c *Context) CloudKeyRequired() {
if license := c.App.Srv().License(); license == nil || !*license.Features.Cloud || c.AppContext.Session().Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_CLOUD_KEY {
if license := c.App.Srv().License(); license == nil || !*license.Features.Cloud || c.AppContext.Session().Props[model.SessionPropType] != model.SessionTypeCloudKey {
c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "TokenRequired", http.StatusUnauthorized)
return
}
}
func (c *Context) RemoteClusterTokenRequired() {
if license := c.App.Srv().License(); license == nil || !*license.Features.RemoteClusterService || c.AppContext.Session().Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_REMOTECLUSTER_TOKEN {
if license := c.App.Srv().License(); license == nil || !*license.Features.RemoteClusterService || c.AppContext.Session().Props[model.SessionPropType] != model.SessionTypeRemoteclusterToken {
c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "TokenRequired", http.StatusUnauthorized)
return
}
@@ -161,8 +161,8 @@ func (c *Context) MfaRequired() {
}
// Only required for email and ldap accounts
if user.AuthService != "" &&
user.AuthService != model.USER_AUTH_SERVICE_EMAIL &&
user.AuthService != model.USER_AUTH_SERVICE_LDAP {
user.AuthService != model.UserAuthServiceEmail &&
user.AuthService != model.UserAuthServiceLdap {
return
}
@@ -195,7 +195,7 @@ func (c *Context) RemoveSessionCookie(w http.ResponseWriter, r *http.Request) {
subpath, _ := utils.GetSubpathFromConfig(c.App.Config())
cookie := &http.Cookie{
Name: model.SESSION_COOKIE_TOKEN,
Name: model.SessionCookieToken,
Value: "",
Path: subpath,
MaxAge: -1,
@@ -235,9 +235,9 @@ func (c *Context) SetCommandNotFoundError() {
func (c *Context) HandleEtag(etag string, routeName string, w http.ResponseWriter, r *http.Request) bool {
metrics := c.App.Metrics()
if et := r.Header.Get(model.HEADER_ETAG_CLIENT); etag != "" {
if et := r.Header.Get(model.HeaderEtagClient); etag != "" {
if et == etag {
w.Header().Set(model.HEADER_ETAG_SERVER, etag)
w.Header().Set(model.HeaderEtagServer, etag)
w.WriteHeader(http.StatusNotModified)
if metrics != nil {
metrics.IncrementEtagHitCounter(routeName)
@@ -298,7 +298,7 @@ func (c *Context) RequireUserId() *Context {
return c
}
if c.Params.UserId == model.ME {
if c.Params.UserId == model.Me {
c.Params.UserId = c.AppContext.Session().UserId
}
@@ -579,7 +579,7 @@ func (c *Context) RequireEmojiName() *Context {
validName := regexp.MustCompile(`^[a-zA-Z0-9\-\+_]+$`)
if c.Params.EmojiName == "" || len(c.Params.EmojiName) > model.EMOJI_NAME_MAX_LENGTH || !validName.MatchString(c.Params.EmojiName) {
if c.Params.EmojiName == "" || len(c.Params.EmojiName) > model.EmojiNameMaxLength || !validName.MatchString(c.Params.EmojiName) {
c.SetInvalidUrlParam("emoji_name")
}
@@ -733,5 +733,5 @@ func (c *Context) RequireInvoiceId() *Context {
}
func (c *Context) GetRemoteID(r *http.Request) string {
return r.Header.Get(model.HEADER_REMOTECLUSTER_ID)
return r.Header.Get(model.HeaderRemoteclusterId)
}

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

@@ -158,8 +158,8 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
siteURLHeader := app.GetProtocol(r) + "://" + r.Host + subpath
c.SetSiteURLHeader(siteURLHeader)
w.Header().Set(model.HEADER_REQUEST_ID, c.AppContext.RequestId())
w.Header().Set(model.HEADER_VERSION_ID, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.Srv().License() != nil))
w.Header().Set(model.HeaderRequestId, c.AppContext.RequestId())
w.Header().Set(model.HeaderVersionId, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.Srv().License() != nil))
if *c.App.Config().ServiceSettings.TLSStrictTransport {
w.Header().Set("Strict-Transport-Security", fmt.Sprintf("max-age=%d", *c.App.Config().ServiceSettings.TLSStrictTransportMaxAge))
@@ -336,7 +336,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if c.App.Metrics() != nil {
c.App.Metrics().IncrementHttpRequest()
if r.URL.Path != model.API_URL_SUFFIX+"/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)
}
@@ -350,11 +350,11 @@ func (h *Handler) checkCSRFToken(c *Context, r *http.Request, token string, toke
csrfCheckPassed := false
if csrfCheckNeeded {
csrfHeader := r.Header.Get(model.HEADER_CSRF_TOKEN)
csrfHeader := r.Header.Get(model.HeaderCsrfToken)
if csrfHeader == session.GetCSRF() {
csrfCheckPassed = true
} else if r.Header.Get(model.HEADER_REQUESTED_WITH) == model.HEADER_REQUESTED_WITH_XML {
} else if r.Header.Get(model.HeaderRequestedWith) == model.HeaderRequestedWithXml {
// ToDo(DSchalla) 2019/01/04: Remove after deprecation period and only allow CSRF Header (MM-13657)
csrfErrorMessage := "CSRF Header check failed for request - Please upgrade your web application or custom app to set a CSRF Header"

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

@@ -126,7 +126,7 @@ func TestHandlerServeCSRFToken(t *testing.T) {
session := &model.Session{
UserId: th.BasicUser.Id,
CreateAt: model.GetMillis(),
Roles: model.SYSTEM_USER_ROLE_ID,
Roles: model.SystemUserRoleId,
IsOAuth: false,
}
session.GenerateCSRF()
@@ -148,15 +148,15 @@ func TestHandlerServeCSRFToken(t *testing.T) {
}
cookie := &http.Cookie{
Name: model.SESSION_COOKIE_USER,
Name: model.SessionCookieUser,
Value: th.BasicUser.Username,
}
cookie2 := &http.Cookie{
Name: model.SESSION_COOKIE_TOKEN,
Name: model.SessionCookieToken,
Value: session.Token,
}
cookie3 := &http.Cookie{
Name: model.SESSION_COOKIE_CSRF,
Name: model.SessionCookieCsrf,
Value: session.GetCSRF(),
}
@@ -166,7 +166,7 @@ func TestHandlerServeCSRFToken(t *testing.T) {
request.AddCookie(cookie)
request.AddCookie(cookie2)
request.AddCookie(cookie3)
request.Header.Add(model.HEADER_CSRF_TOKEN, session.GetCSRF())
request.Header.Add(model.HeaderCsrfToken, session.GetCSRF())
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
@@ -196,7 +196,7 @@ func TestHandlerServeCSRFToken(t *testing.T) {
request.AddCookie(cookie)
request.AddCookie(cookie2)
request.AddCookie(cookie3)
request.Header.Add(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML)
request.Header.Add(model.HeaderRequestedWith, model.HeaderRequestedWithXml)
response = httptest.NewRecorder()
handler.ServeHTTP(response, request)
@@ -233,7 +233,7 @@ func TestHandlerServeCSRFToken(t *testing.T) {
request.AddCookie(cookie)
request.AddCookie(cookie2)
request.AddCookie(cookie3)
request.Header.Add(model.HEADER_CSRF_TOKEN, session.GetCSRF())
request.Header.Add(model.HeaderCsrfToken, session.GetCSRF())
response = httptest.NewRecorder()
handlerNoSession.ServeHTTP(response, request)
@@ -392,7 +392,7 @@ func TestHandlerServeInvalidToken(t *testing.T) {
}
cookie := &http.Cookie{
Name: model.SESSION_COOKIE_TOKEN,
Name: model.SessionCookieToken,
Value: "invalid",
}
@@ -426,7 +426,7 @@ func TestCheckCSRFToken(t *testing.T) {
AppContext: th.Context,
}
r, _ := http.NewRequest(http.MethodPost, "", nil)
r.Header.Set(model.HEADER_CSRF_TOKEN, token)
r.Header.Set(model.HeaderCsrfToken, token)
session := &model.Session{
Props: map[string]string{
"csrf": token,
@@ -458,7 +458,7 @@ func TestCheckCSRFToken(t *testing.T) {
AppContext: th.Context,
}
r, _ := http.NewRequest(http.MethodPost, "", nil)
r.Header.Set(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML)
r.Header.Set(model.HeaderRequestedWith, model.HeaderRequestedWithXml)
session := &model.Session{
Props: map[string]string{
"csrf": token,
@@ -508,7 +508,7 @@ func TestCheckCSRFToken(t *testing.T) {
AppContext: th.Context,
}
r, _ := http.NewRequest(http.MethodPost, "", nil)
r.Header.Set(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML)
r.Header.Set(model.HeaderRequestedWith, model.HeaderRequestedWithXml)
session := &model.Session{
Props: map[string]string{
"csrf": token,
@@ -629,7 +629,7 @@ func TestCheckCSRFToken(t *testing.T) {
AppContext: th.Context,
}
r, _ := http.NewRequest(http.MethodPost, "", nil)
r.Header.Set(model.HEADER_CSRF_TOKEN, token)
r.Header.Set(model.HeaderCsrfToken, token)
checked, passed := h.checkCSRFToken(c, r, token, tokenLocation, nil)
@@ -655,7 +655,7 @@ func TestCheckCSRFToken(t *testing.T) {
AppContext: th.Context,
}
r, _ := http.NewRequest(http.MethodPost, "", nil)
r.Header.Set(model.HEADER_CSRF_TOKEN, token)
r.Header.Set(model.HeaderCsrfToken, token)
session := &model.Session{
Props: map[string]string{
"csrf": token,

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

@@ -56,7 +56,7 @@ func authorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) {
}
if c.AppContext.Session().IsOAuth {
c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS)
c.SetPermissionError(model.PermissionEditOtherUsers)
c.Err.DetailedError += ", attempted access by oauth app"
return
}
@@ -136,7 +136,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) {
// here we should check if the user is logged in
if c.AppContext.Session().UserId == "" {
if loginHint == model.USER_AUTH_SERVICE_SAML {
if loginHint == model.UserAuthServiceSaml {
http.Redirect(w, r, c.GetSiteURLHeader()+"/login/sso/saml?redirect_to="+url.QueryEscape(r.RequestURI), http.StatusFound)
} else {
http.Redirect(w, r, c.GetSiteURLHeader()+"/login?redirect_to="+url.QueryEscape(r.RequestURI), http.StatusFound)
@@ -156,7 +156,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) {
isAuthorized := false
if _, err := c.App.GetPreferenceByCategoryAndNameForUser(c.AppContext.Session().UserId, model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, authRequest.ClientId); err == nil {
if _, err := c.App.GetPreferenceByCategoryAndNameForUser(c.AppContext.Session().UserId, model.PreferenceCategoryAuthorizedOAuthApp, authRequest.ClientId); err == nil {
// when we support scopes we should check if the scopes match
isAuthorized = true
}
@@ -179,7 +179,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache, max-age=31556926")
staticDir, _ := fileutils.FindDir(model.CLIENT_DIR)
staticDir, _ := fileutils.FindDir(model.ClientDir)
http.ServeFile(w, r, filepath.Join(staticDir, "root.html"))
}
@@ -191,12 +191,12 @@ func getAccessToken(c *Context, w http.ResponseWriter, r *http.Request) {
grantType := r.FormValue("grant_type")
switch grantType {
case model.ACCESS_TOKEN_GRANT_TYPE:
case model.AccessTokenGrantType:
if code == "" {
c.Err = model.NewAppError("getAccessToken", "api.oauth.get_access_token.missing_code.app_error", nil, "", http.StatusBadRequest)
return
}
case model.REFRESH_TOKEN_GRANT_TYPE:
case model.RefreshTokenGrantType:
if refreshToken == "" {
c.Err = model.NewAppError("getAccessToken", "api.oauth.get_access_token.missing_refresh_token.app_error", nil, "", http.StatusBadRequest)
return
@@ -280,7 +280,7 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
redirectURL := ""
if props != nil {
action = props["action"]
isMobile = action == model.OAUTH_ACTION_MOBILE
isMobile = action == model.OAuthActionMobile
if val, ok := props["redirect_to"]; ok {
redirectURL = val
hasRedirectURL = redirectURL != ""
@@ -310,9 +310,9 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
if action == model.OAUTH_ACTION_EMAIL_TO_SSO {
if action == model.OAuthActionEmailToSSO {
redirectURL = c.GetSiteURLHeader() + "/login?extra=signin_change"
} else if action == model.OAUTH_ACTION_SSO_TO_EMAIL {
} else if action == model.OAuthActionSSOToEmail {
redirectURL = app.GetProtocol(r) + "://" + r.Host + "/claim?email=" + url.QueryEscape(props["email"])
} else {
err = c.App.DoLogin(c.AppContext, w, r, user, "", isMobile, false, false)
@@ -331,8 +331,8 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
// New mobile version
if isMobile && hasRedirectURL {
redirectURL = utils.AppendQueryParamsToURL(redirectURL, map[string]string{
model.SESSION_COOKIE_TOKEN: c.AppContext.Session().Token,
model.SESSION_COOKIE_CSRF: c.AppContext.Session().GetCSRF(),
model.SessionCookieToken: c.AppContext.Session().Token,
model.SessionCookieCsrf: c.AppContext.Session().GetCSRF(),
})
utils.RenderMobileAuthComplete(w, redirectURL)
return
@@ -370,7 +370,7 @@ func loginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
authUrl, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAUTH_ACTION_LOGIN, 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
@@ -399,7 +399,7 @@ func mobileLoginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
authUrl, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAUTH_ACTION_MOBILE, redirectURL, "", true)
authUrl, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionMobile, redirectURL, "", true)
if err != nil {
c.Err = err
return

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

@@ -74,7 +74,7 @@ func TestAuthorizeOAuthApp(t *testing.T) {
require.Nil(t, appErr)
authRequest := &model.AuthorizeRequest{
ResponseType: model.AUTHCODE_RESPONSE_TYPE,
ResponseType: model.AuthCodeResponseType,
ClientId: rapp.Id,
RedirectUri: rapp.CallbackUrls[0],
Scope: "",
@@ -93,7 +93,7 @@ func TestAuthorizeOAuthApp(t *testing.T) {
require.Equal(t, ru.Query().Get("state"), authRequest.State, "returned state doesn't match")
// Test implicit flow
authRequest.ResponseType = model.IMPLICIT_RESPONSE_TYPE
authRequest.ResponseType = model.ImplicitResponseType
ruri, resp = ApiClient.AuthorizeOAuthApp(authRequest)
require.Nil(t, resp.Error)
require.False(t, ruri == "", "redirect url should be set")
@@ -125,7 +125,7 @@ func TestAuthorizeOAuthApp(t *testing.T) {
_, resp = ApiClient.AuthorizeOAuthApp(authRequest)
CheckBadRequestStatus(t, resp)
authRequest.ResponseType = model.AUTHCODE_RESPONSE_TYPE
authRequest.ResponseType = model.AuthCodeResponseType
authRequest.ClientId = ""
_, resp = ApiClient.AuthorizeOAuthApp(authRequest)
CheckBadRequestStatus(t, resp)
@@ -168,7 +168,7 @@ func TestDeauthorizeOAuthApp(t *testing.T) {
require.Nil(t, appErr)
authRequest := &model.AuthorizeRequest{
ResponseType: model.AUTHCODE_RESPONSE_TYPE,
ResponseType: model.AuthCodeResponseType,
ClientId: rapp.Id,
RedirectUri: rapp.CallbackUrls[0],
Scope: "",
@@ -213,8 +213,8 @@ func TestOAuthAccessToken(t *testing.T) {
defer func() {
th.RestoreDefaultRolePermissions(defaultRolePermissions)
}()
th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.TEAM_USER_ROLE_ID)
th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID)
th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.TeamUserRoleId)
th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId)
oauthApp := &model.OAuthApp{
Name: "TestApp5" + model.NewId(),
@@ -234,7 +234,7 @@ func TestOAuthAccessToken(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true })
authRequest := &model.AuthorizeRequest{
ResponseType: model.AUTHCODE_RESPONSE_TYPE,
ResponseType: model.AuthCodeResponseType,
ClientId: oauthApp.Id,
RedirectUri: oauthApp.CallbackUrls[0],
Scope: "all",
@@ -252,7 +252,7 @@ func TestOAuthAccessToken(t *testing.T) {
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - bad grant type")
data.Set("grant_type", model.ACCESS_TOKEN_GRANT_TYPE)
data.Set("grant_type", model.AccessTokenGrantType)
data.Set("client_id", "")
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - missing client id")
@@ -285,7 +285,7 @@ func TestOAuthAccessToken(t *testing.T) {
require.NotNil(t, resp.Error, "should have failed - non-matching redirect uri")
// reset data for successful request
data.Set("grant_type", model.ACCESS_TOKEN_GRANT_TYPE)
data.Set("grant_type", model.AccessTokenGrantType)
data.Set("client_id", oauthApp.Id)
data.Set("client_secret", oauthApp.ClientSecret)
data.Set("code", rurl.Query().Get("code"))
@@ -298,7 +298,7 @@ func TestOAuthAccessToken(t *testing.T) {
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.ACCESS_TOKEN_TYPE, "access token type incorrect")
require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect")
_, err := ApiClient.DoApiGet("/oauth_test", "")
require.Nil(t, err)
@@ -318,7 +318,7 @@ func TestOAuthAccessToken(t *testing.T) {
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - tried to reuse auth code")
data.Set("grant_type", model.REFRESH_TOKEN_GRANT_TYPE)
data.Set("grant_type", model.RefreshTokenGrantType)
data.Set("client_id", oauthApp.Id)
data.Set("client_secret", oauthApp.ClientSecret)
data.Set("refresh_token", "")
@@ -333,7 +333,7 @@ func TestOAuthAccessToken(t *testing.T) {
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.ACCESS_TOKEN_TYPE, "access token type incorrect")
require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect")
ApiClient.SetOAuthToken(rsp.AccessToken)
_, err = ApiClient.DoApiGet("/oauth_test", "")
@@ -345,7 +345,7 @@ func TestOAuthAccessToken(t *testing.T) {
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.ACCESS_TOKEN_TYPE, "access token type incorrect")
require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect")
ApiClient.SetOAuthToken(rsp.AccessToken)
_, err = ApiClient.DoApiGet("/oauth_test", "")
@@ -355,7 +355,7 @@ func TestOAuthAccessToken(t *testing.T) {
_, nErr := th.App.Srv().Store.OAuth().SaveAuthData(authData)
require.NoError(t, nErr)
data.Set("grant_type", model.ACCESS_TOKEN_GRANT_TYPE)
data.Set("grant_type", model.AccessTokenGrantType)
data.Set("client_id", oauthApp.Id)
data.Set("client_secret", oauthApp.ClientSecret)
data.Set("redirect_uri", oauthApp.CallbackUrls[0])
@@ -386,7 +386,7 @@ func TestMobileLoginWithOAuth(t *testing.T) {
buffer := &bytes.Buffer{}
c.Logger = mlog.NewTestingLogger(t, buffer)
provider := &MattermostTestProvider{}
einterfaces.RegisterOauthProvider(model.SERVICE_GITLAB, provider)
einterfaces.RegisterOAuthProvider(model.ServiceGitlab, provider)
t.Run("Should include redirect URL in the output when valid URL Scheme is passed", func(t *testing.T) {
responseWriter := httptest.NewRecorder()
@@ -452,7 +452,7 @@ func TestOAuthComplete(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Id = model.NewId() })
stateProps := map[string]string{}
stateProps["action"] = model.OAUTH_ACTION_LOGIN
stateProps["action"] = model.OAuthActionLogin
stateProps["team_id"] = th.BasicTeam.Id
stateProps["redirect_to"] = *th.App.Config().GitLabSettings.AuthEndpoint
@@ -474,16 +474,16 @@ func TestOAuthComplete(t *testing.T) {
defer func() {
th.RestoreDefaultRolePermissions(defaultRolePermissions)
}()
th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.TEAM_USER_ROLE_ID)
th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID)
th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.TeamUserRoleId)
th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId)
oauthApp := &model.OAuthApp{
Name: "TestApp5" + model.NewId(),
Homepage: "https://nowhere.com",
Description: "test",
CallbackUrls: []string{
ApiClient.Url + "/signup/" + model.SERVICE_GITLAB + "/complete",
ApiClient.Url + "/login/" + model.SERVICE_GITLAB + "/complete",
ApiClient.Url + "/signup/" + model.ServiceGitlab + "/complete",
ApiClient.Url + "/login/" + model.ServiceGitlab + "/complete",
},
CreatorId: th.SystemAdminUser.Id,
IsTrusted: true,
@@ -500,7 +500,7 @@ func TestOAuthComplete(t *testing.T) {
provider := &MattermostTestProvider{}
authRequest := &model.AuthorizeRequest{
ResponseType: model.AUTHCODE_RESPONSE_TYPE,
ResponseType: model.AuthCodeResponseType,
ClientId: oauthApp.Id,
RedirectUri: oauthApp.CallbackUrls[0],
Scope: "all",
@@ -512,31 +512,31 @@ func TestOAuthComplete(t *testing.T) {
rurl, _ := url.Parse(redirect)
code := rurl.Query().Get("code")
stateProps["action"] = model.OAUTH_ACTION_EMAIL_TO_SSO
stateProps["action"] = model.OAuthActionEmailToSSO
delete(stateProps, "team_id")
stateProps["redirect_to"] = *th.App.Config().GitLabSettings.AuthEndpoint
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.SERVICE_GITLAB+"/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.SERVICE_GITLAB, provider)
einterfaces.RegisterOAuthProvider(model.ServiceGitlab, provider)
redirect, resp = ApiClient.AuthorizeOAuthApp(authRequest)
require.Nil(t, resp.Error)
rurl, _ = url.Parse(redirect)
code = rurl.Query().Get("code")
r, err = HttpGet(ApiClient.Url+"/login/"+model.SERVICE_GITLAB+"/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)
}
_, nErr := th.App.Srv().Store.User().UpdateAuthData(
th.BasicUser.Id, model.SERVICE_GITLAB, &th.BasicUser.Email, th.BasicUser.Email, true)
th.BasicUser.Id, model.ServiceGitlab, &th.BasicUser.Email, th.BasicUser.Email, true)
require.NoError(t, nErr)
redirect, resp = ApiClient.AuthorizeOAuthApp(authRequest)
@@ -544,9 +544,9 @@ func TestOAuthComplete(t *testing.T) {
rurl, _ = url.Parse(redirect)
code = rurl.Query().Get("code")
stateProps["action"] = model.OAUTH_ACTION_LOGIN
stateProps["action"] = model.OAuthActionLogin
state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
if r, err := HttpGet(ApiClient.Url+"/login/"+model.SERVICE_GITLAB+"/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)
}
@@ -557,7 +557,7 @@ func TestOAuthComplete(t *testing.T) {
code = rurl.Query().Get("code")
delete(stateProps, "action")
state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
if r, err := HttpGet(ApiClient.Url+"/login/"+model.SERVICE_GITLAB+"/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)
}
@@ -566,9 +566,9 @@ func TestOAuthComplete(t *testing.T) {
rurl, _ = url.Parse(redirect)
code = rurl.Query().Get("code")
stateProps["action"] = model.OAUTH_ACTION_SIGNUP
stateProps["action"] = model.OAuthActionSignup
state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
if r, err := HttpGet(ApiClient.Url+"/login/"+model.SERVICE_GITLAB+"/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)
}
}
@@ -591,7 +591,7 @@ func TestOAuthComplete_ErrorMessages(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Enable = true })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true })
provider := &MattermostTestProvider{}
einterfaces.RegisterOauthProvider(model.SERVICE_GITLAB, provider)
einterfaces.RegisterOAuthProvider(model.ServiceGitlab, provider)
responseWriter := httptest.NewRecorder()
@@ -603,7 +603,7 @@ func TestOAuthComplete_ErrorMessages(t *testing.T) {
// Renders for mobile app with redirect url
stateProps := map[string]string{}
stateProps["action"] = model.OAUTH_ACTION_MOBILE
stateProps["action"] = model.OAuthActionMobile
stateProps["redirect_to"] = th.App.Config().NativeAppSettings.AppCustomURLSchemes[0]
state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
request2, _ := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/signup/gitlab/complete?code=1234&state="+url.QueryEscape(state), nil)
@@ -617,7 +617,7 @@ func HttpGet(url string, httpClient *http.Client, authToken string, followRedire
rq.Close = true
if authToken != "" {
rq.Header.Set(model.HEADER_AUTH, authToken)
rq.Header.Set(model.HeaderAuth, authToken)
}
if !followRedirect {
@@ -710,7 +710,7 @@ func (th *TestHelper) Login(client *model.Client4, user *model.User) {
}
session, _ = th.App.CreateSession(session)
client.AuthToken = session.Token
client.AuthType = model.HEADER_BEARER
client.AuthType = model.HeaderBearer
}
func (th *TestHelper) Logout(client *model.Client4) {

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

@@ -35,7 +35,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
action := r.URL.Query().Get("action")
isMobile := action == model.OAUTH_ACTION_MOBILE
isMobile := action == model.OAuthActionMobile
redirectURL := html.EscapeString(r.URL.Query().Get("redirect_to"))
relayProps := map[string]string{}
relayState := ""
@@ -43,7 +43,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) {
if action != "" {
relayProps["team_id"] = teamId
relayProps["action"] = action
if action == model.OAUTH_ACTION_EMAIL_TO_SSO {
if action == model.OAuthActionEmailToSSO {
relayProps["email"] = r.URL.Query().Get("email")
}
}
@@ -57,7 +57,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) {
relayProps["redirect_to"] = redirectURL
}
relayProps[model.USER_AUTH_SERVICE_IS_MOBILE] = strconv.FormatBool(isMobile)
relayProps[model.UserAuthServiceIsMobile] = strconv.FormatBool(isMobile)
if len(relayProps) > 0 {
relayState = b64.StdEncoding.EncodeToString([]byte(model.MapToJson(relayProps)))
@@ -103,7 +103,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) {
action := relayProps["action"]
auditRec.AddMeta("action", action)
isMobile := action == model.OAUTH_ACTION_MOBILE
isMobile := action == model.OAuthActionMobile
redirectURL := ""
hasRedirectURL := false
if val, ok := relayProps["redirect_to"]; ok {
@@ -136,7 +136,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) {
}
switch action {
case model.OAUTH_ACTION_SIGNUP:
case model.OAuthActionSignup:
if teamId := relayProps["team_id"]; teamId != "" {
if err = c.App.AddUserToTeamByTeamId(c.AppContext, teamId, user); err != nil {
c.LogErrorByCode(err)
@@ -144,7 +144,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) {
}
c.App.AddDirectChannels(teamId, user)
}
case model.OAUTH_ACTION_EMAIL_TO_SSO:
case model.OAuthActionEmailToSSO:
if err = c.App.RevokeAllSessions(user.Id); err != nil {
c.Err = err
return
@@ -154,7 +154,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) {
c.LogAuditWithUserId(user.Id, "Revoked all sessions for user")
c.App.Srv().Go(func() {
if err := c.App.Srv().EmailService.SendSignInChangeEmail(user.Email, strings.Title(model.USER_AUTH_SERVICE_SAML)+" SSO", user.Locale, c.App.GetSiteURL()); err != nil {
if err := c.App.Srv().EmailService.SendSignInChangeEmail(user.Email, strings.Title(model.UserAuthServiceSaml)+" SSO", user.Locale, c.App.GetSiteURL()); err != nil {
c.LogErrorByCode(model.NewAppError("SendSignInChangeEmail", "api.user.send_sign_in_change_email_and_forget.error", nil, err.Error(), http.StatusInternalServerError))
}
})
@@ -179,8 +179,8 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) {
if isMobile {
// Mobile clients with redirect url support
redirectURL = utils.AppendQueryParamsToURL(redirectURL, map[string]string{
model.SESSION_COOKIE_TOKEN: c.AppContext.Session().Token,
model.SESSION_COOKIE_CSRF: c.AppContext.Session().GetCSRF(),
model.SessionCookieToken: c.AppContext.Session().Token,
model.SessionCookieCsrf: c.AppContext.Session().GetCSRF(),
})
utils.RenderMobileAuthComplete(w, redirectURL)
} else {
@@ -192,9 +192,9 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) {
switch action {
// Mobile clients with web view implementation
case model.OAUTH_ACTION_MOBILE:
case model.OAuthActionMobile:
ReturnStatusOK(w)
case model.OAUTH_ACTION_EMAIL_TO_SSO:
case model.OAuthActionEmailToSSO:
http.Redirect(w, r, c.GetSiteURLHeader()+"/login?extra=signin_change", http.StatusFound)
default:
http.Redirect(w, r, c.GetSiteURLHeader(), http.StatusFound)

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

@@ -26,7 +26,7 @@ func (w *Web) InitStatic() {
mlog.Error("Failed to update assets subpath from config", mlog.Err(err))
}
staticDir, _ := fileutils.FindDir(model.CLIENT_DIR)
staticDir, _ := fileutils.FindDir(model.ClientDir)
mlog.Debug("Using client directory", mlog.String("clientDir", staticDir))
subpath, _ := utils.GetSubpathFromConfig(w.app.Config())
@@ -72,7 +72,7 @@ func root(c *Context, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache, max-age=31556926, public")
staticDir, _ := fileutils.FindDir(model.CLIENT_DIR)
staticDir, _ := fileutils.FindDir(model.ClientDir)
http.ServeFile(w, r, filepath.Join(staticDir, "root.html"))
}

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

@@ -102,6 +102,6 @@ func IsOAuthApiCall(a app.AppIface, r *http.Request) bool {
func ReturnStatusOK(w http.ResponseWriter) {
m := make(map[string]string)
m[model.STATUS] = model.STATUS_OK
m[model.STATUS] = model.StatusOk
w.Write([]byte(model.MapToJson(m)))
}

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

@@ -148,15 +148,15 @@ func (th *TestHelper) NewPluginAPI(manifest *model.Manifest) plugin.API {
}
func (th *TestHelper) InitBasic() *TestHelper {
th.SystemAdminUser, _ = th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SYSTEM_ADMIN_ROLE_ID})
th.SystemAdminUser, _ = th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SystemAdminRoleId})
user, _ := th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SYSTEM_USER_ROLE_ID})
user, _ := th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SystemUserRoleId})
team, _ := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: user.Email, Type: model.TEAM_OPEN})
team, _ := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: user.Email, Type: model.TeamOpen})
th.App.JoinUserToTeam(th.Context, team, user, "")
channel, _ := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Test API Name", Name: "zz" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id, CreatorId: user.Id}, true)
channel, _ := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Test API Name", Name: "zz" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id, CreatorId: user.Id}, true)
th.BasicUser = user
th.BasicChannel = channel

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

@@ -134,7 +134,7 @@ func TestIncomingWebhook(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true })
// Read only default channel should fail.
resp, err := http.Post(url, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DEFAULT_CHANNEL)))
resp, err := http.Post(url, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DefaultChannelName)))
require.NoError(t, err)
assert.True(t, resp.StatusCode != http.StatusOK)
@@ -148,7 +148,7 @@ func TestIncomingWebhook(t *testing.T) {
require.Nil(t, appErr)
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.DEFAULT_CHANNEL)))
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)
@@ -232,7 +232,7 @@ func TestIncomingWebhook(t *testing.T) {
})
t.Run("ChannelLockedWebhook", func(t *testing.T) {
channel, err := th.App.CreateChannel(th.Context, &model.Channel{TeamId: th.BasicTeam.Id, Name: model.NewId(), DisplayName: model.NewId(), Type: model.CHANNEL_OPEN, CreatorId: th.BasicUser.Id}, true)
channel, err := th.App.CreateChannel(th.Context, &model.Channel{TeamId: th.BasicTeam.Id, Name: model.NewId(), DisplayName: model.NewId(), Type: model.ChannelTypeOpen, CreatorId: th.BasicUser.Id}, true)
require.Nil(t, err)
hook, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id, ChannelLocked: true})
@@ -271,7 +271,7 @@ func TestCommandWebhooks(t *testing.T) {
CreatorId: th.BasicUser.Id,
TeamId: th.BasicTeam.Id,
URL: "http://nowhere.com",
Method: model.COMMAND_METHOD_POST,
Method: model.CommandMethodPost,
Trigger: "delayed"})
require.Nil(t, appErr)