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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
_ "github.com/lib/pq"
"github.com/gleich/logoru"
"github.com/joho/godotenv"
"golang.org/x/oauth2"
"golang.org/x/oauth2/endpoints"
)
var spotifyConfig oauth2.Config
var db *sql.DB
func Success(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Success!")
}
func LandingPage(w http.ResponseWriter, r *http.Request) {
logoru.Info("Starting auth process")
spotifyUrl := spotifyConfig.AuthCodeURL("zyx")
http.Redirect(w, r, spotifyUrl, http.StatusFound)
}
func Privacy(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "No.")
}
func SpotifyAuth(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
state := r.Form.Get("state")
if state != "zyx" {
http.Error(w, "Invalid State", http.StatusBadRequest)
return
}
code := r.Form.Get("code")
if code == "" {
http.Error(w, "Code not found", http.StatusBadRequest)
return
}
token, err := spotifyConfig.Exchange(context.Background(), code)
if err != nil {
http.Error(w, "Couldn't exchange code", http.StatusInternalServerError)
return
}
var bearer = "Bearer " + token.AccessToken
req, _ := http.NewRequest("GET", "https://api.spotify.com/v1/me", nil)
req.Header.Add("Authorization", bearer)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
logoru.Critical("Couldn't get API information")
http.Error(w, "", http.StatusInternalServerError)
return
}
var generic map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&generic)
if err != nil {
return
}
logoru.Debug(generic)
_, err = db.Exec("INSERT INTO spotify (spotify_username, spotify_token, spotify_token_expires, spotify_refresh_token) VALUES ($1, $2, $3, $4)", generic["display_name"], token.AccessToken, token.Expiry, token.RefreshToken)
if err != nil {
logoru.Error(err.Error())
return
}
http.Redirect(w, r, "/success", http.StatusFound)
}
func main() {
err := godotenv.Load()
if err != nil {
logoru.Critical("Could not load .env")
}
spotifyConfig = oauth2.Config{
ClientID: os.Getenv("SPOTIFY_CLIENT_ID"),
ClientSecret: os.Getenv("SPOTIFY_CLIENT_SECRET"),
Scopes: []string{"user-modify-playback-state", "user-read-playback-state", "user-read-email"},
RedirectURL: fmt.Sprintf("%s/oauth/spotify", os.Getenv("BASE_URL")),
Endpoint: endpoints.Spotify,
}
db, err = sql.Open("postgres", os.Getenv("POSTGRES_URL"))
if err != nil {
logoru.Critical("Could not open database connection")
return
}
http.HandleFunc("/", LandingPage)
http.HandleFunc("/oauth/spotify", SpotifyAuth)
http.HandleFunc("/success", Success)
http.HandleFunc("/privay", Privacy)
logoru.Info("Starting client")
logoru.Critical(http.ListenAndServe(fmt.Sprintf(":%s", os.Getenv("LISTEN_PORT")), nil))
}
|