Skip to content

Commit

Permalink
Linted and formatted
Browse files Browse the repository at this point in the history
  • Loading branch information
Martin committed Jul 15, 2014
1 parent 1d1e3a2 commit 2375569
Show file tree
Hide file tree
Showing 10 changed files with 155 additions and 145 deletions.
45 changes: 24 additions & 21 deletions api.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package main

import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/RangelReale/osin"
"github.com/Sirupsen/logrus"
"github.com/nu7hatch/gouuid"
"net/http"
"strings"
"github.com/RangelReale/osin"
"encoding/base64"
)

// APIModifyKeySuccess represents when a Key modification was successful
Expand Down Expand Up @@ -175,7 +175,6 @@ func handleDeleteKey(keyName string) ([]byte, int) {
"key": keyName,
}).Info("Attempted key deletion - success.")


return responseMessage, code
}

Expand Down Expand Up @@ -323,9 +322,10 @@ func createKeyHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, string(responseMessage))
}

// NewClientRequest is an outward facing JSON object translated from osin OAuthClients
type NewClientRequest struct {
ClientRedirectURI string `json:"redirect_uri"`
APIID string `json:"api_id"`
ClientRedirectURI string `json:"redirect_uri"`
APIID string `json:"api_id"`
}

func createOauthClientStorageID(APIID string, clientID string) string {
Expand Down Expand Up @@ -369,8 +369,8 @@ func createOauthClient(w http.ResponseWriter, r *http.Request) {
}

reportableClientData := OAuthClient{
ClientID: newClient.Id,
ClientSecret: newClient.Secret,
ClientID: newClient.Id,
ClientSecret: newClient.Secret,
ClientRedirectURI: newClient.RedirectUri,
}

Expand All @@ -383,7 +383,7 @@ func createOauthClient(w http.ResponseWriter, r *http.Request) {
code = 500
} else {
log.WithFields(logrus.Fields{
"key": newClient.Id,
"key": newClient.Id,
}).Info("New OAuth Client registered successfully.")
}

Expand Down Expand Up @@ -455,8 +455,8 @@ func getOauthClientDetails(keyName string, APIID string) ([]byte, int) {
success = false
} else {
reportableClientData := OAuthClient{
ClientID: thisClientData.Id,
ClientSecret: thisClientData.Secret,
ClientID: thisClientData.Id,
ClientSecret: thisClientData.Secret,
ClientRedirectURI: thisClientData.RedirectUri,
}
responseMessage, err = json.Marshal(&reportableClientData)
Expand All @@ -472,12 +472,12 @@ func getOauthClientDetails(keyName string, APIID string) ([]byte, int) {
responseMessage, _ = json.Marshal(&notFound)
code = 404
log.WithFields(logrus.Fields{
"key": keyName,
}).Info("Attempted oauth client retrieval - failure.")
"key": keyName,
}).Info("Attempted oauth client retrieval - failure.")
} else {
log.WithFields(logrus.Fields{
"key": keyName,
}).Info("Attempted oauth client retrieval - success.")
"key": keyName,
}).Info("Attempted oauth client retrieval - success.")
}

return responseMessage, code
Expand Down Expand Up @@ -515,6 +515,7 @@ func handleDeleteOAuthClient(keyName string, APIID string) ([]byte, int) {

return responseMessage, code
}

// List Clients
func getOauthClients(APIID string) ([]byte, int) {
success := true
Expand All @@ -528,10 +529,10 @@ func getOauthClients(APIID string) ([]byte, int) {
success = false
} else {
clients := []OAuthClient{}
for _, osinClient := range(*thisClientData) {
for _, osinClient := range *thisClientData {
reportableClientData := OAuthClient{
ClientID: osinClient.Id,
ClientSecret: osinClient.Secret,
ClientID: osinClient.Id,
ClientSecret: osinClient.Secret,
ClientRedirectURI: osinClient.RedirectUri,
}
clients = append(clients, reportableClientData)
Expand All @@ -550,17 +551,19 @@ func getOauthClients(APIID string) ([]byte, int) {
responseMessage, _ = json.Marshal(&notFound)
code = 404
log.WithFields(logrus.Fields{
"API": APIID,
}).Info("Attempted oauth client retrieval - failure.")
"API": APIID,
}).Info("Attempted oauth client retrieval - failure.")
} else {
log.WithFields(logrus.Fields{
"API": APIID,
}).Info("Attempted oauth clients retrieval - success.")
"API": APIID,
}).Info("Attempted oauth clients retrieval - success.")
}

return responseMessage, code
}

// MakeNewOsinServer creates a generic osinStorage object, used primarily by the API to create and get keys outside of an APISpec context.
// This is not ideal, but is only used in the Tyk API and nowhere else.
func MakeNewOsinServer() *RedisOsinStorageInterface {
log.Info("Creating generic redis OAuth connection")
storageManager := RedisStorageManager{KeyPrefix: ""}
Expand Down
21 changes: 10 additions & 11 deletions api_definition_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"encoding/json"
"github.com/RangelReale/osin"
"io/ioutil"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
Expand All @@ -10,23 +11,22 @@ import (
"regexp"
"strings"
"time"
"github.com/RangelReale/osin"
)

// APIDefinition represents the configuration for a single proxied API and it's versions.
type APIDefinition struct {
ID bson.ObjectId `bson:"_id,omitempty" json:"id"`
Name string `bson:"name" json:"name"`
APIID string `bson:"api_id" json:"api_id"`
OrgID string `bson:"org_id" json:"org_id"`
UseOauth2 bool `bson:"use_oauth2" json:"use_oauth2"`
ID bson.ObjectId `bson:"_id,omitempty" json:"id"`
Name string `bson:"name" json:"name"`
APIID string `bson:"api_id" json:"api_id"`
OrgID string `bson:"org_id" json:"org_id"`
UseOauth2 bool `bson:"use_oauth2" json:"use_oauth2"`
Oauth2Meta struct {
AllowedAccessTypes []osin.AccessRequestType `bson:"allowed_access_types" json:"allowed_access_types"`
AllowedAuthorizeTypes []osin.AuthorizeRequestType `bson:"allowed_authorize_types" json:"allowed_authorize_types"`
AuthorizeLoginRedirect string `bson:"auth_login_redirect" json:"auth_login_redirect"`
AllowedAccessTypes []osin.AccessRequestType `bson:"allowed_access_types" json:"allowed_access_types"`
AllowedAuthorizeTypes []osin.AuthorizeRequestType `bson:"allowed_authorize_types" json:"allowed_authorize_types"`
AuthorizeLoginRedirect string `bson:"auth_login_redirect" json:"auth_login_redirect"`
} `bson:"oauth_meta" json:"oauth_meta"`
NotificationsDetails NotificationsManager `bson:"notifications" json:"notifications"`
VersionDefinition struct {
VersionDefinition struct {
Location string `bson:"location" json:"location"`
Key string `bson:"key" json:"key"`
} `bson:"definition" json:"definition"`
Expand Down Expand Up @@ -208,7 +208,6 @@ func (a *APIDefinitionLoader) getPathSpecs(apiVersionDef VersionInfo) ([]URLSpec
return combinedPath, false
}


func (a *APIDefinitionLoader) compilePathSpec(paths []string, specType URLStatus) []URLSpec {

// transform a configuration URL into an array of URLSpecs
Expand Down
10 changes: 5 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ package main

import (
"fmt"
"github.com/RangelReale/osin"
"github.com/Sirupsen/logrus"
"github.com/buger/goterm"
"github.com/docopt/docopt.go"
"github.com/RangelReale/osin"
"github.com/justinas/alice"
"github.com/rcrowley/goagain"
"html/template"
Expand All @@ -29,9 +29,9 @@ var genericOsinStorage *RedisOsinStorageInterface

// Generic system error
const (
E_SYSTEM_ERROR string = "{\"status\": \"system error, please contact administrator\"}"
OAUTH_AUTH_CODE_TIMEOUT int = 60 * 60
OAUTH_PREFIX string = "oauth-data."
E_SYSTEM_ERROR string = "{\"status\": \"system error, please contact administrator\"}"
OAUTH_AUTH_CODE_TIMEOUT int = 60 * 60
OAUTH_PREFIX string = "oauth-data."
)

// Display introductory details
Expand Down Expand Up @@ -131,7 +131,7 @@ func addOAuthHandlers(spec APISpec, Muxer *http.ServeMux, test bool) {

serverConfig := osin.NewServerConfig()
serverConfig.ErrorStatusCode = 403
serverConfig.AllowedAccessTypes = spec.Oauth2Meta.AllowedAccessTypes //osin.AllowedAccessType{osin.AUTHORIZATION_CODE, osin.REFRESH_TOKEN}
serverConfig.AllowedAccessTypes = spec.Oauth2Meta.AllowedAccessTypes //osin.AllowedAccessType{osin.AUTHORIZATION_CODE, osin.REFRESH_TOKEN}
serverConfig.AllowedAuthorizeTypes = spec.Oauth2Meta.AllowedAuthorizeTypes // osin.AllowedAuthorizeType{osin.CODE, osin.TOKEN}

OAuthPrefix := OAUTH_PREFIX + spec.APIID + "."
Expand Down
2 changes: 1 addition & 1 deletion middleware_api_security_handler.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package main

import (
"net/http"
"fmt"
"net/http"
)

// CheckIsAPIOwner will ensure that the accessor of the tyk API has the correct security credentials - this is a
Expand Down
11 changes: 5 additions & 6 deletions middleware_oauth2_key_exists.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ import (
"github.com/Sirupsen/logrus"
"github.com/gorilla/context"
"strings"

)

// KeyExists will check if the key being used to access the API is in the request data,
// Oauth2KeyExists will check if the key being used to access the API is in the request data,
// and then if the key is in the storage engine
type Oauth2KeyExists struct {
TykMiddleware
Expand Down Expand Up @@ -51,14 +50,14 @@ func (k Oauth2KeyExists) New() func(http.Handler) http.Handler {
return
}

access_token := parts[1]
keyExists, thisSessionState := authManager.IsKeyAuthorised(access_token)
accessToken := parts[1]
keyExists, thisSessionState := authManager.IsKeyAuthorised(accessToken)

if !keyExists {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": r.RemoteAddr,
"key": access_token,
"key": accessToken,
}).Info("Attempted access with non-existent key.")

handler := ErrorHandler{k.TykMiddleware}
Expand All @@ -68,7 +67,7 @@ func (k Oauth2KeyExists) New() func(http.Handler) http.Handler {

// Set session state on context, we will need it later
context.Set(r, SessionData, thisSessionState)
context.Set(r, AuthHeaderValue, access_token)
context.Set(r, AuthHeaderValue, accessToken)

// Request is valid, carry on
h.ServeHTTP(w, r)
Expand Down
22 changes: 12 additions & 10 deletions notifications.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
package main

import(
"time"
import (
"github.com/franela/goreq"
"time"
)

type NotificationsManager struct{
SharedSecret string `bson:"shared_secret" json:"shared_secret"`
OAuthKeyChangeURL string `bson:"oauth_on_keychange_url" json:"oauth_on_keychange_url"`
// NotificationsManager handles sending notifications to OAuth endpoints to notify the provider of key changes.
// TODO: Make this more generic
type NotificationsManager struct {
SharedSecret string `bson:"shared_secret" json:"shared_secret"`
OAuthKeyChangeURL string `bson:"oauth_on_keychange_url" json:"oauth_on_keychange_url"`
}

// SendRequest sends the requested package (as a POST) to the defined
func (n NotificationsManager) SendRequest(wait bool, count int, notification interface{}) {
if wait {
if count < 3 {
Expand All @@ -21,18 +24,17 @@ func (n NotificationsManager) SendRequest(wait bool, count int, notification int
}

req := goreq.Request{
Method: "POST",
Uri: n.OAuthKeyChangeURL,
UserAgent: "Tyk-Gatewy-Notifications",
Method: "POST",
Uri: n.OAuthKeyChangeURL,
UserAgent: "Tyk-Gatewy-Notifications",
ContentType: "application/json",
Body: notification,
Body: notification,
}

req.AddHeader("X-Tyk-Shared-Secret", n.SharedSecret)

resp, reqErr := req.Do()


if reqErr != nil {
log.Error("Request failed, trying again in 10s. Error was: ", reqErr)
count++
Expand Down
Loading

0 comments on commit 2375569

Please sign in to comment.