/
oauth.go
95 lines (81 loc) · 2.17 KB
/
oauth.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
90
91
92
93
94
95
/*
* Copyright (c) 2022-2024 Mikhail Knyazhev <markus621@yandex.com>. All rights reserved.
* Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file.
*/
package oauth
import (
"net/http"
"sync"
)
/**********************************************************************************************************************/
type (
ConfigItem struct {
Code string `yaml:"code"`
ClientID string `yaml:"client_id"`
ClientSecret string `yaml:"client_secret"`
RedirectURL string `yaml:"redirect_url"`
}
Config struct {
Provider []ConfigItem `yaml:"oauth"`
}
configIsp struct {
State string
AuthCodeKey string
RequestURL string
}
)
/**********************************************************************************************************************/
type (
OAuth struct {
config *Config
list map[string]Provider
mux sync.RWMutex
}
CallBack func(http.ResponseWriter, *http.Request, User)
)
func New(c *Config) *OAuth {
return &OAuth{
config: c,
list: make(map[string]Provider),
}
}
func (v *OAuth) Up() error {
v.AddProviders(
&IspYandex{},
)
return nil
}
func (v *OAuth) Down() error {
return nil
}
func (v *OAuth) Request(name string) func(http.ResponseWriter, *http.Request) {
p, err := v.GetProvider(name)
if err != nil {
return func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error())) // nolint: errcheck
}
}
return func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, p.AuthCodeURL(), http.StatusMovedPermanently)
}
}
func (v *OAuth) CallBack(name string, call CallBack) func(w http.ResponseWriter, r *http.Request) {
p, err := v.GetProvider(name)
if err != nil {
return func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error())) // nolint: errcheck
}
}
return func(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get(p.AuthCodeKey())
u, err := p.Exchange(r.Context(), code)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error())) // nolint: errcheck
return
}
call(w, r, u)
}
}