summaryrefslogblamecommitdiff
path: root/main.go
blob: 75d5a2d86b18ab2bc7cec37999155924f5a54194 (plain) (tree)



















































































                                                                                                                                                                                                                                     

                                                         










                                                                 
                                                                                                                    

















                                                                                               
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))
}