Skip to content

Commit

Permalink
Merge branch 'main' into bugfix/fixing-unban
Browse files Browse the repository at this point in the history
  • Loading branch information
lleadbet authored Sep 7, 2021
2 parents 6703ecb + 5508e02 commit 24172a7
Show file tree
Hide file tree
Showing 11 changed files with 198 additions and 32 deletions.
4 changes: 2 additions & 2 deletions internal/mock_api/endpoints/bits/cheermotes.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,8 @@ func getCheermotes(w http.ResponseWriter, r *http.Request) {
cheermoteBody = append(cheermoteBody, cheermote)
}

resposne, _ := json.Marshal(cheermoteBody)
w.Write(resposne)
response, _ := json.Marshal(cheermoteBody)
w.Write(response)
}

func generateCheermoteImageSizes(prefix string, theme string, imageType string, bits int) CheermoteImageSizes {
Expand Down
10 changes: 5 additions & 5 deletions internal/mock_api/endpoints/clips/clips.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,21 +92,21 @@ func getClips(w http.ResponseWriter, r *http.Request) {
}

clips := dbr.Data.([]database.Clip)
apiResposne := models.APIResponse{
apiResponse := models.APIResponse{
Data: clips,
}

if len(apiResposne.Data.([]database.Clip)) == 0 {
apiResposne.Data = []string{}
if len(apiResponse.Data.([]database.Clip)) == 0 {
apiResponse.Data = []string{}
}

if dbr.Limit == len(dbr.Data.([]database.Clip)) {
apiResposne.Pagination = &models.APIPagination{
apiResponse.Pagination = &models.APIPagination{
Cursor: dbr.Cursor,
}
}

bytes, _ := json.Marshal(apiResposne)
bytes, _ := json.Marshal(apiResponse)
w.Write(bytes)
}

Expand Down
12 changes: 6 additions & 6 deletions internal/mock_api/endpoints/polls/polls.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,17 @@ func getPolls(w http.ResponseWriter, r *http.Request) {
polls = append(polls, dbr.Data.([]database.Poll)...)
}

apiResposne := models.APIResponse{
apiResponse := models.APIResponse{
Data: polls,
}

if dbr != nil && dbr.Cursor != "" {
apiResposne.Pagination = &models.APIPagination{
apiResponse.Pagination = &models.APIPagination{
Cursor: dbr.Cursor,
}
}

bytes, _ := json.Marshal(apiResposne)
bytes, _ := json.Marshal(apiResponse)
w.Write(bytes)
}

Expand Down Expand Up @@ -231,16 +231,16 @@ func patchPolls(w http.ResponseWriter, r *http.Request) {
return
}

apiResposne := models.APIResponse{
apiResponse := models.APIResponse{
Data: dbr.Data,
}

if dbr.Cursor != "" {
apiResposne.Pagination = &models.APIPagination{
apiResponse.Pagination = &models.APIPagination{
Cursor: dbr.Cursor,
}
}

bytes, _ := json.Marshal(apiResposne)
bytes, _ := json.Marshal(apiResponse)
w.Write(bytes)
}
6 changes: 3 additions & 3 deletions internal/mock_api/endpoints/predictions/predictions.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,17 @@ func getPredictions(w http.ResponseWriter, r *http.Request) {
predictions = append(predictions, dbr.Data.([]database.Prediction)...)
}

apiResposne := models.APIResponse{
apiResponse := models.APIResponse{
Data: predictions,
}

if dbr != nil && dbr.Cursor != "" {
apiResposne.Pagination = &models.APIPagination{
apiResponse.Pagination = &models.APIPagination{
Cursor: dbr.Cursor,
}
}

bytes, _ := json.Marshal(apiResposne)
bytes, _ := json.Marshal(apiResponse)
w.Write(bytes)
}

Expand Down
4 changes: 2 additions & 2 deletions internal/mock_api/endpoints/streams/streamkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ var streamKeyScopesByMethod = map[string][]string{

type StreamKey struct{}

type StreamKeyResposne struct {
type StreamKeyResponse struct {
StreamKey string `json:"stream_key"`
}

Expand Down Expand Up @@ -66,7 +66,7 @@ func getStreamKey(w http.ResponseWriter, r *http.Request) {
return
}

streamKeys := []StreamKeyResposne{{StreamKey: fmt.Sprintf("live_%v_%v", userCtx.UserID, util.RandomGUID())}}
streamKeys := []StreamKeyResponse{{StreamKey: fmt.Sprintf("live_%v_%v", userCtx.UserID, util.RandomGUID())}}

bytes, _ := json.Marshal(models.APIResponse{Data: streamKeys})
w.Write(bytes)
Expand Down
6 changes: 3 additions & 3 deletions internal/mock_api/endpoints/teams/channel_teams.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ var channelTeamsScopesByMethod = map[string][]string{
}

type ChannelTeams struct{}
type ChannelTeamResposne struct {
type ChannelTeamResponse struct {
ID string `json:"id"`
BackgroundImageUrl *string `json:"background_image_url"`
Banner *string `json:"banner"`
Expand Down Expand Up @@ -77,9 +77,9 @@ func getChannelTeams(w http.ResponseWriter, r *http.Request) {
if len(team) == 0 {
dbr.Data = make([]database.Team, 0)
}
response := []ChannelTeamResposne{}
response := []ChannelTeamResponse{}
for _, t := range team {
response = append(response, ChannelTeamResposne{
response = append(response, ChannelTeamResponse{
ID: t.ID,
Info: t.Info,
BackgroundImageUrl: t.BackgroundImageUrl,
Expand Down
50 changes: 41 additions & 9 deletions internal/mock_auth/app_access_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@ import (

type AppAccessTokenEndpoint struct{}

type AppAccessTokenEndpointResposne struct {
type AppAccessTokenRequestBody struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
GrantType string `json:"grant_type"`
Scope string `json:"scope"`
}

type AppAccessTokenEndpointResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
Expand All @@ -33,12 +40,37 @@ func (e AppAccessTokenEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request
return
}

clientID := r.URL.Query().Get("client_id")
clientSecret := r.URL.Query().Get("client_secret")
grantType := r.URL.Query().Get("grant_type")
scope := r.URL.Query().Get("scope")
scopes := strings.Split(scope, " ")
if clientID == "" || clientSecret == "" || grantType != "client_credentials" {
params := AppAccessTokenRequestBody{
ClientID: r.URL.Query().Get("client_id"),
ClientSecret: r.URL.Query().Get("client_secret"),
GrantType: r.URL.Query().Get("grant_type"),
Scope: r.URL.Query().Get("scope"),
}

if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
err := r.ParseForm()
if err != nil {
mock_errors.WriteServerError(w, err.Error())
return
}

if r.Form.Get("client_id") != "" {
params.ClientID = r.Form.Get("client_id")
}
if r.Form.Get("client_secret") != "" {
params.ClientSecret = r.Form.Get("client_secret")
}
if r.Form.Get("grant_type") != "" {
params.GrantType = r.Form.Get("grant_type")
}
if r.Form.Get("scope") != "" {
params.Scope = r.Form.Get("scope")
}
}

scopes := strings.Split(params.Scope, " ")

if params.ClientID == "" || params.ClientSecret == "" || params.GrantType != "client_credentials" {
w.WriteHeader(http.StatusBadRequest)
return
}
Expand All @@ -55,7 +87,7 @@ func (e AppAccessTokenEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request
return
}

res, err := db.NewQuery(r, 10).GetAuthenticationClient(database.AuthenticationClient{ID: clientID, Secret: clientSecret})
res, err := db.NewQuery(r, 10).GetAuthenticationClient(database.AuthenticationClient{ID: params.ClientID, Secret: params.ClientSecret})
if err != nil {
mock_errors.WriteServerError(w, err.Error())
return
Expand All @@ -79,7 +111,7 @@ func (e AppAccessTokenEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request
return
}
ea, _ := time.Parse(time.RFC3339, a.ExpiresAt)
ater := AppAccessTokenEndpointResposne{
ater := AppAccessTokenEndpointResponse{
AccessToken: auth.Token,
RefreshToken: "",
ExpiresIn: int(ea.Sub(time.Now().UTC()).Seconds()),
Expand Down
3 changes: 2 additions & 1 deletion internal/mock_auth/mock_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,9 @@ var validScopesByTokenType = map[string]map[string]bool{

func All() []AuthEndpoint {
return []AuthEndpoint{
UserTokenEndpoint{},
AppAccessTokenEndpoint{},
UserTokenEndpoint{},
ValidateTokenEndpoint{},
}
}

Expand Down
48 changes: 48 additions & 0 deletions internal/mock_auth/mock_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ package mock_auth

import (
"context"
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/twitchdev/twitch-cli/internal/database"
Expand All @@ -19,6 +22,10 @@ var a *assert.Assertions
var firstRun = true
var ac = database.AuthenticationClient{ID: "222", Secret: "333", Name: "test_client", IsExtension: false}

func TestMain(m *testing.M) {

os.Exit(m.Run())
}
func TestAreValidScopes(t *testing.T) {
a := test_setup.SetupTestEnv(t)

Expand Down Expand Up @@ -70,6 +77,46 @@ func TestUserToken(t *testing.T) {
a.Equal(400, resp.StatusCode)
}

func TestValidateToken(t *testing.T) {
a = test_setup.SetupTestEnv(t)
ts := httptest.NewServer(baseMiddleware(ValidateTokenEndpoint{}))

req, _ := http.NewRequest(http.MethodGet, ts.URL+ValidateTokenEndpoint{}.Path(), nil)
resp, err := http.DefaultClient.Do(req)
a.Nil(err, err)
a.Equal(401, resp.StatusCode)

req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", "auth.Token"))
resp, err = http.DefaultClient.Do(req)
a.Nil(err, err)
a.Equal(401, resp.StatusCode)

db, err := database.NewConnection()
a.Nil(err, err)
defer db.DB.Close()

auth, err := db.NewQuery(nil, 0).CreateAuthorization(database.Authorization{
ClientID: ac.ID,
ExpiresAt: util.GetTimestamp().Add(time.Hour * 4).Format(time.RFC3339),
Scopes: "",
})

req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", auth.Token))
resp, err = http.DefaultClient.Do(req)
a.Nil(err, err)
a.Equal(200, resp.StatusCode)

auth, err = db.NewQuery(nil, 0).CreateAuthorization(database.Authorization{
ClientID: ac.ID,
ExpiresAt: util.GetTimestamp().Add(time.Hour * 4).Format(time.RFC3339),
Scopes: "user:read:email",
UserID: "1",
})
req.Header.Set("Authorization", fmt.Sprintf("Oauth %v", auth.Token))
resp, err = http.DefaultClient.Do(req)
a.Nil(err, err)
a.Equal(200, resp.StatusCode)
}
func TestAppAccessToken(t *testing.T) {
a = test_setup.SetupTestEnv(t)
ts := httptest.NewServer(baseMiddleware(AppAccessTokenEndpoint{}))
Expand Down Expand Up @@ -99,6 +146,7 @@ func TestAppAccessToken(t *testing.T) {
a.Nil(err)
a.Equal(200, resp.StatusCode)
}

func baseMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
Expand Down
2 changes: 1 addition & 1 deletion internal/mock_auth/user_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func (e UserTokenEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
ea, _ := time.Parse(time.RFC3339, a.ExpiresAt)
ater := AppAccessTokenEndpointResposne{
ater := AppAccessTokenEndpointResponse{
AccessToken: auth.Token,
RefreshToken: "",
ExpiresIn: int(ea.Sub(time.Now().UTC()).Seconds()),
Expand Down
Loading

0 comments on commit 24172a7

Please sign in to comment.