forked from drone/go-scm
-
Notifications
You must be signed in to change notification settings - Fork 86
/
user.go
83 lines (73 loc) · 1.99 KB
/
user.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2017 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package stash
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"strings"
"github.com/jenkins-x/go-scm/scm"
)
type userService struct {
client *wrapper
}
func (s *userService) Find(ctx context.Context) (*scm.User, *scm.Response, error) {
path := fmt.Sprintf("plugins/servlet/applinks/whoami")
out := new(bytes.Buffer)
res, err := s.client.do(ctx, "GET", path, nil, out)
if err != nil {
return nil, res, err
}
login := out.String()
login = strings.TrimSpace(login)
return s.FindLogin(ctx, login)
}
func (s *userService) FindLogin(ctx context.Context, login string) (*scm.User, *scm.Response, error) {
path := fmt.Sprintf("rest/api/1.0/users/%s", login)
out := new(user)
res, err := s.client.do(ctx, "GET", path, nil, out)
return convertUser(out), res, err
}
func (s *userService) FindEmail(ctx context.Context) (string, *scm.Response, error) {
user, res, err := s.Find(ctx)
var email string
if err == nil {
email = user.Email
}
return email, res, err
}
type user struct {
Name string `json:"name"`
EmailAddress string `json:"emailAddress"`
ID int `json:"id"`
DisplayName string `json:"displayName"`
Active bool `json:"active"`
Slug string `json:"slug"`
Type string `json:"type"`
Links struct {
Self []struct {
Href string `json:"href"`
} `json:"self"`
} `json:"links"`
}
func convertUser(from *user) *scm.User {
if from == nil {
return nil
}
return &scm.User{
Avatar: avatarLink(from.EmailAddress),
Login: from.Slug,
Name: from.DisplayName,
Email: from.EmailAddress,
}
}
func avatarLink(email string) string {
hasher := md5.New()
hasher.Write([]byte(strings.ToLower(email)))
emailHash := fmt.Sprintf("%v", hex.EncodeToString(hasher.Sum(nil)))
avatarURL := fmt.Sprintf("https://www.gravatar.com/avatar/%s.jpg", emailHash)
return avatarURL
}