64 lines
1.2 KiB
Go
64 lines
1.2 KiB
Go
package slash
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
const (
|
|
clientID = "client"
|
|
clientSecret = "secret"
|
|
token = "abcd"
|
|
)
|
|
|
|
func TestOAuth(t *testing.T) {
|
|
s := httptest.NewServer(oauthHandler)
|
|
defer s.Close()
|
|
|
|
client := NewClient(clientID, clientSecret)
|
|
baseEndpoint = s.URL + "/"
|
|
|
|
// OK
|
|
if err := client.checkToken(context.Background()); err != nil {
|
|
t.Log(err)
|
|
t.FailNow()
|
|
}
|
|
if client.oauth.AccessToken != token {
|
|
t.Logf("incorrect access token, got %s but expected %s\n", client.oauth.AccessToken, token)
|
|
}
|
|
|
|
// Rinse
|
|
client.oauth = oauth{}
|
|
|
|
// Not-OK
|
|
client.clientSecret = "public"
|
|
if err := client.checkToken(context.Background()); err == nil {
|
|
t.Log("bad client secret should fail oauth check")
|
|
t.FailNow()
|
|
}
|
|
}
|
|
|
|
var oauthHandler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
|
|
user, pass, ok := r.BasicAuth()
|
|
if !ok {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if user != clientID || pass != clientSecret {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
o := oauth{
|
|
AccessToken: token,
|
|
TokenType: "Bearer",
|
|
ExpiresIn: 60,
|
|
Scope: "360no",
|
|
}
|
|
_ = json.NewEncoder(w).Encode(o)
|
|
}
|