diff --git a/api/user.go b/api/user.go index a42f81cf14..303ec2b0af 100644 --- a/api/user.go +++ b/api/user.go @@ -7,6 +7,7 @@ import ( "bytes" "code.google.com/p/freetype-go/freetype" l4g "code.google.com/p/log4go" + b64 "encoding/base64" "fmt" "github.com/gorilla/mux" "github.com/mattermost/platform/model" @@ -1304,7 +1305,7 @@ func getStatuses(c *Context, w http.ResponseWriter, r *http.Request) { } } -func GetAuthorizationCode(c *Context, w http.ResponseWriter, r *http.Request, teamName, service, redirectUri string) { +func GetAuthorizationCode(c *Context, w http.ResponseWriter, r *http.Request, teamName, service, redirectUri, loginHint string) { if s, ok := utils.Cfg.SSOSettings[service]; !ok || !s.Allow { c.Err = model.NewAppError("GetAuthorizationCode", "Unsupported OAuth service provider", "service="+service) @@ -1314,21 +1315,49 @@ func GetAuthorizationCode(c *Context, w http.ResponseWriter, r *http.Request, te clientId := utils.Cfg.SSOSettings[service].Id endpoint := utils.Cfg.SSOSettings[service].AuthEndpoint - state := model.HashPassword(clientId) + scope := utils.Cfg.SSOSettings[service].Scope + + stateProps := map[string]string{"team": teamName, "hash": model.HashPassword(clientId)} + state := b64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) + + authUrl := endpoint + "?response_type=code&client_id=" + clientId + "&redirect_uri=" + url.QueryEscape(redirectUri) + "&state=" + url.QueryEscape(state) + + if len(scope) > 0 { + authUrl += "&scope=" + utils.UrlEncode(scope) + } + + if len(loginHint) > 0 { + authUrl += "&login_hint=" + utils.UrlEncode(loginHint) + } - authUrl := endpoint + "?response_type=code&client_id=" + clientId + "&redirect_uri=" + url.QueryEscape(redirectUri+"?team="+teamName) + "&state=" + url.QueryEscape(state) http.Redirect(w, r, authUrl, http.StatusFound) } -func AuthorizeOAuthUser(service, code, state, redirectUri string) (io.ReadCloser, *model.AppError) { +func AuthorizeOAuthUser(service, code, state, redirectUri string) (io.ReadCloser, *model.Team, *model.AppError) { if s, ok := utils.Cfg.SSOSettings[service]; !ok || !s.Allow { - return nil, model.NewAppError("AuthorizeOAuthUser", "Unsupported OAuth service provider", "service="+service) + return nil, nil, model.NewAppError("AuthorizeOAuthUser", "Unsupported OAuth service provider", "service="+service) } - if !model.ComparePassword(state, utils.Cfg.SSOSettings[service].Id) { - return nil, model.NewAppError("AuthorizeOAuthUser", "Invalid state", "") + stateStr := "" + if b, err := b64.StdEncoding.DecodeString(state); err != nil { + return nil, nil, model.NewAppError("AuthorizeOAuthUser", "Invalid state", err.Error()) + } else { + stateStr = string(b) } + stateProps := model.MapFromJson(strings.NewReader(stateStr)) + + if !model.ComparePassword(stateProps["hash"], utils.Cfg.SSOSettings[service].Id) { + return nil, nil, model.NewAppError("AuthorizeOAuthUser", "Invalid state", "") + } + + teamName := stateProps["team"] + if len(teamName) == 0 { + return nil, nil, model.NewAppError("AuthorizeOAuthUser", "Invalid state; missing team name", "") + } + + tchan := Srv.Store.Team().GetByName(teamName) + p := url.Values{} p.Set("client_id", utils.Cfg.SSOSettings[service].Id) p.Set("client_secret", utils.Cfg.SSOSettings[service].Secret) @@ -1344,17 +1373,17 @@ func AuthorizeOAuthUser(service, code, state, redirectUri string) (io.ReadCloser var ar *model.AccessResponse if resp, err := client.Do(req); err != nil { - return nil, model.NewAppError("AuthorizeOAuthUser", "Token request failed", err.Error()) + return nil, nil, model.NewAppError("AuthorizeOAuthUser", "Token request failed", err.Error()) } else { ar = model.AccessResponseFromJson(resp.Body) } - if ar.TokenType != model.ACCESS_TOKEN_TYPE { - return nil, model.NewAppError("AuthorizeOAuthUser", "Bad token type", "token_type="+ar.TokenType) + if strings.ToLower(ar.TokenType) != model.ACCESS_TOKEN_TYPE { + return nil, nil, model.NewAppError("AuthorizeOAuthUser", "Bad token type", "token_type="+ar.TokenType) } if len(ar.AccessToken) == 0 { - return nil, model.NewAppError("AuthorizeOAuthUser", "Missing access token", "") + return nil, nil, model.NewAppError("AuthorizeOAuthUser", "Missing access token", "") } p = url.Values{} @@ -1366,9 +1395,13 @@ func AuthorizeOAuthUser(service, code, state, redirectUri string) (io.ReadCloser req.Header.Set("Authorization", "Bearer "+ar.AccessToken) if resp, err := client.Do(req); err != nil { - return nil, model.NewAppError("AuthorizeOAuthUser", "Token request to "+service+" failed", err.Error()) + return nil, nil, model.NewAppError("AuthorizeOAuthUser", "Token request to "+service+" failed", err.Error()) } else { - return resp.Body, nil + if result := <-tchan; result.Err != nil { + return nil, nil, result.Err + } else { + return resp.Body, result.Data.(*model.Team), nil + } } } diff --git a/config/config.json b/config/config.json index c446b517cb..e7134cba56 100644 --- a/config/config.json +++ b/config/config.json @@ -29,9 +29,19 @@ "Allow": false, "Secret" : "", "Id": "", + "Scope": "", "AuthEndpoint": "", "TokenEndpoint": "", "UserApiEndpoint": "" + }, + "google": { + "Allow": false, + "Secret": "", + "Id": "", + "Scope": "email profile", + "AuthEndpoint": "https://accounts.google.com/o/oauth2/auth", + "TokenEndpoint": "https://www.googleapis.com/oauth2/v3/token", + "UserApiEndpoint": "https://www.googleapis.com/plus/v1/people/me" } }, "SqlSettings": { diff --git a/model/gitlab.go b/model/gitlab.go new file mode 100644 index 0000000000..9adcac1894 --- /dev/null +++ b/model/gitlab.go @@ -0,0 +1,57 @@ +// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved. +// See License.txt for license information. + +package model + +import ( + "encoding/json" + "io" + "strconv" + "strings" +) + +const ( + USER_AUTH_SERVICE_GITLAB = "gitlab" +) + +type GitLabUser struct { + Id int64 `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Name string `json:"name"` +} + +func UserFromGitLabUser(glu *GitLabUser) *User { + user := &User{} + user.Username = glu.Username + splitName := strings.Split(glu.Name, " ") + if len(splitName) == 2 { + user.FirstName = splitName[0] + user.LastName = splitName[1] + } else if len(splitName) >= 2 { + user.FirstName = splitName[0] + user.LastName = strings.Join(splitName[1:], " ") + } else { + user.FirstName = glu.Name + } + user.Email = glu.Email + user.AuthData = strconv.FormatInt(glu.Id, 10) + user.AuthService = USER_AUTH_SERVICE_GITLAB + + return user +} + +func GitLabUserFromJson(data io.Reader) *GitLabUser { + decoder := json.NewDecoder(data) + var glu GitLabUser + err := decoder.Decode(&glu) + if err == nil { + return &glu + } else { + return nil + } +} + +func (glu *GitLabUser) GetAuthData() string { + return strconv.FormatInt(glu.Id, 10) +} diff --git a/model/google.go b/model/google.go new file mode 100644 index 0000000000..2a1eb3caa9 --- /dev/null +++ b/model/google.go @@ -0,0 +1,60 @@ +// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved. +// See License.txt for license information. + +package model + +import ( + "encoding/json" + "io" + "strings" +) + +const ( + USER_AUTH_SERVICE_GOOGLE = "google" +) + +type GoogleUser struct { + Id string `json:"id"` + Nickname string `json:"nickname"` + DisplayName string `json:"displayName"` + Emails []map[string]string `json:"emails"` + Names map[string]string `json:"name"` +} + +func UserFromGoogleUser(gu *GoogleUser) *User { + user := &User{} + if len(gu.Nickname) > 0 { + user.Username = gu.Nickname + } else { + user.Username = strings.ToLower(strings.Replace(gu.DisplayName, " ", "", -1)) + } + user.FirstName = gu.Names["givenName"] + user.LastName = gu.Names["familyName"] + user.Nickname = gu.Nickname + + for _, e := range gu.Emails { + if e["type"] == "account" { + user.Email = e["value"] + } + } + + user.AuthData = gu.Id + user.AuthService = USER_AUTH_SERVICE_GOOGLE + + return user +} + +func GoogleUserFromJson(data io.Reader) *GoogleUser { + decoder := json.NewDecoder(data) + var gu GoogleUser + err := decoder.Decode(&gu) + if err == nil { + return &gu + } else { + return nil + } +} + +func (gu *GoogleUser) GetAuthData() string { + return gu.Id +} diff --git a/model/user.go b/model/user.go index ed5161538a..ebefa47628 100644 --- a/model/user.go +++ b/model/user.go @@ -8,24 +8,22 @@ import ( "encoding/json" "io" "regexp" - "strconv" "strings" ) const ( - ROLE_ADMIN = "admin" - ROLE_SYSTEM_ADMIN = "system_admin" - ROLE_SYSTEM_SUPPORT = "system_support" - USER_AWAY_TIMEOUT = 5 * 60 * 1000 // 5 minutes - USER_OFFLINE_TIMEOUT = 1 * 60 * 1000 // 1 minute - USER_OFFLINE = "offline" - USER_AWAY = "away" - USER_ONLINE = "online" - USER_NOTIFY_ALL = "all" - USER_NOTIFY_MENTION = "mention" - USER_NOTIFY_NONE = "none" - BOT_USERNAME = "valet" - USER_AUTH_SERVICE_GITLAB = "gitlab" + ROLE_ADMIN = "admin" + ROLE_SYSTEM_ADMIN = "system_admin" + ROLE_SYSTEM_SUPPORT = "system_support" + USER_AWAY_TIMEOUT = 5 * 60 * 1000 // 5 minutes + USER_OFFLINE_TIMEOUT = 1 * 60 * 1000 // 1 minute + USER_OFFLINE = "offline" + USER_AWAY = "away" + USER_ONLINE = "online" + USER_NOTIFY_ALL = "all" + USER_NOTIFY_MENTION = "mention" + USER_NOTIFY_NONE = "none" + BOT_USERNAME = "valet" ) type User struct { @@ -54,13 +52,6 @@ type User struct { FailedAttempts int `json:"failed_attempts"` } -type GitLabUser struct { - Id int64 `json:"id"` - Username string `json:"username"` - Email string `json:"email"` - Name string `json:"name"` -} - // IsValid validates the user and returns an error if it isn't configured // correctly. func (u *User) IsValid() *AppError { @@ -355,38 +346,3 @@ func IsUsernameValid(username string) bool { return true } - -func UserFromGitLabUser(glu *GitLabUser) *User { - user := &User{} - user.Username = glu.Username - splitName := strings.Split(glu.Name, " ") - if len(splitName) == 2 { - user.FirstName = splitName[0] - user.LastName = splitName[1] - } else if len(splitName) >= 2 { - user.FirstName = splitName[0] - user.LastName = strings.Join(splitName[1:], " ") - } else { - user.FirstName = glu.Name - } - user.Email = glu.Email - user.AuthData = strconv.FormatInt(glu.Id, 10) - user.AuthService = USER_AUTH_SERVICE_GITLAB - - return user -} - -func GitLabUserFromJson(data io.Reader) *GitLabUser { - decoder := json.NewDecoder(data) - var glu GitLabUser - err := decoder.Decode(&glu) - if err == nil { - return &glu - } else { - return nil - } -} - -func (glu *GitLabUser) GetAuthData() string { - return strconv.FormatInt(glu.Id, 10) -} diff --git a/utils/config.go b/utils/config.go index 8d9dd11e0f..a3944f6708 100644 --- a/utils/config.go +++ b/utils/config.go @@ -37,6 +37,7 @@ type SSOSetting struct { Allow bool Secret string Id string + Scope string AuthEndpoint string TokenEndpoint string UserApiEndpoint string diff --git a/web/react/components/login.jsx b/web/react/components/login.jsx index eba4f06f4d..f9eacf0946 100644 --- a/web/react/components/login.jsx +++ b/web/react/components/login.jsx @@ -4,64 +4,62 @@ var utils = require('../utils/utils.jsx'); var client = require('../utils/client.jsx'); var UserStore = require('../stores/user_store.jsx'); -var TeamStore = require('../stores/team_store.jsx'); var BrowserStore = require('../stores/browser_store.jsx'); var Constants = require('../utils/constants.jsx'); module.exports = React.createClass({ handleSubmit: function(e) { e.preventDefault(); - var state = { } + var state = {}; - var name = this.props.teamName + var name = this.props.teamName; if (!name) { - state.server_error = "Bad team name" + state.serverError = 'Bad team name'; this.setState(state); return; } var email = this.refs.email.getDOMNode().value.trim(); if (!email) { - state.server_error = "An email is required" + state.serverError = 'An email is required'; this.setState(state); return; } var password = this.refs.password.getDOMNode().value.trim(); if (!password) { - state.server_error = "A password is required" + state.serverError = 'A password is required'; this.setState(state); return; } if (!BrowserStore.isLocalStorageSupported()) { - state.server_error = "This service requires local storage to be enabled. Please enable it or exit private browsing."; + state.serverError = 'This service requires local storage to be enabled. Please enable it or exit private browsing.'; this.setState(state); return; } - state.server_error = ""; + state.serverError = ''; this.setState(state); client.loginByEmail(name, email, password, - function(data) { + function loggedIn(data) { UserStore.setCurrentUser(data); UserStore.setLastEmail(email); - var redirect = utils.getUrlParameter("redirect"); + var redirect = utils.getUrlParameter('redirect'); if (redirect) { window.location.pathname = decodeURIComponent(redirect); } else { window.location.pathname = '/' + name + '/channels/town-square'; } - - }.bind(this), - function(err) { - if (err.message == "Login failed because email address has not been verified") { + }, + function loginFailed(err) { + if (err.message === 'Login failed because email address has not been verified') { window.location.href = '/verify_email?name=' + encodeURIComponent(name) + '&email=' + encodeURIComponent(email); return; } - state.server_error = err.message; + state.serverError = err.message; this.valid = false; this.setState(state); }.bind(this) @@ -71,10 +69,13 @@ module.exports = React.createClass({ return { }; }, render: function() { - var server_error = this.state.server_error ? : null; - var priorEmail = UserStore.getLastEmail() !== "undefined" ? UserStore.getLastEmail() : "" + var serverError; + if (this.state.serverError) { + serverError = ; + } + var priorEmail = UserStore.getLastEmail(); - var emailParam = utils.getUrlParameter("email"); + var emailParam = utils.getUrlParameter('email'); if (emailParam) { priorEmail = decodeURIComponent(emailParam); } @@ -84,50 +85,62 @@ module.exports = React.createClass({ var focusEmail = false; var focusPassword = false; - if (priorEmail != "") { + if (priorEmail !== '') { focusPassword = true; } else { focusEmail = true; } - var auth_services = JSON.parse(this.props.authServices); + var authServices = JSON.parse(this.props.authServices); - var login_message; - if (auth_services.indexOf("gitlab") >= 0) { - login_message = ( -