github.com/larkox/mattermost-server@v5.11.1+incompatible/model/gitlab/gitlab.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package oauthgitlab 5 6 import ( 7 "encoding/json" 8 "io" 9 "strconv" 10 "strings" 11 12 "github.com/mattermost/mattermost-server/einterfaces" 13 "github.com/mattermost/mattermost-server/model" 14 ) 15 16 type GitLabProvider struct { 17 } 18 19 type GitLabUser struct { 20 Id int64 `json:"id"` 21 Username string `json:"username"` 22 Login string `json:"login"` 23 Email string `json:"email"` 24 Name string `json:"name"` 25 } 26 27 func init() { 28 provider := &GitLabProvider{} 29 einterfaces.RegisterOauthProvider(model.USER_AUTH_SERVICE_GITLAB, provider) 30 } 31 32 func userFromGitLabUser(glu *GitLabUser) *model.User { 33 user := &model.User{} 34 username := glu.Username 35 if username == "" { 36 username = glu.Login 37 } 38 user.Username = model.CleanUsername(username) 39 splitName := strings.Split(glu.Name, " ") 40 if len(splitName) == 2 { 41 user.FirstName = splitName[0] 42 user.LastName = splitName[1] 43 } else if len(splitName) >= 2 { 44 user.FirstName = splitName[0] 45 user.LastName = strings.Join(splitName[1:], " ") 46 } else { 47 user.FirstName = glu.Name 48 } 49 user.Email = glu.Email 50 userId := glu.getAuthData() 51 user.AuthData = &userId 52 user.AuthService = model.USER_AUTH_SERVICE_GITLAB 53 54 return user 55 } 56 57 func gitLabUserFromJson(data io.Reader) *GitLabUser { 58 decoder := json.NewDecoder(data) 59 var glu GitLabUser 60 err := decoder.Decode(&glu) 61 if err == nil { 62 return &glu 63 } else { 64 return nil 65 } 66 } 67 68 func (glu *GitLabUser) ToJson() string { 69 b, err := json.Marshal(glu) 70 if err != nil { 71 return "" 72 } else { 73 return string(b) 74 } 75 } 76 77 func (glu *GitLabUser) IsValid() bool { 78 if glu.Id == 0 { 79 return false 80 } 81 82 if len(glu.Email) == 0 { 83 return false 84 } 85 86 return true 87 } 88 89 func (glu *GitLabUser) getAuthData() string { 90 return strconv.FormatInt(glu.Id, 10) 91 } 92 93 func (m *GitLabProvider) GetUserFromJson(data io.Reader) *model.User { 94 glu := gitLabUserFromJson(data) 95 if glu.IsValid() { 96 return userFromGitLabUser(glu) 97 } 98 99 return &model.User{} 100 }