-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
91 lines (76 loc) · 2.38 KB
/
auth.go
File metadata and controls
91 lines (76 loc) · 2.38 KB
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
package main
import (
"context"
"crypto/sha256"
"crypto/subtle"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"time"
"github.com/zmb3/spotify/v2"
spotifyauth "github.com/zmb3/spotify/v2/auth"
)
type AuthSpotify struct {
client *spotifyauth.Authenticator
state string
ch chan *spotify.Client
URL string
}
func NewAuthSpotify(redirectURL string) *AuthSpotify {
c := spotifyauth.New(
spotifyauth.WithRedirectURL(redirectURL),
spotifyauth.WithScopes(
spotifyauth.ScopeUserReadPrivate,
spotifyauth.ScopePlaylistModifyPublic,
spotifyauth.ScopePlaylistModifyPrivate,
),
spotifyauth.WithClientID(os.Getenv("SPOTIFY_ID")),
spotifyauth.WithClientSecret(os.Getenv("SPOTIFY_SECRET")),
)
a := &AuthSpotify{
client: c,
state: fmt.Sprint(time.Now().Unix() * rand.Int63()),
ch: make(chan *spotify.Client),
}
a.URL = a.client.AuthURL(a.state)
return a
}
func handleAuthSpotify(w http.ResponseWriter, r *http.Request, authURL string) {
http.Redirect(w, r, authURL, http.StatusFound)
}
func completeAuthSpotify(w http.ResponseWriter, r *http.Request, auth *AuthSpotify) {
ctx := context.Background()
tok, err := auth.client.Token(ctx, auth.state, r)
if err != nil {
http.Error(w, "Couldn't get token", http.StatusForbidden)
log.Fatal(err)
}
if st := r.FormValue("state"); st != auth.state {
http.NotFound(w, r)
log.Fatalf("State mismatch: %s != %s\n", st, auth.state)
}
client := spotify.New(auth.client.Client(ctx, tok), spotify.WithRetry(true))
http.Redirect(w, r, r.URL.Hostname()+"/admin", http.StatusFound)
auth.ch <- client
}
func basicAuth(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if ok {
usernameHash := sha256.Sum256([]byte(username))
passwordHash := sha256.Sum256([]byte(password))
expectedUsernameHash := sha256.Sum256([]byte(expectedUsername))
expectedPasswordHash := sha256.Sum256([]byte(expectedPassword))
usernameMatch := (subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:]) == 1)
passwordMatch := (subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:]) == 1)
if usernameMatch && passwordMatch {
next.ServeHTTP(w, r)
return
}
}
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
})
}