Skip to content

Commit

Permalink
objx transition
Browse files Browse the repository at this point in the history
  • Loading branch information
tylerb committed Sep 17, 2013
1 parent 473846b commit 9f822f1
Show file tree
Hide file tree
Showing 28 changed files with 166 additions and 166 deletions.
12 changes: 6 additions & 6 deletions README.md
Expand Up @@ -5,7 +5,7 @@ Authentication framework for Go applications.
## Features

* OAuth2 today
* Supports other protocols too
* Supports other protocols too
* [Multiple providers](https://github.com/stretchr/gomniauth/tree/master/providers)
* Comes with Google and GitHub baked in
* Easily extensible
Expand Down Expand Up @@ -37,8 +37,8 @@ First and only once for your application, you need to setup the security key and

You are free to use the [signature package's RandomKey function](http://godoc.org/github.com/stretchr/signature#RandomKey) to generate a unique code every time your application starts.

gomniauth.SetSecurityKey(signature.RandomKey(64))
gomniauth.SetSecurityKey(signature.RandomKey(64))

A provider represents an authentication service that will be available to your users. Usually, you'll have to add some configuration of your own, such as your application `key` and `secret` (provided by the auth service), and the `callback` into your app where users will be sent following successful (or not) authentication.

gomniauth.WithProviders(
Expand Down Expand Up @@ -82,7 +82,7 @@ You should then redirect the user to the `authUrl`.

The `state` parameter is a `State` object that contains information that will be hashed and passed (via the third party) through to your callback (see below). Usually, this object contains the URL to redirect to once authentication has completed, but you can store whatever you like in here.

The `options` parameter is an `objects.Map` containing additional query-string parameters that will be sent to the authentication service. For example, in OAuth2 implementations, you can specify a `scope` parameter to get additional access to other services you might need.
The `options` parameter is an `objx.Map` containing additional query-string parameters that will be sent to the authentication service. For example, in OAuth2 implementations, you can specify a `scope` parameter to get additional access to other services you might need.

### Handling the callback

Expand All @@ -107,8 +107,8 @@ The provider will then do the work in the background to complete the authenticat

If you then want some information about the user who just authenticated, you can call the `GetUser` method on the provider (passing in the `creds` from the `CompleteAuth` method.)

The [User](https://github.com/stretchr/gomniauth/blob/master/common/user.go) you get back will give you access to the common user data you will need (like name, email, avatar URL etc) and also an `objects.Map` of `Data()` that contains everything else.
The [User](https://github.com/stretchr/gomniauth/blob/master/common/user.go) you get back will give you access to the common user data you will need (like name, email, avatar URL etc) and also an `objx.Map` of `Data()` that contains everything else.

### Caching in

Once you had the credentials for a user for a given provider, you should cache them in your own datastore. This will mean that if the cookie hasn't expired, or if the client has stored the auth token, they can continue to use the service without having to log in again.
Once you had the credentials for a user for a given provider, you should cache them in your own datastore. This will mean that if the cookie hasn't expired, or if the client has stored the auth token, they can continue to use the service without having to log in again.
4 changes: 2 additions & 2 deletions common/config.go
@@ -1,11 +1,11 @@
package common

import (
"github.com/stretchr/stew/objects"
"github.com/stretchr/objx"
)

// Config represent data that describes information needed
// to make authenticated requests.
type Config struct {
objects.Map
objx.Map
}
6 changes: 3 additions & 3 deletions common/credentials.go
Expand Up @@ -2,7 +2,7 @@ package common

import (
"fmt"
"github.com/stretchr/stew/objects"
"github.com/stretchr/objx"
"strconv"
)

Expand All @@ -13,7 +13,7 @@ const (
// Credentials represent data that describes information needed
// to make authenticated requests.
type Credentials struct {
objects.Map
objx.Map
}

var EmptyCredentials *Credentials = nil
Expand All @@ -22,7 +22,7 @@ var EmptyCredentials *Credentials = nil
func (c *Credentials) PublicData(options map[string]interface{}) (publicData interface{}, err error) {

// ensure the ID is a string
idValue := c.Map.Get(CredentialsKeyID)
idValue := c.Map.Get(CredentialsKeyID).Data()
var idStringValue string
switch idValue.(type) {
case float64:
Expand Down
8 changes: 4 additions & 4 deletions common/credentials_test.go
Expand Up @@ -3,20 +3,20 @@ package common
import (
"github.com/stretchr/codecs"
"github.com/stretchr/core/stretchr/constants"
"github.com/stretchr/stew/objects"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
"testing"
)

func TestCredentials_PublicData(t *testing.T) {

creds := &Credentials{objects.M(constants.ParamAuthCode, "ABC123", CredentialsKeyID, 123)}
creds := &Credentials{objx.MSI(constants.ParamAuthCode, "ABC123", CredentialsKeyID, 123)}

publicData, _ := codecs.PublicData(creds, nil)

if assert.NotNil(t, publicData) {
assert.Equal(t, "ABC123", publicData.(objects.Map)[constants.ParamAuthCode])
assert.Equal(t, "123", publicData.(objects.Map)[CredentialsKeyID], "CredentialsKeyID ("+CredentialsKeyID+") must be turned into a string.")
assert.Equal(t, "ABC123", publicData.(objx.Map)[constants.ParamAuthCode])
assert.Equal(t, "123", publicData.(objx.Map)[CredentialsKeyID], "CredentialsKeyID ("+CredentialsKeyID+") must be turned into a string.")
}

}
8 changes: 4 additions & 4 deletions common/provider.go
@@ -1,7 +1,7 @@
package common

import (
"github.com/stretchr/stew/objects"
"github.com/stretchr/objx"
"net/http"
)

Expand All @@ -18,20 +18,20 @@ type Provider interface {
// callback endpoint.
// The options argument takes any options used to configure the auth request
// sent to the provider.
GetBeginAuthURL(state *State, options objects.Map) (string, error)
GetBeginAuthURL(state *State, options objx.Map) (string, error)

// CompleteAuth takes a map of arguments that are used to
// complete the authorisation process, completes it, and returns
// the appropriate Credentials.
CompleteAuth(data objects.Map) (*Credentials, error)
CompleteAuth(data objx.Map) (*Credentials, error)

// GetUser uses the specified Credentials to access the users profile
// from the remote provider, and builds the appropriate User object.
GetUser(creds *Credentials) (User, error)

// Get makes an authenticated request and returns the data in the
// response as a data map.
Get(creds *Credentials, endpoint string) (objects.Map, error)
Get(creds *Credentials, endpoint string) (objx.Map, error)

// GetClient gets an http.Client authenticated with the specified
// Credentials.
Expand Down
6 changes: 3 additions & 3 deletions common/state.go
@@ -1,17 +1,17 @@
package common

import (
"github.com/stretchr/stew/objects"
"github.com/stretchr/objx"
)

// State represents a map of state arguments that can be used to
// persist values across the authentication process.
type State struct {
objects.Map
objx.Map
}

// NewState creates a new object that can be used to persist
// state across authentication requests.
func NewState(keyAndValuePairs ...interface{}) *State {
return &State{objects.M(keyAndValuePairs...)}
return &State{objx.MSI(keyAndValuePairs...)}
}
4 changes: 2 additions & 2 deletions common/user.go
@@ -1,7 +1,7 @@
package common

import (
"github.com/stretchr/stew/objects"
"github.com/stretchr/objx"
)

const (
Expand Down Expand Up @@ -33,5 +33,5 @@ type User interface {
AuthCode() string

// Data gets the underlying data that makes up this User.
Data() objects.Map
Data() objx.Map
}
2 changes: 1 addition & 1 deletion example/goweb/main.go
Expand Up @@ -61,7 +61,7 @@ func main() {

// if you want to request additional scopes from the provider,
// pass them as login?scope=scope1,scope2
//options := objects.M("scope", ctx.QueryValue("scope"))
//options := objx.MSI("scope", ctx.QueryValue("scope"))

authUrl, err := provider.GetBeginAuthURL(state, nil)

Expand Down
36 changes: 18 additions & 18 deletions oauth2/complete_auth.go
Expand Up @@ -4,7 +4,7 @@ import (
"encoding/json"
"fmt"
"github.com/stretchr/gomniauth/common"
"github.com/stretchr/stew/objects"
"github.com/stretchr/objx"
"io/ioutil"
"mime"
"net/http"
Expand All @@ -17,10 +17,10 @@ import (
//
// The data must contain an OAuth2KeyCode obtained from the auth
// server.
func CompleteAuth(tripperFactory common.TripperFactory, data objects.Map, config *common.Config, provider common.Provider) (*common.Credentials, error) {
func CompleteAuth(tripperFactory common.TripperFactory, data objx.Map, config *common.Config, provider common.Provider) (*common.Credentials, error) {

// get the code
codeList := data.Get(OAuth2KeyCode)
codeList := data.Get(OAuth2KeyCode).Data()

code, ok := codeList.(string)
if !ok {
Expand All @@ -39,15 +39,15 @@ func CompleteAuth(tripperFactory common.TripperFactory, data objects.Map, config
return nil, clientErr
}

params := objects.M(OAuth2KeyGrantType, OAuth2GrantTypeAuthorizationCode,
OAuth2KeyRedirectUrl, config.GetStringOrEmpty(OAuth2KeyRedirectUrl),
OAuth2KeyScope, config.GetStringOrEmpty(OAuth2KeyScope),
params := objx.MSI(OAuth2KeyGrantType, OAuth2GrantTypeAuthorizationCode,
OAuth2KeyRedirectUrl, config.Get(OAuth2KeyRedirectUrl).Str(),
OAuth2KeyScope, config.Get(OAuth2KeyScope).Str(),
OAuth2KeyCode, code,
OAuth2KeyClientID, config.GetStringOrEmpty(OAuth2KeyClientID),
OAuth2KeySecret, config.GetStringOrEmpty(OAuth2KeySecret))
OAuth2KeyClientID, config.Get(OAuth2KeyClientID).Str(),
OAuth2KeySecret, config.Get(OAuth2KeySecret).Str())

// post the form
response, requestErr := client.PostForm(config.GetString(OAuth2KeyTokenURL), params.URLValues())
response, requestErr := client.PostForm(config.Get(OAuth2KeyTokenURL).Str(), params.URLValues())

if requestErr != nil {
return nil, requestErr
Expand All @@ -72,7 +72,7 @@ func CompleteAuth(tripperFactory common.TripperFactory, data objects.Map, config
}

// prepare the credentials object
creds := &common.Credentials{Map: objects.M()}
creds := &common.Credentials{Map: objx.MSI()}

body, err := ioutil.ReadAll(response.Body)
if err != nil {
Expand All @@ -82,25 +82,25 @@ func CompleteAuth(tripperFactory common.TripperFactory, data objects.Map, config
switch content {
case "application/x-www-form-urlencoded", "text/plain":

vals, err := objects.NewMapFromURLQuery(string(body))
vals, err := objx.FromURLQuery(string(body))
if err != nil {
return nil, err
}

// did an error occur?
if len(vals.GetStringOrEmpty("error")) > 0 {
return nil, &common.AuthServerError{ErrorMessage: vals.GetStringOrEmpty("error")}
if len(vals.Get("error").Str()) > 0 {
return nil, &common.AuthServerError{ErrorMessage: vals.Get("error").Str()}
}

expiresIn, _ := time.ParseDuration(vals.GetStringOrEmpty(OAuth2KeyExpiresIn) + "s")
expiresIn, _ := time.ParseDuration(vals.Get(OAuth2KeyExpiresIn).Str() + "s")

creds.Set(OAuth2KeyAccessToken, vals.GetStringOrEmpty(OAuth2KeyAccessToken))
creds.Set(OAuth2KeyRefreshToken, vals.GetStringOrEmpty(OAuth2KeyRefreshToken))
creds.Set(OAuth2KeyAccessToken, vals.Get(OAuth2KeyAccessToken).Str())
creds.Set(OAuth2KeyRefreshToken, vals.Get(OAuth2KeyRefreshToken).Str())
creds.Set(OAuth2KeyExpiresIn, expiresIn)

default: // use JSON

var data objects.Map
var data objx.Map

jsonErr := json.Unmarshal(body, &data)

Expand All @@ -109,7 +109,7 @@ func CompleteAuth(tripperFactory common.TripperFactory, data objects.Map, config
}

// handle the time
timeDuration := data.Get(OAuth2KeyExpiresIn).(float64)
timeDuration := data.Get(OAuth2KeyExpiresIn).Float64()
data.Set(OAuth2KeyExpiresIn, time.Duration(timeDuration)*time.Second)

// merge this data into the creds
Expand Down
26 changes: 13 additions & 13 deletions oauth2/complete_auth_test.go
Expand Up @@ -3,7 +3,7 @@ package oauth2
import (
"github.com/stretchr/gomniauth/common"
"github.com/stretchr/gomniauth/test"
"github.com/stretchr/stew/objects"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"io/ioutil"
Expand All @@ -16,7 +16,7 @@ import (
func TestOAuth2Provider_CompleteAuth_URLEncodedResponse(t *testing.T) {

config := &common.Config{
Map: objects.M(
Map: objx.MSI(
OAuth2KeyRedirectUrl, OAuth2KeyRedirectUrl,
OAuth2KeyScope, OAuth2KeyScope,
OAuth2KeyClientID, OAuth2KeyClientID,
Expand All @@ -39,15 +39,15 @@ func TestOAuth2Provider_CompleteAuth_URLEncodedResponse(t *testing.T) {
testTripperFactory.On("NewTripper", common.EmptyCredentials, mock.Anything).Return(testTripper, nil)
testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

data := objects.M(OAuth2KeyCode, []string{"123"})
data := objx.MSI(OAuth2KeyCode, []string{"123"})
creds, err := CompleteAuth(testTripperFactory, data, config, testProvider)

if assert.NoError(t, err) {
if assert.NotNil(t, creds, "Creds should be returned") {

assert.Equal(t, creds.GetStringOrEmpty(OAuth2KeyAccessToken), "ACCESSTOKEN")
assert.Equal(t, creds.GetStringOrEmpty(OAuth2KeyRefreshToken), "REFRESHTOKEN")
assert.Equal(t, creds.Get(OAuth2KeyExpiresIn).(time.Duration), 20000000000)
assert.Equal(t, creds.Get(OAuth2KeyAccessToken).Str(), "ACCESSTOKEN")
assert.Equal(t, creds.Get(OAuth2KeyRefreshToken).Str(), "REFRESHTOKEN")
assert.Equal(t, creds.Get(OAuth2KeyExpiresIn).Data().(time.Duration), 20000000000)

}
}
Expand All @@ -59,7 +59,7 @@ func TestOAuth2Provider_CompleteAuth_URLEncodedResponse(t *testing.T) {
func TestOAuth2Provider_Non200Response(t *testing.T) {

config := &common.Config{
Map: objects.M(
Map: objx.MSI(
OAuth2KeyRedirectUrl, OAuth2KeyRedirectUrl,
OAuth2KeyScope, OAuth2KeyScope,
OAuth2KeyClientID, OAuth2KeyClientID,
Expand All @@ -80,7 +80,7 @@ func TestOAuth2Provider_Non200Response(t *testing.T) {
testTripperFactory.On("NewTripper", common.EmptyCredentials, mock.Anything).Return(testTripper, nil)
testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

data := objects.M(OAuth2KeyCode, []string{"123"})
data := objx.MSI(OAuth2KeyCode, []string{"123"})
_, err := CompleteAuth(testTripperFactory, data, config, testProvider)

if assert.Error(t, err) {
Expand All @@ -94,7 +94,7 @@ func TestOAuth2Provider_Non200Response(t *testing.T) {
func TestOAuth2Provider_CompleteAuth_JSON(t *testing.T) {

config := &common.Config{
Map: objects.M(
Map: objx.MSI(
OAuth2KeyRedirectUrl, OAuth2KeyRedirectUrl,
OAuth2KeyScope, OAuth2KeyScope,
OAuth2KeyClientID, OAuth2KeyClientID,
Expand All @@ -117,15 +117,15 @@ func TestOAuth2Provider_CompleteAuth_JSON(t *testing.T) {
testTripperFactory.On("NewTripper", common.EmptyCredentials, mock.Anything).Return(testTripper, nil)
testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

data := objects.M(OAuth2KeyCode, []string{"123"})
data := objx.MSI(OAuth2KeyCode, []string{"123"})
creds, err := CompleteAuth(testTripperFactory, data, config, testProvider)

if assert.NoError(t, err) {
if assert.NotNil(t, creds, "Creds should be returned") {

assert.Equal(t, creds.GetStringOrEmpty(OAuth2KeyAccessToken), "ACCESSTOKEN")
assert.Equal(t, creds.GetStringOrEmpty(OAuth2KeyRefreshToken), "REFRESHTOKEN")
assert.Equal(t, creds.Get(OAuth2KeyExpiresIn).(time.Duration), 20000000000)
assert.Equal(t, creds.Get(OAuth2KeyAccessToken).Str(), "ACCESSTOKEN")
assert.Equal(t, creds.Get(OAuth2KeyRefreshToken).Str(), "REFRESHTOKEN")
assert.Equal(t, creds.Get(OAuth2KeyExpiresIn).Data().(time.Duration), 20000000000)

}
}
Expand Down
8 changes: 4 additions & 4 deletions oauth2/get.go
Expand Up @@ -3,15 +3,15 @@ package oauth2
import (
"github.com/stretchr/codecs/services"
"github.com/stretchr/gomniauth/common"
"github.com/stretchr/stew/objects"
"github.com/stretchr/objx"
"io/ioutil"
)

// Get executes an authenticated HTTP GET against the given provider and returns an
// objects.Map of the response.
// objx.Map of the response.
//
// The response type is automatically detected and used to unmarshal the response.
func Get(provider common.Provider, creds *common.Credentials, endpoint string) (objects.Map, error) {
func Get(provider common.Provider, creds *common.Credentials, endpoint string) (objx.Map, error) {

client, clientErr := provider.GetClient(creds)

Expand Down Expand Up @@ -40,7 +40,7 @@ func Get(provider common.Provider, creds *common.Credentials, endpoint string) (
return nil, getCodecErr
}

var data objects.Map
var data objx.Map
unmarshalErr := codec.Unmarshal(body, &data)

if unmarshalErr != nil {
Expand Down

0 comments on commit 9f822f1

Please sign in to comment.