This repository has been archived by the owner on Aug 4, 2021. It is now read-only.
/
api.go
175 lines (149 loc) · 3.96 KB
/
api.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package main
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
"golang.org/x/oauth2"
oauthSpotify "golang.org/x/oauth2/spotify"
)
func RegisterAPI(r gin.IRouter) {
r.GET("/login", Login)
r.GET("/spotify_callback", SpotifyCallback)
r.GET("/token", GetToken)
}
func OauthClient(scopes ...string) *oauth2.Config {
if len(scopes) == 0 {
scopes = append(scopes, "user-read-private")
}
return &oauth2.Config{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
RedirectURL: config.ClientRedirectURL,
Endpoint: oauthSpotify.Endpoint,
Scopes: scopes,
}
}
func GetToken(c *gin.Context) {
tokenID, apiKey, ok := c.Request.BasicAuth()
if !ok {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "request must have basic auth"})
return
}
token := new(Token)
db.First(token, Token{ID: tokenID})
if token.ID == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid auth"})
return
}
if err := bcrypt.CompareHashAndPassword(token.APIKeyHash, []byte(apiKey)); err != nil {
c.Error(err)
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid auth"})
return
}
t, err := Refresh(c, token.IntoOauth())
if err != nil {
c.Error(err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "invalid token"})
return
}
c.JSON(http.StatusOK, t)
}
func Login(c *gin.Context) {
state := NewSignature("login", RandomString())
c.Redirect(http.StatusSeeOther, OauthClient().AuthCodeURL(state))
}
func PostLogin(c *gin.Context, code, sessionID string) {
token, err := OauthClient().Exchange(c, code)
if err != nil {
c.String(http.StatusUnauthorized, "Could not complete authorization: invalid code")
c.Abort()
return
}
id, err := GetSpotifyID(c, token)
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
c.Abort()
return
}
user := new(User)
db.FirstOrCreate(user, User{ID: id})
db.Delete(Session{
UserID: user.ID,
})
db.Create(&Session{
ID: sessionID,
UserID: user.ID,
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
TokenType: token.TokenType,
Expires: token.Expiry,
})
SetSessionCookie(c, sessionID)
c.HTML(http.StatusOK, "redirect.html", gin.H{
"path": "/home",
"text": "Complete Login",
})
}
func CreateToken(c *gin.Context, code, tokenID string) {
token := new(Token)
db.Find(token, Token{ID: tokenID})
if token.ID == "" {
c.String(http.StatusUnauthorized, "Could not complete authorization: invalid state")
c.Abort()
return
}
oauthToken, err := OauthClient().Exchange(c, code)
if err != nil {
c.String(http.StatusUnauthorized, "Could not complete authorization: invalid code")
c.Error(err)
c.Abort()
return
}
apiKey := RandomString()
hash, err := bcrypt.GenerateFromPassword([]byte(apiKey), config.HashCost)
if err != nil {
c.String(http.StatusUnauthorized, "Could not complete authorization: something went wrong creating the token")
c.Error(err)
c.Abort()
return
}
token.APIKeyHash = hash
token.FromOauth(oauthToken)
db.Save(token)
c.HTML(http.StatusOK, "token.html", gin.H{
"name": token.Name,
"id": token.ID,
"apiKey": apiKey,
"scopes": strings.Split(token.Scopes, ","),
})
}
func SpotifyCallback(c *gin.Context) {
if err := c.Query("error"); err != "" {
c.String(http.StatusBadRequest, "Could not complete authorization: %s", err)
c.Abort()
return
}
code := c.Query("code")
if code == "" {
c.String(http.StatusBadRequest, "Could not complete authorization: no auth code present")
c.Abort()
return
}
name, value, ok := ValidSignature(c.Query("state"))
if !ok {
c.String(http.StatusUnauthorized, "Could not complete authorization: invalid state")
c.Abort()
return
}
switch name {
case "login":
PostLogin(c, code, value)
case "token":
CreateToken(c, code, value)
default:
c.String(http.StatusUnauthorized, "Could not complete authorization: invalid state")
c.Abort()
return
}
}