-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
75 lines (63 loc) · 1.88 KB
/
auth.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
package main
import (
"crypto/rand"
"encoding/base64"
"github.com/sirupsen/logrus"
"github.com/thechubbypanda/syncify/config"
"golang.org/x/oauth2"
"net/http"
"strings"
)
var oauthConfig oauth2.Config
func SetOauthConfig(cfg config.Config) {
oauthConfig = oauth2.Config{
ClientID: cfg.ClientID,
ClientSecret: cfg.ClientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: "https://accounts.spotify.com/authorize",
DeviceAuthURL: "",
TokenURL: "https://accounts.spotify.com/api/token",
AuthStyle: 0,
},
RedirectURL: strings.Join([]string{cfg.Url, "callback"}, "/"),
Scopes: []string{"playlist-read-private", "user-library-read", "playlist-modify-private", "playlist-modify-public"},
}
}
func randomState() (string, error) {
var bytes = make([]byte, 32)
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(bytes), nil
}
func Login(w http.ResponseWriter, r *http.Request) {
state, err := randomState()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
logrus.Errorln(err.Error())
return
}
sm.Put(r.Context(), "state", state)
http.Redirect(w, r, oauthConfig.AuthCodeURL(state), http.StatusSeeOther)
}
func Callback(w http.ResponseWriter, r *http.Request) {
state := sm.PopString(r.Context(), "state")
if state == "" || r.URL.Query().Get("state") != state {
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
logrus.Traceln("state did not match:", state)
return
}
token, err := oauthConfig.Exchange(r.Context(), r.URL.Query().Get("code"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
logrus.Errorln(err)
return
}
sm.Put(r.Context(), "token", token)
http.Redirect(w, r, "/", http.StatusFound)
}
func Logout(w http.ResponseWriter, r *http.Request) {
sm.Pop(r.Context(), "token")
http.Redirect(w, r, "/", http.StatusFound)
}