oxorm

package module
v0.0.0-...-8e1c92b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2017 License: MIT Imports: 9 Imported by: 0

README

osin-xorm

Encrypt your tokens

Unfortunately, the osin library offers little capabilities for storing credentials like access or refresh tokens in a hashed or encrypted way. An attacker could gain access to your database through various attack vectors, steal these tokens and gain, for example, administrative access to your application.

Please be aware, that this library stores all data as-is and does not perform any sort of encryption or hashing.

Usage

First, install this library with go get "github.com/chinahdkj/osin-xorm".

package main

// Open url in browser:
// http://localhost:14000/app

import (
	"fmt"
	"net/http"
	"net/url"

	"github.com/RangelReale/osin"
	"github.com/RangelReale/osin/example"
	"github.com/chinahdkj/osin-xorm"
	"github.com/chinahdkj/xorm"
	_ "github.com/go-sql-driver/mysql"
)

func main() {

	urldb := "root:secret@tcp(localhost:3306)/osin?parseTime=true"
	db, err := xorm.NewDB("mysql", urldb)

	if err != nil {
		panic(err)
	}

	store := oxorm.New(db)

	err = store.CreateSchemas()
	if err != nil {
		panic(err)
	}
	cfg := osin.NewServerConfig()
	cfg.AllowGetAccessRequest = true
	cfg.AllowClientSecretInParams = true

	server := osin.NewServer(cfg, store)

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

	http.ListenAndServe(":14000", nil)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SHA256

func SHA256(sources ...string) string

Types

type OauthAccess

type OauthAccess struct {
	AccessToken  string  `json:"access_token" xorm:"pk VARCHAR(255) NOT NULL"`
	Client       string  `json:"client" xorm:"VARCHAR(255) NOT NULL"`
	Authorize    *string `json:"authorize" xorm:"VARCHAR(255) NULL"`
	Previous     *string `json:"previous" xorm:"VARCHAR(255) NULL"`
	RefreshToken *string `json:"refresh_token" xorm:"VARCHAR(255) NULL"`
	ExpiresIn    int64   `json:"expires_in" xorm:"INT(20) NOT NULL"`
	Scope        *string `json:"scope" xorm:"VARCHAR(255) NULL"`
	RedirectUri  *string `json:"redirect_uri" xorm:"VARCHAR(255) NOT NULL"`
	Extra        *string `json:"extra" xorm:"VARCHAR(255) NULL"`
	CreatedAt    int64   `json:"created_at" xorm:"INT(20) NOT NULL"`
}

type OauthAuthorize

type OauthAuthorize struct {
	Client      string  `json:"client" xorm:"VARCHAR(255) NOT NULL"`
	Code        string  `json:"code" xorm:"pk VARCHAR(255) NOT NULL"`
	ExpiresIn   int64   `json:"expires_in" xorm:"INT(20) NOT NULL"`
	Scope       *string `json:"scope" xorm:"VARCHAR(255) NULL"`
	RedirectUri *string `json:"redirect_uri" xorm:"VARCHAR(255) NOT NULL"`
	State       *string `json:"state" xorm:"VARCHAR(255) NULL"`
	Extra       *string `json:"extra" xorm:"VARCHAR(255) NULL"`
	CreatedAt   int64   `json:"created_at" xorm:"INT(20) NOT NULL"`
}

type OauthClient

type OauthClient struct {
	Id          string  `json:"id" xorm:"pk VARCHAR(255) NOT NULL"`
	Secret      string  `json:"secret" xorm:"VARCHAR(255) NOT NULL"`
	Extra       *string `json:"extra" xorm:"VARCHAR(255) NULL"`
	RedirectUri *string `json:"redirect_uri" xorm:"VARCHAR(255) NULL"`
}

func (*OauthClient) ClientSecretMatches

func (this *OauthClient) ClientSecretMatches(secret string) bool

func (*OauthClient) GetId

func (this *OauthClient) GetId() string

Client id

func (*OauthClient) GetRedirectUri

func (this *OauthClient) GetRedirectUri() string

Base client uri

func (*OauthClient) GetSecret

func (this *OauthClient) GetSecret() string

Client secret

func (*OauthClient) GetUserData

func (this *OauthClient) GetUserData() interface{}

Data to be passed to storage. Not used by the library.

type OauthExpires

type OauthExpires struct {
	Id        string `json:"id" xorm:"pk VARCHAR(255) NOT NULL"`
	Token     string `json:"token" xorm:"index VARCHAR(255) NOT NULL"`
	ExpiresAt int64  `json:"expires_at" xorm:"index INT(20) NOT NULL"`
}

type OauthRefresh

type OauthRefresh struct {
	Token  string `json:"token" xorm:"pk VARCHAR(255) NOT NULL"`
	Access string `json:"access" xorm:"VARCHAR(255) NOT NULL"`
}

type Storage

type Storage struct {
	// contains filtered or unexported fields
}

Storage implements interface "github.com/RangelReale/osin".Storage and interface "github.com/felipeweb/osin-mysql/storage".Storage

func New

func New(db *xorm.Engine) *Storage

New returns a new mysql storage instance.

func (*Storage) AddExpireAtData

func (s *Storage) AddExpireAtData(code string, expireAt time.Time) error

AddExpireAtData add info in expires table

func (*Storage) Clone

func (s *Storage) Clone() osin.Storage

Clone the storage if needed. For example, using mgo, you can clone the session with session.Clone to avoid concurrent access problems. This is to avoid cloning the connection at each method access. Can return itself if not a problem.

func (*Storage) Close

func (s *Storage) Close()

Close the resources the Storage potentially holds (using Clone for example)

func (*Storage) CreateClient

func (s *Storage) CreateClient(c osin.Client) error

CreateClient stores the client in the database and returns an error, if something went wrong.

func (*Storage) CreateClientWithInformation

func (s *Storage) CreateClientWithInformation(id string, secret string, redirectURI string, userData interface{}) osin.Client

CreateClientWithInformation Makes easy to create a osin.DefaultClient

func (*Storage) CreateSchemas

func (s *Storage) CreateSchemas() error

CreateSchemas creates the schemata, if they do not exist yet in the database. Returns an error if something went wrong.

func (*Storage) GetClient

func (s *Storage) GetClient(id string) (osin.Client, error)

GetClient loads the client by id

func (*Storage) LoadAccess

func (s *Storage) LoadAccess(code string) (*osin.AccessData, error)

LoadAccess retrieves access data by token. Client information MUST be loaded together. AuthorizeData and AccessData DON'T NEED to be loaded if not easily available. Optionally can return error if expired.

func (*Storage) LoadAuthorize

func (s *Storage) LoadAuthorize(code string) (*osin.AuthorizeData, error)

LoadAuthorize looks up AuthorizeData by a code. Client information MUST be loaded together. Optionally can return error if expired.

func (*Storage) LoadRefresh

func (s *Storage) LoadRefresh(code string) (*osin.AccessData, error)

LoadRefresh retrieves refresh AccessData. Client information MUST be loaded together. AuthorizeData and AccessData DON'T NEED to be loaded if not easily available. Optionally can return error if expired.

func (*Storage) RemoveAccess

func (s *Storage) RemoveAccess(code string) (err error)

RemoveAccess revokes or deletes an AccessData.

func (*Storage) RemoveAuthorize

func (s *Storage) RemoveAuthorize(code string) (err error)

RemoveAuthorize revokes or deletes the authorization code.

func (*Storage) RemoveClient

func (s *Storage) RemoveClient(id string) error

RemoveClient removes a client (identified by id) from the database. Returns an error if something went wrong.

func (*Storage) RemoveExpireAtData

func (s *Storage) RemoveExpireAtData(code string) error

RemoveExpireAtData remove info in expires table

func (*Storage) RemoveRefresh

func (s *Storage) RemoveRefresh(code string) error

RemoveRefresh revokes or deletes refresh AccessData.

func (*Storage) SaveAccess

func (s *Storage) SaveAccess(data *osin.AccessData) (err error)

SaveAccess writes AccessData. If RefreshToken is not blank, it must save in a way that can be loaded using LoadRefresh.

func (*Storage) SaveAuthorize

func (s *Storage) SaveAuthorize(data *osin.AuthorizeData) error

SaveAuthorize saves authorize data.

func (*Storage) UpdateClient

func (s *Storage) UpdateClient(c osin.Client) error

UpdateClient updates the client (identified by it's id) and replaces the values with the values of client.

Directories

Path Synopsis
Package storage defines an interface, which all osin-storage implementations are going to support.
Package storage defines an interface, which all osin-storage implementations are going to support.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL