forked from RichardKnop/go-oauth2-server
/
client.go
89 lines (74 loc) · 2.27 KB
/
client.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
84
85
86
87
88
89
package oauth
import (
"errors"
"strings"
"github.com/RichardKnop/go-oauth2-server/password"
"github.com/RichardKnop/go-oauth2-server/util"
"github.com/jinzhu/gorm"
)
var (
// ErrClientNotFound ...
ErrClientNotFound = errors.New("Client not found")
// ErrInvalidClientSecret ...
ErrInvalidClientSecret = errors.New("Invalid client secret")
// ErrClientIDTaken ...
ErrClientIDTaken = errors.New("Client ID taken")
)
// ClientExists returns true if client exists
func (s *Service) ClientExists(clientID string) bool {
_, err := s.FindClientByClientID(clientID)
return err == nil
}
// FindClientByClientID looks up a client by client ID
func (s *Service) FindClientByClientID(clientID string) (*Client, error) {
// Client IDs are case insensitive
client := new(Client)
notFound := s.db.Where("key = LOWER(?)", clientID).
First(client).RecordNotFound()
// Not found
if notFound {
return nil, ErrClientNotFound
}
return client, nil
}
// CreateClient saves a new client to database
func (s *Service) CreateClient(clientID, secret, redirectURI string) (*Client, error) {
return s.createClientCommon(s.db, clientID, secret, redirectURI)
}
// CreateClientTx saves a new client to database using injected db object
func (s *Service) CreateClientTx(tx *gorm.DB, clientID, secret, redirectURI string) (*Client, error) {
return s.createClientCommon(tx, clientID, secret, redirectURI)
}
// AuthClient authenticates client
func (s *Service) AuthClient(clientID, secret string) (*Client, error) {
// Fetch the client
client, err := s.FindClientByClientID(clientID)
if err != nil {
return nil, ErrClientNotFound
}
// Verify the secret
if password.VerifyPassword(client.Secret, secret) != nil {
return nil, ErrInvalidClientSecret
}
return client, nil
}
func (s *Service) createClientCommon(db *gorm.DB, clientID, secret, redirectURI string) (*Client, error) {
// Check client ID
if s.ClientExists(clientID) {
return nil, ErrClientIDTaken
}
// Hash password
secretHash, err := password.HashPassword(secret)
if err != nil {
return nil, err
}
client := &Client{
Key: strings.ToLower(clientID),
Secret: string(secretHash),
RedirectURI: util.StringOrNull(redirectURI),
}
if err := db.Create(client).Error; err != nil {
return nil, err
}
return client, nil
}