github.com/vnforks/kid/v5@v5.22.1-0.20200408055009-b89d99c65676/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/vnforks/kid/v5/einterfaces"
    13  	"github.com/vnforks/kid/v5/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  	user.Email = strings.ToLower(user.Email)
    51  	userId := glu.getAuthData()
    52  	user.AuthData = &userId
    53  	user.AuthService = model.USER_AUTH_SERVICE_GITLAB
    54  
    55  	return user
    56  }
    57  
    58  func gitLabUserFromJson(data io.Reader) *GitLabUser {
    59  	decoder := json.NewDecoder(data)
    60  	var glu GitLabUser
    61  	err := decoder.Decode(&glu)
    62  	if err == nil {
    63  		return &glu
    64  	} else {
    65  		return nil
    66  	}
    67  }
    68  
    69  func (glu *GitLabUser) ToJson() string {
    70  	b, err := json.Marshal(glu)
    71  	if err != nil {
    72  		return ""
    73  	} else {
    74  		return string(b)
    75  	}
    76  }
    77  
    78  func (glu *GitLabUser) IsValid() bool {
    79  	if glu.Id == 0 {
    80  		return false
    81  	}
    82  
    83  	if len(glu.Email) == 0 {
    84  		return false
    85  	}
    86  
    87  	return true
    88  }
    89  
    90  func (glu *GitLabUser) getAuthData() string {
    91  	return strconv.FormatInt(glu.Id, 10)
    92  }
    93  
    94  func (m *GitLabProvider) GetUserFromJson(data io.Reader) *model.User {
    95  	glu := gitLabUserFromJson(data)
    96  	if glu.IsValid() {
    97  		return userFromGitLabUser(glu)
    98  	}
    99  
   100  	return &model.User{}
   101  }