diff --git a/api/user.go b/api/user.go index 7035613ea2..e1d5e83dd9 100644 --- a/api/user.go +++ b/api/user.go @@ -20,6 +20,7 @@ import ( _ "image/gif" _ "image/jpeg" "image/png" + "io" "net/http" "net/url" "strconv" @@ -80,36 +81,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) { hash := r.URL.Query().Get("h") - shouldVerifyHash := true - - if team.Type == model.TEAM_INVITE && len(team.AllowedDomains) > 0 && len(hash) == 0 { - domains := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(team.AllowedDomains, "@", " ", -1), ",", " ", -1)))) - - matched := false - for _, d := range domains { - if strings.HasSuffix(user.Email, "@"+d) { - matched = true - break - } - } - - if matched { - shouldVerifyHash = false - } else { - c.Err = model.NewAppError("createUser", "The signup link does not appear to be valid", "allowed domains failed") - return - } - } - - if team.Type == model.TEAM_OPEN { - shouldVerifyHash = false - } - - if len(hash) > 0 { - shouldVerifyHash = true - } - - if shouldVerifyHash { + if IsVerifyHashRequired(user, team, hash) { data := r.URL.Query().Get("d") props := model.MapFromJson(strings.NewReader(data)) @@ -133,6 +105,10 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) { user.EmailVerified = true } + if len(user.AuthData) > 0 && len(user.AuthService) > 0 { + user.EmailVerified = true + } + ruser := CreateUser(c, team, user) if c.Err != nil { return @@ -142,6 +118,38 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) { } +func IsVerifyHashRequired(user *model.User, team *model.Team, hash string) bool { + shouldVerifyHash := true + + if team.Type == model.TEAM_INVITE && len(team.AllowedDomains) > 0 && len(hash) == 0 && user != nil { + domains := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(team.AllowedDomains, "@", " ", -1), ",", " ", -1)))) + + matched := false + for _, d := range domains { + if strings.HasSuffix(user.Email, "@"+d) { + matched = true + break + } + } + + if matched { + shouldVerifyHash = false + } else { + return true + } + } + + if team.Type == model.TEAM_OPEN { + shouldVerifyHash = false + } + + if len(hash) > 0 { + shouldVerifyHash = true + } + + return shouldVerifyHash +} + func CreateValet(c *Context, team *model.Team) *model.User { valet := &model.User{} valet.TeamId = team.Id @@ -233,80 +241,77 @@ func FireAndForgetVerifyEmail(userId, name, email, teamDisplayName, teamURL stri }() } -func login(c *Context, w http.ResponseWriter, r *http.Request) { - props := model.MapFromJson(r.Body) - - extraInfo := "" - var result store.StoreResult - - if len(props["id"]) != 0 { - extraInfo = props["id"] - if result = <-Srv.Store.User().Get(props["id"]); result.Err != nil { - c.Err = result.Err - return +func LoginById(c *Context, w http.ResponseWriter, r *http.Request, userId, password, deviceId string) *model.User { + if result := <-Srv.Store.User().Get(userId); result.Err != nil { + c.Err = result.Err + return nil + } else { + user := result.Data.(*model.User) + if checkUserPassword(c, user, password) { + Login(c, w, r, user, deviceId) + return user } } + return nil +} + +func LoginByEmail(c *Context, w http.ResponseWriter, r *http.Request, email, name, password, deviceId string) *model.User { var team *model.Team - if result.Data == nil && len(props["email"]) != 0 && len(props["name"]) != 0 { - extraInfo = props["email"] + " in " + props["name"] - if nr := <-Srv.Store.Team().GetByName(props["name"]); nr.Err != nil { - c.Err = nr.Err - return - } else { - team = nr.Data.(*model.Team) + if result := <-Srv.Store.Team().GetByName(name); result.Err != nil { + c.Err = result.Err + return nil + } else { + team = result.Data.(*model.Team) + } - if result = <-Srv.Store.User().GetByEmail(team.Id, props["email"]); result.Err != nil { - c.Err = result.Err - return - } + if result := <-Srv.Store.User().GetByEmail(team.Id, email); result.Err != nil { + c.Err = result.Err + return nil + } else { + user := result.Data.(*model.User) + + if checkUserPassword(c, user, password) { + Login(c, w, r, user, deviceId) + return user } } - if result.Data == nil { - c.Err = model.NewAppError("login", "Login failed because we couldn't find a valid account", extraInfo) - c.Err.StatusCode = http.StatusBadRequest - return - } - - user := result.Data.(*model.User) - - if team == nil { - if tResult := <-Srv.Store.Team().Get(user.TeamId); tResult.Err != nil { - c.Err = tResult.Err - return - } else { - team = tResult.Data.(*model.Team) - } + return nil +} + +func checkUserPassword(c *Context, user *model.User, password string) bool { + if !model.ComparePassword(user.Password, password) { + c.LogAuditWithUserId(user.Id, "fail") + c.Err = model.NewAppError("checkUserPassword", "Login failed because of invalid password", "user_id="+user.Id) + c.Err.StatusCode = http.StatusForbidden + return false } + return true +} +// User MUST be validated before calling Login +func Login(c *Context, w http.ResponseWriter, r *http.Request, user *model.User, deviceId string) { c.LogAuditWithUserId(user.Id, "attempt") - if !model.ComparePassword(user.Password, props["password"]) { - c.LogAuditWithUserId(user.Id, "fail") - c.Err = model.NewAppError("login", "Login failed because of invalid password", extraInfo) - c.Err.StatusCode = http.StatusForbidden - return - } - if !user.EmailVerified && !utils.Cfg.EmailSettings.ByPassEmail { - c.Err = model.NewAppError("login", "Login failed because email address has not been verified", extraInfo) + c.Err = model.NewAppError("Login", "Login failed because email address has not been verified", "user_id="+user.Id) c.Err.StatusCode = http.StatusForbidden return } if user.DeleteAt > 0 { - c.Err = model.NewAppError("login", "Login failed because your account has been set to inactive. Please contact an administrator.", extraInfo) + c.Err = model.NewAppError("Login", "Login failed because your account has been set to inactive. Please contact an administrator.", "user_id="+user.Id) c.Err.StatusCode = http.StatusForbidden return } - session := &model.Session{UserId: user.Id, TeamId: team.Id, Roles: user.Roles, DeviceId: props["device_id"]} + session := &model.Session{UserId: user.Id, TeamId: user.TeamId, Roles: user.Roles, DeviceId: deviceId} maxAge := model.SESSION_TIME_WEB_IN_SECS - if len(props["device_id"]) > 0 { + if len(deviceId) > 0 { session.SetExpireInDays(model.SESSION_TIME_MOBILE_IN_DAYS) maxAge = model.SESSION_TIME_MOBILE_IN_SECS } else { @@ -357,12 +362,41 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) { } http.SetCookie(w, sessionCookie) - user.Sanitize(map[string]bool{}) c.Session = *session c.LogAuditWithUserId(user.Id, "success") +} - w.Write([]byte(result.Data.(*model.User).ToJson())) +func login(c *Context, w http.ResponseWriter, r *http.Request) { + props := model.MapFromJson(r.Body) + + if len(props["password"]) == 0 { + c.Err = model.NewAppError("login", "Password field must not be blank", "") + c.Err.StatusCode = http.StatusForbidden + return + } + + var user *model.User + if len(props["id"]) != 0 { + user = LoginById(c, w, r, props["id"], props["password"], props["device_id"]) + } else if len(props["email"]) != 0 && len(props["name"]) != 0 { + user = LoginByEmail(c, w, r, props["email"], props["name"], props["password"], props["device_id"]) + } else { + c.Err = model.NewAppError("login", "Either user id or team name and user email must be provided", "") + c.Err.StatusCode = http.StatusForbidden + return + } + + if c.Err != nil { + return + } + + if user != nil { + user.Sanitize(map[string]bool{}) + } else { + user = &model.User{} + } + w.Write([]byte(user.ToJson())) } func revokeSession(c *Context, w http.ResponseWriter, r *http.Request) { @@ -793,6 +827,13 @@ func updatePassword(c *Context, w http.ResponseWriter, r *http.Request) { tchan := Srv.Store.Team().Get(user.TeamId) + if user.AuthData != "" { + c.LogAudit("failed - tried to update user password who was logged in through oauth") + c.Err = model.NewAppError("updatePassword", "Update password failed because the user is logged in through an OAuth service", "auth_service="+user.AuthService) + c.Err.StatusCode = http.StatusForbidden + return + } + if !model.ComparePassword(user.Password, currentPassword) { c.Err = model.NewAppError("updatePassword", "Update password failed because of invalid password", "") c.Err.StatusCode = http.StatusForbidden @@ -1212,3 +1253,72 @@ func getStatuses(c *Context, w http.ResponseWriter, r *http.Request) { return } } + +func GetAuthorizationCode(c *Context, w http.ResponseWriter, r *http.Request, teamName, service, redirectUri string) { + + if s, ok := utils.Cfg.SSOSettings[service]; !ok || !s.Allow { + c.Err = model.NewAppError("GetAuthorizationCode", "Unsupported OAuth service provider", "service="+service) + c.Err.StatusCode = http.StatusBadRequest + return + } + + clientId := utils.Cfg.SSOSettings[service].Id + endpoint := utils.Cfg.SSOSettings[service].AuthEndpoint + state := model.HashPassword(clientId) + + 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) { + if s, ok := utils.Cfg.SSOSettings[service]; !ok || !s.Allow { + return 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", "") + } + + p := url.Values{} + p.Set("client_id", utils.Cfg.SSOSettings[service].Id) + p.Set("client_secret", utils.Cfg.SSOSettings[service].Secret) + p.Set("code", code) + p.Set("grant_type", model.ACCESS_TOKEN_GRANT_TYPE) + p.Set("redirect_uri", redirectUri) + + client := &http.Client{} + req, _ := http.NewRequest("POST", utils.Cfg.SSOSettings[service].TokenEndpoint, strings.NewReader(p.Encode())) + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + var ar *model.AccessResponse + if resp, err := client.Do(req); err != nil { + return 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 len(ar.AccessToken) == 0 { + return nil, model.NewAppError("AuthorizeOAuthUser", "Missing access token", "") + } + + p = url.Values{} + p.Set("access_token", ar.AccessToken) + req, _ = http.NewRequest("GET", utils.Cfg.SSOSettings[service].UserApiEndpoint, strings.NewReader("")) + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + 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()) + } else { + return resp.Body, nil + } + +} diff --git a/config/config.json b/config/config.json index 085dd6de65..591e384227 100644 --- a/config/config.json +++ b/config/config.json @@ -23,6 +23,16 @@ "UseLocalStorage": true, "StorageDirectory": "./data/" }, + "SSOSettings": { + "gitlab": { + "Allow": false, + "Secret" : "", + "Id": "", + "AuthEndpoint": "", + "TokenEndpoint": "", + "UserApiEndpoint": "" + } + }, "SqlSettings": { "DriverName": "mysql", "DataSource": "mmuser:mostest@tcp(dockerhost:3306)/mattermost_test", diff --git a/config/config_docker.json b/config/config_docker.json index 062cdef653..a9ed98f1ac 100644 --- a/config/config_docker.json +++ b/config/config_docker.json @@ -23,6 +23,16 @@ "UseLocalStorage": true, "StorageDirectory": "/mattermost/data/" }, + "SSOSettings": { + "gitlab": { + "Allow": false, + "Secret" : "", + "Id": "", + "AuthEndpoint": "", + "TokenEndpoint": "", + "UserApiEndpoint": "" + } + }, "SqlSettings": { "DriverName": "mysql", "DataSource": "mmuser:mostest@tcp(localhost:3306)/mattermost_test", diff --git a/model/access.go b/model/access.go new file mode 100644 index 0000000000..f9e36ce07d --- /dev/null +++ b/model/access.go @@ -0,0 +1,41 @@ +// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved. +// See License.txt for license information. + +package model + +import ( + "encoding/json" + "io" +) + +const ( + ACCESS_TOKEN_GRANT_TYPE = "authorization_code" + ACCESS_TOKEN_TYPE = "bearer" +) + +type AccessResponse struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int32 `json:"expires_in"` + RefreshToken string `json:"refresh_token"` +} + +func (ar *AccessResponse) ToJson() string { + b, err := json.Marshal(ar) + if err != nil { + return "" + } else { + return string(b) + } +} + +func AccessResponseFromJson(data io.Reader) *AccessResponse { + decoder := json.NewDecoder(data) + var ar AccessResponse + err := decoder.Decode(&ar) + if err == nil { + return &ar + } else { + return nil + } +} diff --git a/model/user.go b/model/user.go index 727165b8c2..c71d754056 100644 --- a/model/user.go +++ b/model/user.go @@ -8,22 +8,24 @@ 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" + 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" ) type User struct { @@ -35,6 +37,7 @@ type User struct { Username string `json:"username"` Password string `json:"password"` AuthData string `json:"auth_data"` + AuthService string `json:"auth_service"` Email string `json:"email"` EmailVerified bool `json:"email_verified"` Nickname string `json:"nickname"` @@ -50,6 +53,13 @@ type User struct { LastPictureUpdate int64 `json:"last_picture_update"` } +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 { @@ -96,6 +106,22 @@ func (u *User) IsValid() *AppError { return NewAppError("User.IsValid", "Invalid last name", "user_id="+u.Id) } + if len(u.Password) > 128 { + return NewAppError("User.IsValid", "Invalid password", "user_id="+u.Id) + } + + if len(u.AuthData) > 128 { + return NewAppError("User.IsValid", "Invalid auth data", "user_id="+u.Id) + } + + if len(u.AuthData) > 0 && len(u.AuthService) == 0 { + return NewAppError("User.IsValid", "Invalid user, auth data must be set with auth type", "user_id="+u.Id) + } + + if len(u.Password) > 0 && len(u.AuthData) > 0 { + return NewAppError("User.IsValid", "Invalid user, password and auth data cannot both be set", "user_id="+u.Id) + } + return nil } @@ -328,3 +354,38 @@ 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/store/sql_user_store.go b/store/sql_user_store.go index d8ab4482ed..6cf12f5b8b 100644 --- a/store/sql_user_store.go +++ b/store/sql_user_store.go @@ -24,6 +24,7 @@ func NewSqlUserStore(sqlStore *SqlStore) UserStore { table.ColMap("Username").SetMaxSize(64) table.ColMap("Password").SetMaxSize(128) table.ColMap("AuthData").SetMaxSize(128) + table.ColMap("AuthService").SetMaxSize(32) table.ColMap("Email").SetMaxSize(128) table.ColMap("Nickname").SetMaxSize(64) table.ColMap("FirstName").SetMaxSize(64) @@ -57,6 +58,8 @@ func (us SqlUserStore) UpgradeSchemaIfNeeded() { panic("Failed to set last name from nickname " + err.Error()) } } + + us.CreateColumnIfNotExists("Users", "AuthService", "AuthData", "varchar(32)", "") // for OAuth Client } //func (ss SqlStore) CreateColumnIfNotExists(tableName string, columnName string, afterName string, colType string, defaultValue string) bool { @@ -369,6 +372,28 @@ func (us SqlUserStore) GetByEmail(teamId string, email string) StoreChannel { return storeChannel } +func (us SqlUserStore) GetByAuth(teamId string, authData string, authService string) StoreChannel { + + storeChannel := make(StoreChannel) + + go func() { + result := StoreResult{} + + user := model.User{} + + if err := us.GetReplica().SelectOne(&user, "SELECT * FROM Users WHERE TeamId=? AND AuthData=? AND AuthService=?", teamId, authData, authService); err != nil { + result.Err = model.NewAppError("SqlUserStore.GetByAuth", "We couldn't find the existing account", "teamId="+teamId+", authData="+authData+", authService="+authService+", "+err.Error()) + } + + result.Data = &user + + storeChannel <- result + close(storeChannel) + }() + + return storeChannel +} + func (us SqlUserStore) GetByUsername(teamId string, username string) StoreChannel { storeChannel := make(StoreChannel) diff --git a/store/sql_user_store_test.go b/store/sql_user_store_test.go index 12737caa8d..1f94021b28 100644 --- a/store/sql_user_store_test.go +++ b/store/sql_user_store_test.go @@ -236,6 +236,25 @@ func TestUserStoreGetByEmail(t *testing.T) { } } +func TestUserStoreGetByAuthData(t *testing.T) { + Setup() + + u1 := model.User{} + u1.TeamId = model.NewId() + u1.Email = model.NewId() + u1.AuthData = "123" + u1.AuthService = "service" + Must(store.User().Save(&u1)) + + if err := (<-store.User().GetByAuth(u1.TeamId, u1.AuthData, u1.AuthService)).Err; err != nil { + t.Fatal(err) + } + + if err := (<-store.User().GetByAuth("", "", "")).Err; err == nil { + t.Fatal("Should have failed because of missing auth data") + } +} + func TestUserStoreGetByUsername(t *testing.T) { Setup() diff --git a/store/store.go b/store/store.go index 5b0e13fce6..fac3a5bdb2 100644 --- a/store/store.go +++ b/store/store.go @@ -85,6 +85,7 @@ type UserStore interface { Get(id string) StoreChannel GetProfiles(teamId string) StoreChannel GetByEmail(teamId string, email string) StoreChannel + GetByAuth(teamId string, authData string, authService string) StoreChannel GetByUsername(teamId string, username string) StoreChannel VerifyEmail(userId string) StoreChannel GetEtagForProfiles(teamId string) StoreChannel diff --git a/utils/config.go b/utils/config.go index e8fa9a4778..6a428a5c11 100644 --- a/utils/config.go +++ b/utils/config.go @@ -32,6 +32,15 @@ type ServiceSettings struct { StorageDirectory string } +type SSOSetting struct { + Allow bool + Secret string + Id string + AuthEndpoint string + TokenEndpoint string + UserApiEndpoint string +} + type SqlSettings struct { DriverName string DataSource string @@ -109,6 +118,7 @@ type Config struct { EmailSettings EmailSettings PrivacySettings PrivacySettings TeamSettings TeamSettings + SSOSettings map[string]SSOSetting } func (o *Config) ToJson() string { @@ -243,3 +253,14 @@ func IsS3Configured() bool { return true } + +func GetAllowedAuthServices() []string { + authServices := []string{} + for name, service := range Cfg.SSOSettings { + if service.Allow { + authServices = append(authServices, name) + } + } + + return authServices +} diff --git a/web/react/components/login.jsx b/web/react/components/login.jsx index 71fefff5b7..05918650b1 100644 --- a/web/react/components/login.jsx +++ b/web/react/components/login.jsx @@ -90,6 +90,17 @@ module.exports = React.createClass({ focusEmail = true; } + var auth_services = JSON.parse(this.props.authServices); + + var login_message; + if (auth_services.indexOf("gitlab") >= 0) { + login_message = ( +
+ ); + } + return ({"Choose your username and password for the " + this.props.teamDisplayName + " " + strings.Team} {"or sign up with GitLab."}
; + } else { + signup_message ={"Choose your username and password for the " + this.props.teamDisplayName + " " + strings.Team + "."}
; + } return (
{"Choose your username and password for the " + this.props.team_name + " " + strings.Team +"."}
+Your username can be made of lowercase letters and numbers.
+ {"To continue signing up with " + this.state.user.auth_service + ", please register a username."}
+Your username can be made of lowercase letters and numbers.
+ +{"Pick something " + strings.Team + "mates will recognize. Your username is how you will appear to others."}
+{ yourEmailIs } You’ll use this address to sign in to {config.SiteName}.
+ + + { server_error } +By proceeding to create your account and use { config.SiteName }, you agree to our Terms of Service and Privacy Policy. If you do not agree, you cannot use {config.SiteName}.
+