Esempio n. 1
0
File: server.go Progetto: fd/mauth
// New oauth server
func New(store *storage.Storage) http.Handler {
	conf := osin.NewServerConfig()

	conf.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{
		osin.CODE,
		osin.TOKEN}

	conf.AllowedAccessTypes = osin.AllowedAccessType{
		osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN,
		osin.PASSWORD,
		osin.CLIENT_CREDENTIALS}

	conf.AllowGetAccessRequest = true
	conf.RedirectUriSeparator = " "

	oauthServer := osin.NewServer(conf, store)

	key, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		panic(err)
	}

	err = store.EnsureClient("55e42e87b4301941f9000002", "Profile Page", "http://localhost:3000/me")
	if err != nil {
		panic(err)
	}

	return &server{
		store:       store,
		oauthServer: oauthServer,
		defaultKey:  "1",
		keys:        map[string]*rsa.PrivateKey{"1": key},
	}
}
Esempio n. 2
0
File: main.go Progetto: rmg/tyk
// Create API-specific OAuth handlers and respective auth servers
func addOAuthHandlers(spec APISpec, Muxer *http.ServeMux, test bool) {
	apiAuthorizePath := spec.Proxy.ListenPath + "tyk/oauth/authorize-client/"
	clientAuthPath := spec.Proxy.ListenPath + "oauth/authorize/"
	clientAccessPath := spec.Proxy.ListenPath + "oauth/token/"

	serverConfig := osin.NewServerConfig()
	serverConfig.ErrorStatusCode = 403
	serverConfig.AllowedAccessTypes = spec.Oauth2Meta.AllowedAccessTypes
	serverConfig.AllowedAuthorizeTypes = spec.Oauth2Meta.AllowedAuthorizeTypes

	OAuthPrefix := OAUTH_PREFIX + spec.APIID + "."
	storageManager := RedisStorageManager{KeyPrefix: OAuthPrefix}
	storageManager.Connect()
	osinStorage := RedisOsinStorageInterface{&storageManager}

	if test {
		log.Warning("Adding test client")
		testClient := &osin.Client{
			Id:          "1234",
			Secret:      "aabbccdd",
			RedirectUri: "http://client.oauth.com",
		}
		osinStorage.SetClient(testClient.Id, testClient, false)
		log.Warning("Test client added")
	}
	osinServer := osin.NewServer(serverConfig, osinStorage)
	osinServer.AccessTokenGen = &AccessTokenGenTyk{}

	oauthManager := OAuthManager{spec, osinServer}
	oauthHandlers := OAuthHandlers{oauthManager}

	Muxer.HandleFunc(apiAuthorizePath, CheckIsAPIOwner(oauthHandlers.HandleGenerateAuthCodeData))
	Muxer.HandleFunc(clientAuthPath, oauthHandlers.HandleAuthorizePassthrough)
	Muxer.HandleFunc(clientAccessPath, oauthHandlers.HandleAccessRequest)
}
Esempio n. 3
0
func main() {

	port := flag.String("port", "14000", "Port number to listen on")
	backend_url := flag.String("backend", "http://localhost:14001/authenticate", "Address of the authentication backend")

	flag.Parse()

	config := osin.NewServerConfig()
	config.AllowGetAccessRequest = true
	config.AllowClientSecretInParams = true

	storage := NewInMemoryStorage()

	load_clients(storage)

	server := osin.NewServer(config, storage)

	// Authorization code endpoint
	http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
		resp := server.NewResponse()
		if ar := server.HandleAuthorizeRequest(resp, r); ar != nil {
			if !HandleLoginPage(*backend_url, resp, 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()
		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: (internal) %s\n", resp.InternalError)
		}
		osin.OutputJSON(resp, w, r)
	})

	// Information endpoint
	http.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {
		resp := server.NewResponse()
		if ir := server.HandleInfoRequest(resp, r); ir != nil {
			server.FinishInfoRequest(resp, r, ir)
		}
		osin.OutputJSON(resp, w, r)
	})

	fs := http.FileServer(http.Dir("assets"))
	http.Handle("/assets/", http.StripPrefix("/assets/", fs))

	http.ListenAndServe(":"+*port, nil)
}
Esempio n. 4
0
func TestAccessPassword(t *testing.T) {
	t.Parallel()
	storageConfig := CreateStorageConfig("TestAccessPassword")
	svc := createDynamoDB()
	storage := New(svc, storageConfig)
	err := storage.CreateSchema()
	assert.Nil(t, err, "%s", err)
	defer storage.DropSchema()
	client := &osin.DefaultClient{
		Id:          "1234",
		Secret:      "aabbccdd",
		RedirectUri: "/dev/null",
	}
	err = storage.CreateClient(client)
	assert.Nil(t, err, "%s", err)
	// -- -- --
	sconfig := osin.NewServerConfig()
	sconfig.AllowedAccessTypes = osin.AllowedAccessType{osin.PASSWORD}
	server := osin.NewServer(sconfig, storage)
	server.AccessTokenGen = &TestingAccessTokenGen{}
	resp := server.NewResponse()

	req, err := http.NewRequest("POST", "http://localhost:14000/appauth", nil)
	if err != nil {
		t.Fatal(err)
	}
	req.SetBasicAuth("1234", "aabbccdd")

	req.Form = make(url.Values)
	req.Form.Set("grant_type", string(osin.PASSWORD))
	req.Form.Set("username", "testing")
	req.Form.Set("password", "testing")
	req.Form.Set("state", "a")
	req.PostForm = make(url.Values)

	if ar := server.HandleAccessRequest(resp, req); ar != nil {
		ar.Authorized = ar.Username == "testing" && ar.Password == "testing"
		server.FinishAccessRequest(resp, req, ar)
	}

	if resp.IsError && resp.InternalError != nil {
		t.Fatalf("Error in response: %s", resp.InternalError)
	}

	if resp.IsError {
		t.Fatalf("Should not be an error")
	}

	if resp.Type != osin.DATA {
		t.Fatalf("Response should be data")
	}

	if d := resp.Output["access_token"]; d != "1" {
		t.Fatalf("Unexpected access token: %s", d)
	}

	if d := resp.Output["refresh_token"]; d != "r1" {
		t.Fatalf("Unexpected refresh token: %s", d)
	}
}
Esempio n. 5
0
func (s *Server) Start() {
	config := osin.NewServerConfig()
	config.ErrorStatusCode = 401

	url := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable",
		os.Getenv("DB_USER"),
		os.Getenv("DB_PASS"),
		os.Getenv("DB_HOST"),
		os.Getenv("DB_NAME"),
	)

	db, err := sqlx.Open("postgres", url)
	if err != nil {
		log.Fatalln(err.Error())
	}

	storage := postgres.New(db.DB)
	s.server = osin.NewServer(config, storage)

	wsContainer := restful.NewContainer()

	r := UserResource{}
	r.Register(wsContainer, db)

	ws := new(restful.WebService)
	ws.Route(ws.POST("/authorize").
		Consumes("application/x-www-form-urlencoded").
		To(s.authorize))
	wsContainer.Add(ws)

	address := fmt.Sprintf("%s:%s", s.Host, s.Port)
	log.Printf("Listening on %s", address)

	log.Fatalln(http.ListenAndServe(address, wsContainer))
}
Esempio n. 6
0
func Init(DB *sql.DB) {
	sconfig := osin.NewServerConfig()
	sconfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.TOKEN}
	sconfig.AllowedAccessTypes = osin.AllowedAccessType{osin.REFRESH_TOKEN, osin.PASSWORD, osin.ASSERTION}
	sconfig.AllowGetAccessRequest = false
	server.Init(osin.NewServer(sconfig, storage.NewMySQLStorage()))
	db.Init(DB)
}
Esempio n. 7
0
func NewOAuthHandler(db *sql.DB) *OAuthHandler {
	config := osin.NewServerConfig()
	config.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.CODE, osin.TOKEN}
	config.AllowedAccessTypes = osin.AllowedAccessType{osin.AUTHORIZATION_CODE, osin.REFRESH_TOKEN}
	storage := NewAuthStorage(db)
	server := osin.NewServer(config, storage)
	return &OAuthHandler{config, server, storage, db}
}
Esempio n. 8
0
func NewOAuthHandler(session *mgo.Session, dbName string) *oAuthHandler {
	sconfig := osin.NewServerConfig()
	sconfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.CODE, osin.TOKEN}
	sconfig.AllowedAccessTypes = osin.AllowedAccessType{osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN, osin.PASSWORD, osin.CLIENT_CREDENTIALS, osin.ASSERTION}
	sconfig.AllowGetAccessRequest = true
	storage := mgostore.New(session, dbName)
	server := osin.NewServer(sconfig, storage)
	return &oAuthHandler{sconfig, server, storage}
}
Esempio n. 9
0
// DefaultOsinConfig returns a preset config suitable
// for most generic oauth2 usage
func DefaultOsinConfig() (cfg *osin.ServerConfig) {
	cfg = osin.NewServerConfig()
	cfg.AllowGetAccessRequest = true
	cfg.AllowClientSecretInParams = true
	cfg.AllowedAccessTypes = osin.AllowedAccessType{
		osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN,
	}
	cfg.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{
		osin.CODE,
		osin.TOKEN,
	}
	return
}
Esempio n. 10
0
func NewOAuth() *OAuth {

	sconfig := osin.NewServerConfig()
	sconfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.CODE, osin.TOKEN}
	sconfig.AllowedAccessTypes = osin.AllowedAccessType{osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN, osin.PASSWORD, osin.CLIENT_CREDENTIALS, osin.ASSERTION}
	sconfig.AllowGetAccessRequest = true
	sconfig.AllowClientSecretInParams = true

	oauth := OAuth{
		Server: osin.NewServer(sconfig, NewATStorage()),
		View:   render.New(),
	}
	return &oauth
}
Esempio n. 11
0
func InitApi(config ApiConfig, storage *OAuthStorage, user shoreline.Client, perms clients.Gatekeeper) *Api {

	log.Println(OAUTH2_API_PREFIX, "Api setting up ...")

	sconfig := osin.NewServerConfig()
	sconfig.AllowGetAccessRequest = true
	sconfig.AllowClientSecretInParams = true

	return &Api{
		storage:     storage,
		oauthServer: osin.NewServer(sconfig, storage),
		ApiConfig:   config,
		permsApi:    perms,
		userApi:     user,
	}
}
Esempio n. 12
0
func NewOAuth2(base string) *OAuth2 {
	cfg := osin.NewServerConfig()
	cfg.AllowGetAccessRequest = true

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

	funcauthorize := func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
		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)
	}

	functoken := func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
		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)

	}

	o := &OAuth2{
		FuncAuthorize: funcauthorize,
		FuncToken:     functoken,
		Router:        httprouter.New(),
		BaseURI:       base,
	}
	o.InitRouter()
	return o
}
func init() {
	sc := osin.NewServerConfig()
	sc.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{
		osin.CODE,
		osin.TOKEN,
	}

	sc.AllowedAccessTypes = osin.AllowedAccessType{
		osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN,
		osin.ASSERTION,
		osin.PASSWORD,
		osin.AccessRequestType("saml2-grant"),
	}

	ts = NewRedisStore()
	server = osin.NewServer(sc, ts)
}
Esempio n. 14
0
func NewOAuthHandler(session *mgo.Session) *Oauth {
	sconfig := osin.NewServerConfig()
	// AllowedAccessType is a collection of allowed access request types
	sconfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.CODE, osin.TOKEN}
	// AccessRequestType is the type for OAuth param `grant_type`
	sconfig.AllowedAccessTypes = osin.AllowedAccessType{osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN, osin.PASSWORD, osin.CLIENT_CREDENTIALS, osin.ASSERTION}
	// If true allows access request using GET, else only POST - default false
	sconfig.AllowGetAccessRequest = true
	storage := modelhelper.NewOauthStore(session)
	server := osin.NewServer(sconfig, storage)

	return &Oauth{
		sconfig: sconfig,
		server:  server,
		Storage: storage,
	}
}
Esempio n. 15
0
func DefaultConfig() *osin.ServerConfig {
	conf := osin.NewServerConfig()
	conf.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{
		osin.CODE,
		osin.TOKEN,
	}
	conf.AllowedAccessTypes = osin.AllowedAccessType{
		osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN,
		osin.PASSWORD,
		osin.CLIENT_CREDENTIALS,
		//osin.ASSERTION,
	}
	conf.AllowGetAccessRequest = false
	conf.AllowClientSecretInParams = false
	conf.ErrorStatusCode = http.StatusInternalServerError
	conf.RedirectUriSeparator = "|"
	return conf
}
Esempio n. 16
0
func NewDefaultServerConfig() *osin.ServerConfig {
	config := osin.NewServerConfig()

	config.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{
		osin.CODE,
		osin.TOKEN,
	}
	config.AllowedAccessTypes = osin.AllowedAccessType{
		osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN,
		osin.PASSWORD,
		osin.CLIENT_CREDENTIALS,
		osin.ASSERTION,
	}
	config.AllowClientSecretInParams = true
	config.AllowGetAccessRequest = true
	config.RedirectUriSeparator = ","
	config.ErrorStatusCode = http.StatusBadRequest

	return config
}
Esempio n. 17
0
func osinConfig() (conf *osin.ServerConfig, err error) {
	conf = osin.NewServerConfig()
	lifetime, err := strconv.Atoi(accessTokenLifetime)
	if err != nil {
		return nil, err
	}
	conf.AccessExpiration = int32(lifetime)

	conf.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{
		osin.CODE,
		osin.TOKEN,
	}
	conf.AllowedAccessTypes = osin.AllowedAccessType{
		osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN,
		osin.PASSWORD,
		osin.CLIENT_CREDENTIALS,
	}
	conf.AllowGetAccessRequest = false
	conf.AllowClientSecretInParams = false
	conf.ErrorStatusCode = http.StatusInternalServerError
	conf.RedirectUriSeparator = "|"
	return conf, nil
}
Esempio n. 18
0
func main() {
	sconfig := osin.NewServerConfig()
	sconfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{
		osin.CODE,
		osin.TOKEN,
	}
	sconfig.AllowedAccessTypes = osin.AllowedAccessType{
		osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN,
		osin.PASSWORD,
		osin.CLIENT_CREDENTIALS,
		osin.ASSERTION,
	}
	sconfig.AllowGetAccessRequest = true
	sconfig.AllowClientSecretInParams = true
	// mongodb connect
	var session *mgo.Session
	var err error
	session, err = mgo.Dial(DBSERVER)
	if err != nil {
		log.Fatal(err)
	}
	// config and db
	server := osin.NewServer(sconfig, authserver.NewMongoStorage(session, DBNAME))

	// 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 {
			log.Println("Come ??")
			if !authserver.HandleLoginPage(ar, w, r) {
				log.Println("Login Page Error")
				return
			}
			ar.UserData = struct{ Login string }{Login: "******"}
			ar.Authorized = true
			server.FinishAuthorizeRequest(resp, r, ar)
		}
		if resp.IsError && resp.InternalError != nil {
			log.Printf("ERROR: %s\n", resp.InternalError)
		}
		if !resp.IsError {
			// ??
			resp.Output["custom_parameter"] = 187723
		}
		osin.OutputJSON(resp, w, r)
	})

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

		// 6 type 인증방식
		// 1. Client 타입
		// 2. Authorization Code Grant(*)
		// 3. Implict Grant Flow(*)
		// 4. Password Credential Grant(*)
		// 5. Client Credentials Grant(*)
		// 6. Extension
		if ar := server.HandleAccessRequest(resp, r); ar != nil {
			switch ar.Type {
			// Authorization Code Grant
			case osin.AUTHORIZATION_CODE:
				ar.Authorized = true
			// token refresh
			case osin.REFRESH_TOKEN:
				ar.Authorized = true
				// Password credential grant
				// 2-legged method. id and pass -> access token
			case osin.PASSWORD:
				// Test code ?
				if ar.Username == "test" && ar.Password == "test" {
					ar.Authorized = true
				}
				// client 자신이 resource에 대한 접근권한을 가지는 방식
			case osin.CLIENT_CREDENTIALS:
				ar.Authorized = true
			// ?
			case osin.ASSERTION:
				if ar.AssertionType == "urn:osin.authserver.complete" &&
					ar.Assertion == "osin.data" {
					ar.Authorized = true
				}
			}
			server.FinishAccessRequest(resp, r, ar)
		}

		if resp.IsError && resp.InternalError != nil {
			log.Printf("ERROR: %s\n", resp.InternalError)
		}
		if !resp.IsError {
			resp.Output["custom_parameter"] = 19923
		}
		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\">Code</a><br/>", url.QueryEscape("http://"+AUTHHOST+AUTHPORT+"/appauth/code"))))
		w.Write([]byte(fmt.Sprintf("<a href=\"/authorize?response_type=token&client_id=1234&state=xyz&scope=everything&redirect_uri=%s\">Implict</a><br/>", url.QueryEscape("http://"+AUTHHOST+AUTHPORT+"/appauth/token"))))
		w.Write([]byte(fmt.Sprintf("<a href=\"/appauth/password\">Password</a><br/>")))
		w.Write([]byte(fmt.Sprintf("<a href=\"/appauth/client_credentials\">Client Credentials</a><br/>")))
		w.Write([]byte(fmt.Sprintf("<a href=\"/appauth/assertion\">Assertion</a><br/>")))

		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://"+AUTHHOST+AUTHPORT+"/appauth/code"), url.QueryEscape(code))

		// if parse, download and parse json
		if r.Form.Get("doparse") == "1" {
			err := authserver.DownloadAccessToken(
				fmt.Sprintf("http://"+AUTHHOST+AUTHPORT+"%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())))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}

		if at, ok := jr["access_token"]; ok {
			rurl := fmt.Sprintf("/appauth/info?code=%s", at)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Info</a><br/>", rurl)))
		}
	})

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

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

		w.Write([]byte("Response data in fragment - not acessible via server - Nothing to do"))

		w.Write([]byte("</body></html>"))
	})

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

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

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

		// build access code url
		aurl := fmt.Sprintf("/token?grant_type=password&scope=everything&username=%s&password=%s",
			"test", "test")

		// download token
		err := authserver.DownloadAccessToken(
			fmt.Sprintf("http://"+AUTHHOST+AUTHPORT+"%s", aurl),
			&osin.BasicAuth{Username: "******", Password: "******"}, 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)))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}

		if at, ok := jr["access_token"]; ok {
			rurl := fmt.Sprintf("/appauth/info?code=%s", at)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Info</a><br/>", rurl)))
		}

		w.Write([]byte("</body></html>"))
	})

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

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

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

		// build access code url
		aurl := fmt.Sprintf("/token?grant_type=client_credentials")

		// download token
		err := authserver.DownloadAccessToken(
			fmt.Sprintf("http://"+AUTHHOST+AUTHPORT+"%s", aurl),
			&osin.BasicAuth{Username: "******", Password: "******"}, 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)))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}

		if at, ok := jr["access_token"]; ok {
			rurl := fmt.Sprintf("/appauth/info?code=%s", at)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Info</a><br/>", rurl)))
		}

		w.Write([]byte("</body></html>"))
	})

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

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

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

		// build access code url
		aurl := fmt.Sprintf("/token?grant_type=assertion&assertion_type=urn:osin.authserver.complete&assertion=osin.data")

		// download token
		err := authserver.DownloadAccessToken(
			fmt.Sprintf("http://"+AUTHHOST+AUTHPORT+"%s", aurl),
			&osin.BasicAuth{Username: "******", Password: "******"}, 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)))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}

		if at, ok := jr["access_token"]; ok {
			rurl := fmt.Sprintf("/appauth/info?code=%s", at)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Info</a><br/>", rurl)))
		}

		w.Write([]byte("</body></html>"))
	})

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

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

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

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

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

		// build access code url
		aurl := fmt.Sprintf("/token?grant_type=refresh_token&refresh_token=%s", url.QueryEscape(code))

		// download token
		err := authserver.DownloadAccessToken(
			fmt.Sprintf("http://"+AUTHHOST+AUTHPORT+"%s", aurl),
			&osin.BasicAuth{Username: "******", Password: "******"}, 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)))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}

		if at, ok := jr["access_token"]; ok {
			rurl := fmt.Sprintf("/appauth/info?code=%s", at)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Info</a><br/>", rurl)))
		}
	})

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

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

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

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

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

		// build access code url
		aurl := fmt.Sprintf("/info?code=%s", url.QueryEscape(code))

		// download token
		err := authserver.DownloadAccessToken(
			fmt.Sprintf("http://"+AUTHHOST+AUTHPORT+"%s", aurl),
			&osin.BearerAuth{Code: url.QueryEscape(code)}, jr)
		if err != nil {
			log.Println("download access token error")
			w.Write([]byte(err.Error()))
			w.Write([]byte("<br/>"))
		}

		// show json error
		if erd, ok := jr["error"]; ok {
			log.Println("error return from /info?code=xxxx")
			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)))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}
	})

	http.ListenAndServe(AUTHPORT, nil)
}
Esempio n. 19
0
File: main.go Progetto: gofmt/oauth2
func serve(ctx *cli.Context) error {
	var err error

	var config settings.Config
	if ctx.String("config") != "" {
		config, err = settings.Parse(ctx.String("config"))
		if err != nil {
			logs.Error(err)
		}
	}

	if config.Debug() {
		logs.Level(logs.DebugLevel)
	}

	dialect, args, err := config.SqlDB()
	if err != nil {
		logs.Critical(err)
		os.Exit(1)
	}
	logs.Debug("database type: %s", dialect)

	var app = application.New()
	if app.Components["DB"], err = databases.InitGORM(dialect, args); err != nil {
		logs.Critical(err)
		os.Exit(1)
	}
	logs.Debug("connected to %s", args)

	if config.Migrate() {
		app.Components["DB"].(*gorm.DB).AutoMigrate(models.Models()...)
		logs.Debug("database migrated successfully")
	}

	redisSettings, err := config.Redis()
	client := redis.NewClient(&redis.Options{Addr: redisSettings.String()})
	if _, err := client.Ping().Result(); err != nil {
		return err
	}
	logs.Debug("Connected to Redis at %s", redisSettings.String())

	app.Components["Redis"] = client

	cfg := osin.NewServerConfig()
	cfg.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.CODE, osin.TOKEN}
	cfg.AllowedAccessTypes = osin.AllowedAccessType{osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN, osin.PASSWORD}

	oauthServer := osin.NewServer(cfg, components.NewRedisStorage(client))
	app.Components["OAuth"] = oauthServer

	app.Components["Templates"] = views.Templates()

	app.Components["Mux"] = gojimux.New()

	if config.Debug() {
		app.Components["DB"].(*gorm.DB).LogMode(true)
		app.Use(router.Logger)
	}

	app.Use(app.Apply)

	app.Get("/oauth2/authorize", controllers.Authorize)
	app.Post("/oauth2/token", controllers.Token)
	app.Get("/oauth2/info", controllers.Info)

	app.Post("/users/register", controllers.Register)
	app.Get("/users/:id", controllers.RetrieveUser)

	app.Get("/groups", controllers.RetrieveGroupCollection)
	app.Post("/groups", controllers.CreateGroup)
	app.Get("/groups/:id", controllers.RetrieveGroup)
	app.Delete("/groups/:id", controllers.DeleteGroup)
	app.Patch("/groups/:id", controllers.UpdateGroup)

	server, err := config.Server()
	if err != nil {
		logs.Critical(err)
		os.Exit(1)
	}
	return app.Serve(server.String())
}
Esempio n. 20
0
func main() {
	sconfig := osin.NewServerConfig()
	sconfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.CODE, osin.TOKEN}
	sconfig.AllowedAccessTypes = osin.AllowedAccessType{osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN, osin.PASSWORD, osin.CLIENT_CREDENTIALS, osin.ASSERTION}
	sconfig.AllowGetAccessRequest = true
	server := osin.NewServer(sconfig, 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.UserData = struct{ Login string }{Login: "******"}
			ar.Authorized = true
			server.FinishAuthorizeRequest(resp, r, ar)
		}
		if resp.IsError && resp.InternalError != nil {
			fmt.Printf("ERROR: %s\n", resp.InternalError)
		}
		if !resp.IsError {
			resp.Output["custom_parameter"] = 187723
		}
		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 {
			switch ar.Type {
			case osin.AUTHORIZATION_CODE:
				ar.Authorized = true
			case osin.REFRESH_TOKEN:
				ar.Authorized = true
			case osin.PASSWORD:
				if ar.Username == "test" && ar.Password == "test" {
					ar.Authorized = true
				}
			case osin.CLIENT_CREDENTIALS:
				ar.Authorized = true
			case osin.ASSERTION:
				if ar.AssertionType == "urn:osin.example.complete" && ar.Assertion == "osin.data" {
					ar.Authorized = true
				}
			}
			server.FinishAccessRequest(resp, r, ar)
		}
		if resp.IsError && resp.InternalError != nil {
			fmt.Printf("ERROR: %s\n", resp.InternalError)
		}
		if !resp.IsError {
			resp.Output["custom_parameter"] = 19923
		}
		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\">Code</a><br/>", url.QueryEscape("http://localhost:14000/appauth/code"))))
		w.Write([]byte(fmt.Sprintf("<a href=\"/authorize?response_type=token&client_id=1234&state=xyz&scope=everything&redirect_uri=%s\">Implict</a><br/>", url.QueryEscape("http://localhost:14000/appauth/token"))))
		w.Write([]byte(fmt.Sprintf("<a href=\"/appauth/password\">Password</a><br/>")))
		w.Write([]byte(fmt.Sprintf("<a href=\"/appauth/client_credentials\">Client Credentials</a><br/>")))
		w.Write([]byte(fmt.Sprintf("<a href=\"/appauth/assertion\">Assertion</a><br/>")))

		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&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())))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}

		if at, ok := jr["access_token"]; ok {
			rurl := fmt.Sprintf("/appauth/info?code=%s", at)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Info</a><br/>", rurl)))
		}
	})

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

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

		w.Write([]byte("Response data in fragment - not acessible via server - Nothing to do"))

		w.Write([]byte("</body></html>"))
	})

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

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

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

		// build access code url
		aurl := fmt.Sprintf("/token?grant_type=password&scope=everything&username=%s&password=%s",
			"test", "test")

		// download token
		err := example.DownloadAccessToken(fmt.Sprintf("http://localhost:14000%s", aurl),
			&osin.BasicAuth{Username: "******", Password: "******"}, 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)))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}

		if at, ok := jr["access_token"]; ok {
			rurl := fmt.Sprintf("/appauth/info?code=%s", at)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Info</a><br/>", rurl)))
		}

		w.Write([]byte("</body></html>"))
	})

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

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

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

		// build access code url
		aurl := fmt.Sprintf("/token?grant_type=client_credentials")

		// download token
		err := example.DownloadAccessToken(fmt.Sprintf("http://localhost:14000%s", aurl),
			&osin.BasicAuth{Username: "******", Password: "******"}, 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)))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}

		if at, ok := jr["access_token"]; ok {
			rurl := fmt.Sprintf("/appauth/info?code=%s", at)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Info</a><br/>", rurl)))
		}

		w.Write([]byte("</body></html>"))
	})

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

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

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

		// build access code url
		aurl := fmt.Sprintf("/token?grant_type=assertion&assertion_type=urn:osin.example.complete&assertion=osin.data")

		// download token
		err := example.DownloadAccessToken(fmt.Sprintf("http://localhost:14000%s", aurl),
			&osin.BasicAuth{Username: "******", Password: "******"}, 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)))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}

		if at, ok := jr["access_token"]; ok {
			rurl := fmt.Sprintf("/appauth/info?code=%s", at)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Info</a><br/>", rurl)))
		}

		w.Write([]byte("</body></html>"))
	})

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

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

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

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

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

		// build access code url
		aurl := fmt.Sprintf("/token?grant_type=refresh_token&refresh_token=%s", url.QueryEscape(code))

		// download token
		err := example.DownloadAccessToken(fmt.Sprintf("http://localhost:14000%s", aurl),
			&osin.BasicAuth{Username: "******", Password: "******"}, 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)))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}

		if at, ok := jr["access_token"]; ok {
			rurl := fmt.Sprintf("/appauth/info?code=%s", at)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Info</a><br/>", rurl)))
		}
	})

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

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

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

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

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

		// build access code url
		aurl := fmt.Sprintf("/info?code=%s", url.QueryEscape(code))

		// download token
		err := example.DownloadAccessToken(fmt.Sprintf("http://localhost:14000%s", aurl),
			&osin.BasicAuth{Username: "******", Password: "******"}, 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)))

		if rt, ok := jr["refresh_token"]; ok {
			rurl := fmt.Sprintf("/appauth/refresh?code=%s", rt)
			w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Refresh Token</a><br/>", rurl)))
		}
	})

	http.ListenAndServe(":14000", nil)
}
Esempio n. 21
0
func main() {
	server := osin.NewServer(osin.NewServerConfig(), example.NewTestStorage())
	server.AccessTokenGen = &AccessTokenGenJWT{privatekey, publickey}

	// 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/>"))

		if code != "" {
			jr := make(map[string]interface{})

			// build access code url
			aurl := fmt.Sprintf("/token?grant_type=authorization_code&client_id=1234&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())))
		} else {
			w.Write([]byte("Nothing to do"))
		}

		w.Write([]byte("</body></html>"))
	})

	http.ListenAndServe(":14000", nil)
}
Esempio n. 22
0
func TestAccessAuthorizationCode(t *testing.T) {
	t.Parallel()
	storageConfig := CreateStorageConfig("TestAccessAuthorizationCode")
	svc := createDynamoDB()
	storage := New(svc, storageConfig)
	err := storage.CreateSchema()
	defer storage.DropSchema()
	assert.Nil(t, err, "%s", err)
	client := &osin.DefaultClient{
		Id:          "1234",
		Secret:      "aabbccdd",
		RedirectUri: "/dev/null",
	}
	err = storage.CreateClient(client)
	assert.Nil(t, err, "%s", err)
	authorizeData := &osin.AuthorizeData{
		Client:      client,
		Code:        "9999",
		ExpiresIn:   3600,
		RedirectUri: "/dev/null",
		CreatedAt:   time.Now(),
	}
	err = storage.SaveAuthorize(authorizeData)
	assert.Nil(t, err, "%s", err)

	// -- -- --
	sconfig := osin.NewServerConfig()
	sconfig.AllowedAccessTypes = osin.AllowedAccessType{osin.AUTHORIZATION_CODE}
	server := osin.NewServer(sconfig, storage)
	server.AccessTokenGen = &TestingAccessTokenGen{}
	resp := server.NewResponse()

	req, err := http.NewRequest("POST", "http://localhost:14000/appauth", nil)
	if err != nil {
		t.Fatal(err)
	}
	req.SetBasicAuth("1234", "aabbccdd")

	req.Form = make(url.Values)
	req.Form.Set("grant_type", string(osin.AUTHORIZATION_CODE))
	req.Form.Set("code", "9999")
	req.Form.Set("state", "a")
	req.PostForm = make(url.Values)

	if ar := server.HandleAccessRequest(resp, req); ar != nil {
		ar.Authorized = true
		server.FinishAccessRequest(resp, req, ar)
	}

	//fmt.Printf("%+v", resp)

	if resp.IsError && resp.InternalError != nil {
		t.Fatalf("Error in response: %s", resp.InternalError)
	}

	if resp.IsError {
		t.Fatalf("Should not be an error")
	}

	if resp.Type != osin.DATA {
		t.Fatalf("Response should be data")
	}

	if d := resp.Output["access_token"]; d != "1" {
		t.Fatalf("Unexpected access token: %s", d)
	}

	if d := resp.Output["refresh_token"]; d != "r1" {
		t.Fatalf("Unexpected refresh token: %s", d)
	}
}
Esempio n. 23
0
func TestAuthorizeToken(t *testing.T) {
	t.Parallel()
	storageConfig := CreateStorageConfig("TestAuthorizeToken")
	svc := createDynamoDB()
	storage := New(svc, storageConfig)
	err := storage.CreateSchema()
	assert.Nil(t, err, "%s", err)
	defer storage.DropSchema()
	client := &osin.DefaultClient{
		Id:          "1234",
		Secret:      "aabbccdd",
		RedirectUri: "/dev/null",
	}
	err = storage.CreateClient(client)
	assert.Nil(t, err, "%s", err)
	authorizeData := &osin.AuthorizeData{
		Client:      client,
		Code:        "9999",
		ExpiresIn:   3600,
		RedirectUri: "/dev/null",
		CreatedAt:   time.Now(),
	}
	err = storage.SaveAuthorize(authorizeData)
	assert.Nil(t, err, "%s", err)

	// -- -- --
	sconfig := osin.NewServerConfig()
	sconfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.TOKEN}
	server := osin.NewServer(sconfig, storage)
	server.AuthorizeTokenGen = &TestingAuthorizeTokenGen{}
	server.AccessTokenGen = &TestingAccessTokenGen{}
	resp := server.NewResponse()

	req, err := http.NewRequest("GET", "http://localhost:14000/appauth", nil)
	if err != nil {
		t.Fatal(err)
	}
	req.Form = make(url.Values)
	req.Form.Set("response_type", string(osin.TOKEN))
	req.Form.Set("client_id", "1234")
	req.Form.Set("state", "a")

	if ar := server.HandleAuthorizeRequest(resp, req); ar != nil {
		ar.Authorized = true
		server.FinishAuthorizeRequest(resp, req, ar)
	}

	if resp.IsError && resp.InternalError != nil {
		t.Fatalf("Error in response: %s", resp.InternalError)
	}

	if resp.IsError {
		t.Fatalf("Should not be an error")
	}

	if resp.Type != osin.REDIRECT || !resp.RedirectInFragment {
		t.Fatalf("Response should be a redirect with fragment")
	}

	if d := resp.Output["access_token"]; d != "1" {
		t.Fatalf("Unexpected access token: %s", d)
	}
}
Esempio n. 24
0
func main() {
	config := osin.NewServerConfig()
	// goauth2 checks errors using status codes
	config.ErrorStatusCode = 401

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

	client := &oauth.Config{
		ClientId:     "1234",
		ClientSecret: "aabbccdd",
		RedirectURL:  "http://localhost:14000/appauth/code",
		AuthURL:      "http://localhost:14000/authorize",
		TokenURL:     "http://localhost:14000/token",
	}
	ctransport := &oauth.Transport{Config: client}

	// 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(fmt.Sprintf("<a href=\"%s\">Login</a><br/>", client.AuthCodeURL(""))))
		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
		}

		var jr *oauth.Token
		var err error

		// if parse, download and parse json
		if r.Form.Get("doparse") == "1" {
			jr, err = ctransport.Exchange(code)
			if err != nil {
				jr = nil
				w.Write([]byte(fmt.Sprintf("ERROR: %s<br/>\n", err)))
			}
		}

		// show json access token
		if jr != nil {
			w.Write([]byte(fmt.Sprintf("ACCESS TOKEN: %s<br/>\n", jr.AccessToken)))
			if jr.RefreshToken != "" {
				w.Write([]byte(fmt.Sprintf("REFRESH TOKEN: %s<br/>\n", jr.RefreshToken)))
			}
		}

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

		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())))
	})

	http.ListenAndServe(":14000", nil)
}
Esempio n. 25
0
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/RangelReale/osin"
	"github.com/RangelReale/osin/example"

	"gopkg.in/square/go-jose.v1"
)

var (
	issuer = "http://127.0.0.1:14001"
	server = osin.NewServer(osin.NewServerConfig(), example.NewTestStorage())

	jwtSigner  jose.Signer
	publicKeys *jose.JsonWebKeySet
)

func main() {
	// Load signing key.
	block, _ := pem.Decode(privateKeyBytes)
	if block == nil {
		log.Fatalf("no private key found")
	}
	key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		log.Fatalf("failed to parse key: %v", err)
	}
Esempio n. 26
0
func main() {
	// mongodb connection
	var dbConfig *bongo.Config
	if dbUri := os.Getenv("MONGOLAB_URI"); dbUri != "" {
		dbConfig = &bongo.Config{ConnectionString: dbUri}
	} else {
		dbConfig = &bongo.Config{ConnectionString: dbUrl, Database: dbName}
	}
	conn, err := bongo.Connect(dbConfig)
	if err != nil {
		log.Fatal(err)
	}

	// oauth server
	oConfig := osin.NewServerConfig()
	oConfig.ErrorStatusCode = http.StatusBadRequest
	// allow grant_type password only
	oConfig.AccessExpiration = tokenExpiration
	oConfig.AllowedAccessTypes = osin.AllowedAccessType{osin.PASSWORD}
	oauthServer := osin.NewServer(oConfig, MongoStorage{conn})

	// TODO: move to some DB config file
	conn.Collection("Category").Collection().EnsureIndex(mgo.Index{
		Key:        []string{"slug"},
		Unique:     true,
		DropDups:   true,
		Background: true,
	})
	conn.Collection(routes.COL_CITIZEN).Collection().EnsureIndex(mgo.Index{
		Key:        []string{"username"},
		Unique:     true,
		DropDups:   true,
		Background: true,
	})

	// api routes config
	router := gin.Default()

	// CORS
	router.Use(cors.Middleware(cors.Config{
		Origins:         "*",
		Methods:         "GET, PUT, POST, DELETE",
		RequestHeaders:  "Origin, Authorization, Content-Type",
		ExposedHeaders:  "",
		MaxAge:          50 * time.Second,
		Credentials:     true,
		ValidateHeaders: false,
	}))

	// disable automatic trailing slash due to errors on client
	router.RedirectTrailingSlash = false

	v1 := router.Group("/v1")
	{
		reports := &routes.Reports{conn}
		r := v1.Group("reports")
		r.GET("", reports.List())
		r.POST("", util.RequireLogin(oauthServer), reports.Create())
		r.GET("/:id", reports.Get())

		categories := &routes.Categories{conn}
		c := v1.Group("categories")
		//c.GET("/", categories.List())
		//c.GET("/tree", categories.List()) // fix pending in httprouter
		c.GET("", categories.GetTree())
		c.GET("/:slug", categories.Get())

		citizens := &routes.Citizens{conn}
		cz := v1.Group("citizens")
		cz.POST("", citizens.Create())
		cz.POST("/login", citizens.Login(oauthServer))
		cz.GET("/:uname", util.RequireLogin(oauthServer), citizens.GetProfile())
		//cz.POST("/logout", citizens.Get())
	}

	// run server on configured port
	router.Run(":" + getPort())
}
Esempio n. 27
0
package oauth

import (
	"github.com/RangelReale/osin"
)

var config = func() *osin.ServerConfig {
	c := osin.NewServerConfig()
	c.ErrorStatusCode = 401
	c.AllowClientSecretInParams = true
	c.AllowGetAccessRequest = true
	c.AllowedAccessTypes = osin.AllowedAccessType{
		osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN,
	}
	return c
}()
Esempio n. 28
0
func main() {
	// create http muxes
	serverhttp := http.NewServeMux()
	clienthttp := http.NewServeMux()

	// create server
	config := osin.NewServerConfig()
	sstorage := example.NewTestStorage()
	sstorage.SetClient("1234", &osin.DefaultClient{
		Id:          "1234",
		Secret:      "aabbccdd",
		RedirectUri: "http://localhost:14001/appauth",
	})
	server := osin.NewServer(config, sstorage)

	// create client
	cliconfig := &osincli.ClientConfig{
		ClientId:     "1234",
		ClientSecret: "aabbccdd",
		AuthorizeUrl: "http://localhost:14000/authorize",
		TokenUrl:     "http://localhost:14000/token",
		RedirectUrl:  "http://localhost:14001/appauth",
	}
	client, err := osincli.NewClient(cliconfig)
	if err != nil {
		panic(err)
	}

	// create a new request to generate the url
	areq := client.NewAuthorizeRequest(osincli.CODE)

	// SERVER

	// Authorization code endpoint
	serverhttp.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
	serverhttp.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
	serverhttp.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)
	})

	// CLIENT

	// Home
	clienthttp.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		u := areq.GetAuthorizeUrl()

		w.Write([]byte(fmt.Sprintf("<a href=\"%s\">Login</a>", u.String())))
	})

	// Auth endpoint
	clienthttp.HandleFunc("/appauth", func(w http.ResponseWriter, r *http.Request) {
		// parse a token request
		areqdata, err := areq.HandleRequest(r)
		if err != nil {
			w.Write([]byte(fmt.Sprintf("ERROR: %s\n", err)))
			return
		}

		treq := client.NewAccessRequest(osincli.AUTHORIZATION_CODE, areqdata)

		// show access request url (for debugging only)
		u2 := treq.GetTokenUrl()
		w.Write([]byte(fmt.Sprintf("Access token URL: %s\n", u2.String())))

		// exchange the authorize token for the access token
		ad, err := treq.GetToken()
		if err != nil {
			w.Write([]byte(fmt.Sprintf("ERROR: %s\n", err)))
			return
		}
		w.Write([]byte(fmt.Sprintf("Access token: %+v\n", ad)))
	})

	go http.ListenAndServe(":14001", clienthttp)
	http.ListenAndServe(":14000", serverhttp)
}
Esempio n. 29
0
package controllers

import (
	"fmt"
	"github.com/RangelReale/osin"
	"github.com/revel/revel"
	"golang.org/x/oauth2"
	"restful/app/helpers"
)

var cfg = osin.NewServerConfig()
var server = osin.NewServer(cfg, helpers.NewStorage())

type App struct {
	*revel.Controller
}

func (c App) Init() revel.Result {

	if c.Controller.Action != "App.Index" &&
		c.Controller.Action != "App.Token" &&
		c.Controller.Action != "App.GetToken" {

		if c.Session["access_token"] != c.Params.Get("access_token") {
			mp := map[string]interface{}{
				"error": 1,
			}
			return c.RenderJson(mp)
		}
	}
Esempio n. 30
0
// Init configures the router and returns the *echo.Echo struct
// enableLog set to true enable echo middleware logger
func Init(enableLog bool) *echo.Echo {
	e := echo.New()
	if enableLog {
		e.Use(middleware.Logger())
	}
	e.Pre(middleware.RemoveTrailingSlash())

	// Create the Authorization server for OAuth2
	authConfig := osin.NewServerConfig()
	// Configure the Authorization server
	authConfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.CODE, osin.TOKEN}
	authConfig.AllowedAccessTypes = osin.AllowedAccessType{
		osin.AUTHORIZATION_CODE,
		osin.REFRESH_TOKEN,
		osin.PASSWORD,
		osin.CLIENT_CREDENTIALS,
	}
	authConfig.AllowGetAccessRequest = true
	authConfig.AllowClientSecretInParams = true

	// Create the storage for osin (where to save oauth infos)
	var authStorage nerdz.OAuth2Storage
	authorizationServer := osin.NewServer(authConfig, &authStorage)

	// Initialize oauth2 server implementation
	oauth2.Init(authorizationServer)

	basePath := e.Group("/v" + strconv.Itoa(VERSION))

	/**************************************************************************
	* ROUTE /oauth2
	* Authorization not required.
	***************************************************************************/
	o := basePath.Group("/oauth2")
	o.GET("/authorize", oauth2.Authorize())
	o.POST("/authorize", oauth2.Authorize())
	o.GET("/token", oauth2.Token())
	o.GET("/info", oauth2.Info())

	/**************************************************************************
	* ROUTE /users/:id
	* Authorization required
	***************************************************************************/
	usersG := basePath.Group("/users") // users Group
	usersG.Use(authorization())
	usersG.Use(user.SetOther())
	usersG.GET("/:id", user.Info())
	usersG.GET("/:id/friends", user.Friends())
	usersG.GET("/:id/followers", user.Followers())
	usersG.GET("/:id/whitelist", user.Whitelist())
	usersG.GET("/:id/whitelisting", user.Whitelisting())
	usersG.GET("/:id/blacklist", user.Blacklist())
	usersG.GET("/:id/blacklisting", user.Blacklisting())
	usersG.GET("/:id/following/users", user.UserFollowing())
	usersG.GET("/:id/following/projects", user.ProjectFollowing())
	// uses setPostlist middleware
	usersG.GET("/:id/posts", user.Posts(), setPostlist())
	usersG.POST("/:id/posts", user.NewPost())
	// requests below uses the user.SetPost() middleware to refer to the requested post
	usersG.GET("/:id/posts/:pid", user.Post(), user.SetPost())
	usersG.PUT("/:id/posts/:pid", user.EditPost(), user.SetPost())
	usersG.DELETE("/:id/posts/:pid", user.DeletePost(), user.SetPost())
	// Votes
	usersG.GET("/:id/posts/:pid/votes", user.PostVotes(), user.SetPost())
	// Vote can be used to add/edit/delete the vote, just changing the vote value
	usersG.POST("/:id/posts/:pid/votes", user.NewPostVote(), user.SetPost())
	// Bookmark
	usersG.GET("/:id/posts/:pid/bookmarks", user.PostBookmarks(), user.SetPost())
	usersG.POST("/:id/posts/:pid/bookmarks", user.NewPostBookmark(), user.SetPost())
	usersG.DELETE("/:id/posts/:pid/bookmarks", user.DeletePostBookmark(), user.SetPost())
	// Lurk
	usersG.GET("/:id/posts/:pid/lurks", user.PostLurks(), user.SetPost())
	usersG.POST("/:id/posts/:pid/lurks", user.NewPostLurk(), user.SetPost())
	usersG.DELETE("/:id/posts/:pid/lurks", user.DeletePostLurk(), user.SetPost())
	// Lock
	usersG.GET("/:id/posts/:pid/locks", user.PostLock(), user.SetPost())
	usersG.POST("/:id/posts/:pid/locks", user.NewPostLock(), user.SetPost())
	usersG.DELETE("/:id/posts/:pid/locks", user.DeletePostLock(), user.SetPost())
	usersG.POST("/:id/posts/:pid/locks/:target", user.NewPostUserLock(), user.SetPost())
	usersG.DELETE("/:id/posts/:pid/locks/:target", user.DeletePostUserLock(), user.SetPost())
	// uses setCommentList middleware
	usersG.GET("/:id/posts/:pid/comments", user.PostComments(), user.SetPost(), setCommentList())
	usersG.POST("/:id/posts/:pid/comments", user.NewPostComment(), user.SetPost())
	// requests below uses user.SetComment middleware
	usersG.GET("/:id/posts/:pid/comments/:cid", user.PostComment(), user.SetPost(), user.SetComment())
	usersG.PUT("/:id/posts/:pid/comments/:cid", user.EditPostComment(), user.SetPost(), user.SetComment())
	usersG.DELETE("/:id/posts/:pid/comments/:cid", user.DeletePostComment(), user.SetPost(), user.SetComment())
	// Votes
	usersG.GET("/:id/posts/:pid/comments/:cid/votes", user.PostCommentVotes(), user.SetPost(), user.SetComment())
	usersG.POST("/:id/posts/:pid/comments/:cid/votes", user.NewPostCommentVote(), user.SetPost(), user.SetComment())

	/**************************************************************************
	* ROUTE /me
	* Authorization required
	***************************************************************************/
	meG := basePath.Group("/me")
	meG.Use(authorization())
	meG.Use(me.SetOther())
	// Read only
	meG.GET("", me.Info())
	meG.GET("/friends", me.Friends())
	meG.GET("/followers", me.Followers())
	// Read & write
	meG.GET("/following/users", me.UserFollowing())
	meG.POST("/following/users/:target", me.NewUserFollowing())
	meG.DELETE("/following/users/:target", me.DeleteUserFollowing())
	meG.GET("/following/projects", me.ProjectFollowing())
	meG.POST("/following/projects/:target", me.NewProjectFollowing())
	meG.DELETE("/following/projects/:target", me.DeleteProjectFollowing())
	meG.GET("/whitelist", me.Whitelist())
	meG.POST("/whitelist/:target", me.NewWhitelisted())
	meG.DELETE("/whitelist/:target", me.DeleteWhitelisted())
	// Read only
	meG.GET("/whitelisting", me.Whitelisting())
	// Read & write
	meG.GET("/blacklist", me.Blacklist())
	meG.POST("/blacklist/:target", me.NewBlacklisted())
	meG.DELETE("/blacklist/:target", me.DeleteBlacklisted())
	// Read only
	meG.GET("/blacklisting", me.Blacklisting())
	meG.GET("/home", me.Home(), setPostlist())
	meG.GET("/pms", me.Conversations())
	// uses setPmsOptions middleware
	meG.GET("/pms/:other", me.Conversation(), setPmsOptions())
	meG.POST("/pms/:other", me.NewPm())
	meG.DELETE("/pms/:other", me.DeleteConversation())
	// requests below uses the user.SetPm() middleware to refer to the requested pm
	meG.GET("/pms/:other/:pmid", me.Pm(), me.SetPm())
	// Disabled. At the moment pms' edit is not supported
	//meG.PUT("/pms/:other/:pmid", me.EditPm(), me.SetPm())
	meG.DELETE("/pms/:other/:pmid", me.DeletePm(), me.SetPm())

	// uses setPostlist middleware
	meG.GET("/posts", me.Posts(), setPostlist())
	meG.POST("/posts", me.NewPost())
	// requests below uses the user.SetPost() middleware to refer to the requested post
	meG.GET("/posts/:pid", me.Post(), me.SetPost())
	meG.PUT("/posts/:pid", me.EditPost(), me.SetPost())
	meG.DELETE("/posts/:pid", me.DeletePost(), me.SetPost())
	// Votes
	meG.GET("/posts/:pid/votes", me.PostVotes(), me.SetPost())
	// Vote can be used to add/edit/delete the vote, just changing the vote value
	meG.POST("/posts/:pid/votes", me.NewPostVote(), me.SetPost())
	// Bookmark
	meG.GET("/posts/:pid/bookmarks", me.PostBookmarks(), me.SetPost())
	meG.POST("/posts/:pid/bookmarks", me.NewPostBookmark(), me.SetPost())
	meG.DELETE("/posts/:pid/bookmarks", me.DeletePostBookmark(), me.SetPost())
	// Lurk
	meG.GET("/posts/:pid/lurks", me.PostLurks(), me.SetPost())
	meG.POST("/posts/:pid/lurks", me.NewPostLurk(), me.SetPost())
	meG.DELETE("/posts/:pid/lurks", me.DeletePostLurk(), me.SetPost())
	// Lock
	meG.GET("/posts/:pid/locks", me.PostLock(), me.SetPost())
	meG.POST("/posts/:pid/locks", me.NewPostLock(), me.SetPost())
	meG.DELETE("/posts/:pid/locks", me.DeletePostLock(), me.SetPost())
	meG.POST("/posts/:pid/locks/:target", me.NewPostUserLock(), me.SetPost())
	meG.DELETE("/posts/:pid/locks/:target", me.DeletePostUserLock(), me.SetPost())
	// uses setCommentList middleware
	meG.GET("/posts/:pid/comments", me.PostComments(), me.SetPost(), setCommentList())
	meG.POST("/posts/:pid/comments", me.NewPostComment(), me.SetPost())
	// requests below uses me.SetComment middleware
	meG.GET("/posts/:pid/comments/:cid", me.PostComment(), me.SetPost(), me.SetComment())
	meG.PUT("/posts/:pid/comments/:cid", me.EditPostComment(), me.SetPost(), me.SetComment())
	meG.DELETE("/posts/:pid/comments/:cid", me.DeletePostComment(), me.SetPost(), me.SetComment())
	// Votes
	meG.GET("/posts/:pid/comments/:cid/votes", me.PostCommentVotes(), me.SetPost(), me.SetComment())
	meG.POST("/posts/:pid/comments/:cid/votes", me.NewPostCommentVote(), me.SetPost(), me.SetComment())

	/**************************************************************************
	* ROUTE /projects/:id
	* Authorization required
	***************************************************************************/
	projectG := basePath.Group("/projects") // users Group
	projectG.Use(authorization())
	projectG.Use(project.SetProject())
	projectG.GET("/:id", project.Info())
	projectG.GET("/:id/members", project.Members())
	projectG.GET("/:id/followers", project.Followers())
	// uses setPostlist middleware
	projectG.GET("/:id/posts", project.Posts(), setPostlist())
	projectG.POST("/:id/posts", project.NewPost())
	// requests below uses the project.SetPost() middleware to refer to the requested post
	projectG.GET("/:id/posts/:pid", project.Post(), project.SetPost())
	projectG.PUT("/:id/posts/:pid", project.EditPost(), project.SetPost())
	projectG.DELETE("/:id/posts/:pid", project.DeletePost(), project.SetPost())
	// Votes
	projectG.GET("/:id/posts/:pid/votes", project.PostVotes(), project.SetPost())
	// Vote can be used to add/edit/delete the vote, just changing the vote value
	projectG.POST("/:id/posts/:pid/votes", project.NewPostVote(), project.SetPost())
	// Bookmark
	projectG.GET("/:id/posts/:pid/bookmarks", project.PostBookmarks(), project.SetPost())
	projectG.POST("/:id/posts/:pid/bookmarks", project.NewPostBookmark(), project.SetPost())
	projectG.DELETE("/:id/posts/:pid/bookmarks", project.DeletePostBookmark(), project.SetPost())
	// Lurk
	projectG.GET("/:id/posts/:pid/lurks", project.PostLurks(), project.SetPost())
	projectG.POST("/:id/posts/:pid/lurks", project.NewPostLurk(), project.SetPost())
	projectG.DELETE("/:id/posts/:pid/lurks", project.DeletePostLurk(), project.SetPost())
	// Lock
	projectG.GET("/:id/posts/:pid/locks", project.PostLock(), project.SetPost())
	projectG.POST("/:id/posts/:pid/locks", project.NewPostLock(), project.SetPost())
	projectG.DELETE("/:id/posts/:pid/locks", project.DeletePostLock(), project.SetPost())
	projectG.POST("/:id/posts/:pid/locks/:target", project.NewPostUserLock(), project.SetPost())
	projectG.DELETE("/:id/posts/:pid/locks/:target", project.DeletePostUserLock(), project.SetPost())
	// uses setCommentList middleware
	projectG.GET("/:id/posts/:pid/comments", project.PostComments(), project.SetPost(), setCommentList())
	projectG.POST("/:id/posts/:pid/comments", project.NewPostComment(), project.SetPost())
	// requests below uses project.SetComment middleware
	projectG.GET("/:id/posts/:pid/comments/:cid", project.PostComment(), project.SetPost(), project.SetComment())
	projectG.PUT("/:id/posts/:pid/comments/:cid", project.EditPostComment(), project.SetPost(), project.SetComment())
	projectG.DELETE("/:id/posts/:pid/comments/:cid", project.DeletePostComment(), project.SetPost(), project.SetComment())
	// Votes
	projectG.GET("/:id/posts/:pid/comments/:cid/votes", project.PostCommentVotes(), project.SetPost(), project.SetComment())
	projectG.POST("/:id/posts/:pid/comments/:cid/votes", project.NewPostCommentVote(), project.SetPost(), project.SetComment())

	/**************************************************************************
	* Stream API
	* ROUTE /stream/me
	* Authorization required
	***************************************************************************/
	s := basePath.Group("/stream/me")
	s.Use(authorization())
	// notification for current logged in user
	s.GET("/notifications", stream.Notifications())
	// TODO
	// /stream/users group
	//streamUsers := s.Group("/users/:id")
	// live update of current open profile
	//streamUsers.GET("/", stream.UserPosts())
	// live update of comments on current post
	//streamUsers.GET("/:pid/comments", stream.UserPostComments())

	return e
}