Beispiel #1
0
func TestMain(m *testing.M) {
	if c, err := dockertest.ConnectToPostgreSQL(15, time.Second, func(url string) bool {
		db, err := sql.Open("postgres", url)
		if err != nil {
			log.Printf("Could not connect to database because %s", err)
			return false
		} else if err := db.Ping(); err != nil {
			log.Printf("Could not ping database because %s", err)
			return false
		}

		// Database is now available, let's continue!
		os.Setenv("DATABASE_URL", url)
		if env.Getenv("DATABASE_URL", "") != url {
			log.Fatalf("Could not set DATABASE_URL environment variable: %s != %s", env.Getenv("DATABASE_URL", ""), url)
			return false
		}
		return true
	}); err != nil {
		log.Fatalf("Could not connect to database: %s", err)
	} else {
		defer c.KillRemove()
	}
	os.Exit(m.Run())
}
Beispiel #2
0
func main() {
	http.HandleFunc("/sign-in", func(w http.ResponseWriter, r *http.Request) {
		/**
		 * Normally, you would authenticate the user through the OAuth2 Password Grant as described here: https://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified#others
		 * If you receive a token, the user authenticated successfully, if you receive an error the request was malformed or the user credentials where wrong.
		 *
		 * This file is just for demonstrations sake.
		 */

		code := uuid.New()
		state := r.URL.Query().Get("state")

		d := data{
			User:     env.Getenv("ACCOUNT_ID", "not-provided"),
			Redirect: fmt.Sprintf("%s?code=%s&state=%s", r.URL.Query().Get("redirect_uri"), code, state),
		}

		if verify := r.URL.Query().Get("verify"); verify != "" {
			out, _ := json.Marshal(&d)
			w.Write(out)
		} else {
			renderTemplate(w, d)
		}
	})

	http.HandleFunc("/authenticate/callback", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Congratulations! You have received the authorization code: %s", r.URL.Query().Get("code"))
	})

	http.ListenAndServe(":3000", nil)
}
Beispiel #3
0
func TestRunCLITests(t *testing.T) {
	oldStderr := os.Stderr // keep backup of the real stdout

	for k, c := range []struct {
		args []string
		pass bool
	}{
		{args: []string{"hydra-host", "account", "create", "foo@bar", "--password", "secret"}, pass: true},
		{args: []string{"hydra-host", "account", "create", "foo@bar", "--password", "secret"}, pass: false},
		{args: []string{"hydra-host", "account", "create", "bar@baz", "--password", "secret", "--as-superuser"}, pass: true},
		{args: []string{"hydra-host", "client", "create", "-i", "foo-app", "-s", "secret", "-r", "http://localhost/"}, pass: true},
		{args: []string{"hydra-host", "client", "create", "-i", "foo-app", "-s", "secret", "-r", "http://localhost/"}, pass: false},
		{args: []string{"hydra-host", "client", "create", "-i", "bar-app", "-s", "secret", "-r", "http://localhost/", "--as-superuser"}, pass: true},
		{args: []string{"hydra-host", "policy", "import", "../../example/policies.json"}, pass: true},
	} {
		r, w, _ := os.Pipe()
		os.Stderr = w
		outC := make(chan string)
		go func() {
			var buf bytes.Buffer
			io.Copy(&buf, r)
			outC <- buf.String()
		}()

		log.Println(env.Getenv("DATABASE_URL", ""))
		os.Args = c.args
		err := NewApp().Run(os.Args)
		assert.Nil(t, err, "Case %d: %s", k, err)

		w.Close()
		if c.pass {
			assert.Empty(t, <-outC)
		} else {
			assert.NotEmpty(t, <-outC)
		}
	}
	os.Stdout = oldStderr
}
Beispiel #4
0
	"gopkg.in/mgo.v2"

	_ "github.com/go-sql-driver/mysql"
	_ "github.com/lib/pq"
)

// Debug, if set, prevents any container from being removed.
var Debug bool

// DockerMachineAvailable, if true, uses docker-machine to run docker commands (for running tests on Windows and Mac OS)
var DockerMachineAvailable bool

// DockerMachineName is the machine's name. You might want to use a dedicated machine for running your tests.
var DockerMachineName string = "default"

var bindDockerToLocalhost = env.Getenv("DOCKER_BIND_LOCALHOST", "")

/// runLongTest checks all the conditions for running a docker container
// based on image.
func runLongTest(image string) error {
	DockerMachineAvailable = false
	if haveDockerMachine() {
		DockerMachineAvailable = true
		if !startDockerMachine() {
			log.Printf(`Starting docker machine "%s" failed. This could be because the image is already running or because the image does not exist. Tests will fail if the image does not exist.`, DockerMachineName)
		}
	} else if !haveDocker() {
		return errors.New("Neither 'docker' nor 'docker-machine' available on this system.")
	}
	if ok, err := haveImage(image); !ok || err != nil {
		if err != nil {
Beispiel #5
0
package dockertest

import "github.com/ory-am/common/env"

// Dockertest configuration
var (
	// Debug if set, prevents any container from being removed.
	Debug bool

	// DockerMachineAvailable if true, uses docker-machine to run docker commands (for running tests on Windows and Mac OS)
	DockerMachineAvailable bool

	// DockerMachineName is the machine's name. You might want to use a dedicated machine for running your tests.
	// You can set this variable either directly or by defining a DOCKERTEST_IMAGE_NAME env variable.
	DockerMachineName = env.Getenv("DOCKERTEST_IMAGE_NAME", "default")

	// BindDockerToLocalhost if set, forces docker to bind the image to localhost. This for example is required when running tests on travis-ci.
	// You can set this variable either directly or by defining a DOCKERTEST_BIND_LOCALHOST env variable.
	// FIXME DOCKER_BIND_LOCALHOST remove legacy support
	BindDockerToLocalhost = env.Getenv("DOCKERTEST_BIND_LOCALHOST", env.Getenv("DOCKER_BIND_LOCALHOST", "1"))

	// UseDockerMachine if set, forces docker to use the legacy docker-machine on OSX/Windows.
	UseDockerMachine = env.Getenv("DOCKERTEST_LEGACY_DOCKER_MACHINE", "")

	// ContainerPrefix will be prepended to all containers started by dockertest to make identification of these "test images" hassle-free.
	ContainerPrefix = env.Getenv("DOCKERTEST_CONTAINER_PREFIX", "dockertest-")
)

// Image configuration
var (
	// MongoDBImageName is the MongoDB image name on dockerhub.
Beispiel #6
0
func getEnv() {
	listenOn = fmt.Sprintf(
		"%s:%s",
		env.Getenv("HOST", ""),
		env.Getenv("PORT", "4443"),
	)
	accessTokenLifetime = env.Getenv("OAUTH2_ACCESS_TOKEN_LIFETIME", "3600")
	forceHTTP = env.Getenv("DANGEROUSLY_FORCE_HTTP", "")
	hostURL = env.Getenv("HOST_URL", "https://localhost:4443")
	providers = []provider.Provider{
		dropbox.New(
			"dropbox",
			env.Getenv("DROPBOX_CLIENT", ""),
			env.Getenv("DROPBOX_SECRET", ""),
			pkg.JoinURL(hostURL, "/oauth2/auth"),
		),
		google.New(
			"google",
			env.Getenv("GOOGLE_CLIENT", ""),
			env.Getenv("GOOGLE_SECRET", ""),
			pkg.JoinURL(hostURL, "/oauth2/auth"),
		),
		microsoft.New(
			"microsoft",
			env.Getenv("MICROSOFT_CLIENT", ""),
			env.Getenv("MICROSOFT_SECRET", ""),
			pkg.JoinURL(hostURL, "/oauth2/auth"),
		),
		signin.New(
			"login",
			env.Getenv("SIGNIN_URL", ""),
			pkg.JoinURL(hostURL, "/oauth2/auth"),
		),
	}
	bcryptWorkFactor = env.Getenv("BCRYPT_WORKFACTOR", "10")
	databaseURL = env.Getenv("DATABASE_URL", "")
	locations = map[string]string{
		"signUp": env.Getenv("SIGNUP_URL", ""),
		"signIn": env.Getenv("SIGNIN_URL", ""),
	}
	jwtPrivateKeyPath = env.Getenv("JWT_PRIVATE_KEY_PATH", path.Join(os.Getenv("GOPATH"), "src", "github.com", "ory-am", "hydra", "example", "cert", "rs256-private.pem"))
	jwtPublicKeyPath = env.Getenv("JWT_PUBLIC_KEY_PATH", path.Join(os.Getenv("GOPATH"), "src", "github.com", "ory-am", "hydra", "example", "cert", "rs256-public.pem"))
	tlsKeyPath = env.Getenv("TLS_KEY_PATH", path.Join(os.Getenv("GOPATH"), "src", "github.com", "ory-am", "hydra", "example", "cert", "tls-key.pem"))
	tlsCertPath = env.Getenv("TLS_CERT_PATH", path.Join(os.Getenv("GOPATH"), "src", "github.com", "ory-am", "hydra", "example", "cert", "tls-cert.pem"))
}
Beispiel #7
0
func main() {
	cfg := osin.NewServerConfig()
	cfg.AllowGetAccessRequest = true
	cfg.AllowClientSecretInParams = true

	server := osin.NewServer(cfg, example.NewTestStorage())

	// Authorization code endpoint
	http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
		resp := server.NewResponse()
		defer resp.Close()

		if ar := server.HandleAuthorizeRequest(resp, r); ar != nil {
			if !example.HandleLoginPage(ar, w, r) {
				return
			}
			ar.Authorized = true
			server.FinishAuthorizeRequest(resp, r, ar)
		}
		if resp.IsError && resp.InternalError != nil {
			fmt.Printf("ERROR: %s\n", resp.InternalError)
		}
		osin.OutputJSON(resp, w, r)
	})

	// Access token endpoint
	http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
		resp := server.NewResponse()
		defer resp.Close()

		if ar := server.HandleAccessRequest(resp, r); ar != nil {
			ar.Authorized = true
			server.FinishAccessRequest(resp, r, ar)
		}
		if resp.IsError && resp.InternalError != nil {
			fmt.Printf("ERROR: %s\n", resp.InternalError)
		}
		osin.OutputJSON(resp, w, r)
	})

	// Information endpoint
	http.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {
		resp := server.NewResponse()
		defer resp.Close()

		if ir := server.HandleInfoRequest(resp, r); ir != nil {
			server.FinishInfoRequest(resp, r, ir)
		}
		osin.OutputJSON(resp, w, r)
	})

	// Application home endpoint
	http.HandleFunc("/app", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("<html><body>"))
		w.Write([]byte(fmt.Sprintf("<a href=\"/authorize?response_type=code&client_id=1234&state=xyz&scope=everything&redirect_uri=%s\">Login</a><br/>", url.QueryEscape("http://localhost:14000/appauth/code"))))
		w.Write([]byte("</body></html>"))
	})

	// Application destination - CODE
	http.HandleFunc("/appauth/code", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()

		code := r.Form.Get("code")

		w.Write([]byte("<html><body>"))
		w.Write([]byte("APP AUTH - CODE<br/>"))
		defer w.Write([]byte("</body></html>"))

		if code == "" {
			w.Write([]byte("Nothing to do"))
			return
		}

		jr := make(map[string]interface{})

		// build access code url
		aurl := fmt.Sprintf("/token?grant_type=authorization_code&client_id=1234&client_secret=aabbccdd&state=xyz&redirect_uri=%s&code=%s",
			url.QueryEscape("http://localhost:14000/appauth/code"), url.QueryEscape(code))

		// if parse, download and parse json
		if r.Form.Get("doparse") == "1" {
			err := example.DownloadAccessToken(fmt.Sprintf("http://localhost:14000%s", aurl),
				&osin.BasicAuth{"1234", "aabbccdd"}, jr)
			if err != nil {
				w.Write([]byte(err.Error()))
				w.Write([]byte("<br/>"))
			}
		}

		// show json error
		if erd, ok := jr["error"]; ok {
			w.Write([]byte(fmt.Sprintf("ERROR: %s<br/>\n", erd)))
		}

		// show json access token
		if at, ok := jr["access_token"]; ok {
			w.Write([]byte(fmt.Sprintf("ACCESS TOKEN: %s<br/>\n", at)))
		}

		w.Write([]byte(fmt.Sprintf("FULL RESULT: %+v<br/>\n", jr)))

		// output links
		w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Goto Token URL</a><br/>", aurl)))

		cururl := *r.URL
		curq := cururl.Query()
		curq.Add("doparse", "1")
		cururl.RawQuery = curq.Encode()
		w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Download Token</a><br/>", cururl.String())))
	})

	port := env.Getenv("PORT", "14000")
	http.ListenAndServe(":"+port, nil)
}
Beispiel #8
0
package dockertest

import "github.com/ory-am/common/env"

// Dockertest configuration
var (
	// Debug if set, prevents any container from being removed.
	Debug bool

	// DockerMachineAvailable if true, uses docker-machine to run docker commands (for running tests on Windows and Mac OS)
	DockerMachineAvailable bool

	// DockerMachineName is the machine's name. You might want to use a dedicated machine for running your tests.
	// You can set this variable either directly or by defining a DOCKERTEST_IMAGE_NAME env variable.
	DockerMachineName = env.Getenv("DOCKERTEST_IMAGE_NAME", "default")

	// BindDockerToLocalhost if set, forces docker to bind the image to localhost. This for example is required when running tests on travis-ci.
	// You can set this variable either directly or by defining a DOCKERTEST_BIND_LOCALHOST env variable.
	// FIXME DOCKER_BIND_LOCALHOST remove legacy support
	BindDockerToLocalhost = env.Getenv("DOCKERTEST_BIND_LOCALHOST", env.Getenv("DOCKER_BIND_LOCALHOST", ""))

	// ContainerPrefix will be prepended to all containers started by dockertest to make identification of these "test images" hassle-free.
	ContainerPrefix = env.Getenv("DOCKERTEST_CONTAINER_PREFIX", "dockertest-")
)

// Image configuration
var (
	// MongoDBImageName is the MongoDB image name on dockerhub.
	MongoDBImageName = env.Getenv("DOCKERTEST_MONGODB_IMAGE_NAME", "mongo")

	// MySQLImageName is the MySQL image name on dockerhub.
Beispiel #9
0
package dockertest

import "github.com/ory-am/common/env"

var (
	// Debug if set, prevents any container from being removed.
	Debug bool

	// DockerMachineAvailable if true, uses docker-machine to run docker commands (for running tests on Windows and Mac OS)
	DockerMachineAvailable bool

	// DockerMachineName is the machine's name. You might want to use a dedicated machine for running your tests.
	// You can set this variable either directly or by defining a DOCKERTEST_IMAGE_NAME env variable.
	DockerMachineName = env.Getenv("DOCKERTEST_IMAGE_NAME", "default")

	// BindDockerToLocalhost if set, forces docker to bind the image to localhost. This for example is required when running tests on travis-ci.
	// You can set this variable either directly or by defining a DOCKERTEST_BIND_LOCALHOST env variable.
	// FIXME DOCKER_BIND_LOCALHOST remove legacy support
	BindDockerToLocalhost = env.Getenv("DOCKERTEST_BIND_LOCALHOST", env.Getenv("DOCKER_BIND_LOCALHOST", ""))
)

const (
	mongoImage    = "mongo"
	mysqlImage    = "mysql"
	postgresImage = "postgres"

	// MySQLUsername must be passed as username when connecting to mysql
	MySQLUsername = "******"

	// MySQLPassword must be passed as password when connecting to mysql
	MySQLPassword = "******"
Beispiel #10
0
package main

// The import section defines libraries that we are going to use in our program.
import (
	"fmt"
	"log"
	"net/http"

	"encoding/json"
	"github.com/gorilla/mux"
	"github.com/ory-am/common/env"
	"github.com/rs/cors"
)

// In a 12 factor app, we must obey the environment variables.
var envHost = env.Getenv("HOST", "")
var envPort = env.Getenv("PORT", "5678")

// Contact defines the structure of a contact which including name, department and company.
type Contact struct {
	ID string `json:"id"`

	// Name is the contact's full name.
	Name string `json:"name"`

	// Department is the contact's department in a company.
	Department string `json:"department"`

	// Company is the name of the company the contact works for.
	Company string `json:"company"`
}
Beispiel #11
0
	"github.com/ory-am/common/pkg"
	"github.com/pborman/uuid"
	"github.com/rs/cors"
	"math"
	"strconv"

	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
	. "github.com/ory-am/workshop-dbg/store"
	"github.com/ory-am/workshop-dbg/store/memory"
	"github.com/ory-am/workshop-dbg/store/postgres"
	"time"
)

// In a 12 factor app, we must obey the environment variables.
var envHost = env.Getenv("HOST", "")
var envPort = env.Getenv("PORT", "5678")
var databaseURL = env.Getenv("DATABASE_URL", "")
var thisID = uuid.New()

// MyContacts is an exemplary list of contacts.
var MyContacts = Contacts{
	// Each contact hs identified by its ID which is prepended with "my-id":
	// We are doing this because it is easier to manage and simpler to read.
	"john-bravo": &Contact{
		Name:       "Andreas Preuss",
		Department: "IT",
		Company:    "ACME Inc",
	},
	"cathrine-mueller": &Contact{
		Name:       "Cathrine Eholzer",