gocialite

package module
v2.0.5 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2020 License: MIT Imports: 14 Imported by: 0

README

Gocialite

Travis CI build Available Drivers GoDoc GoReport GitHub contributors

Gocialite is a Socialite inspired package to manage social oAuth authentication without problems. The idea was born when I discovered that Goth is not so flexible: I was using Revel and it was impossible to connect them properly.

Installation

To install it, just run go get github.com/gadelkareem/gocialite/v2 and include it in your app: import "github.com/gadelkareem/gocialite/v2".

Available drivers

  • Amazon
  • Asana
  • Bitbucket
  • Facebook
  • Foursquare
  • Github
  • Google
  • LinkedIn
  • Slack

Create new driver

Please see Contributing page to learn how to create new driver and test it.

Set scopes

Note: Gocialite set some default scopes for the user profile, for example for Facebook it specify email and for Google profile, email.
When you use the following method, you don't have to rewrite them.

Use the Scopes([]string) method of your Gocial instance. Example:

gocial.Scopes([]string{"public_repo"})

Set driver

Use the Driver(string) method of your Gocial instance. Example:

gocial.Driver("facebook")

The driver name will be the provider name in lowercase.

How to use it

Note: All Gocialite methods are chainable.

Declare a "global" variable outside your main func:

import (
	...
)

var gocial = gocialite.NewDispatcher()

func main() {

Then create a route to use as redirect bridge, for example /auth/github. With this route, the user will be redirected to the provider oAuth login. In this case we use Gin Tonic as router. You have to specify the provider with the Driver() method. Then, with Scopes(), you can set a list of scopes as slice of strings. It's optional.
Finally, with Redirect() you can obtain the redirect URL. In this method you have to pass three parameters:

  1. Client ID
  2. Client Secret
  3. Redirect URL
func main() {
	router := gin.Default()

	router.GET("/auth/github", redirectHandler)

	router.Run("127.0.0.1:9090")
}

// Redirect to correct oAuth URL
func redirectHandler(c *gin.Context) {
	authURL, err := gocial.New().
		Driver("github"). // Set provider
		Scopes([]string{"public_repo"}). // Set optional scope(s)
		Redirect( // 
			"xxxxxxxxxxxxxx", // Client ID
			"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", // Client Secret
			"http://localhost:9090/auth/github/callback", // Redirect URL
		)

	// Check for errors (usually driver not valid)
	if err != nil {
		c.Writer.Write([]byte("Error: " + err.Error()))
		return
	}

	// Redirect with authURL
	c.Redirect(http.StatusFound, authURL) // Redirect with 302 HTTP code
}

Now create a callback handler route, where we'll receive the content from the provider.
In order to validate the oAuth and retrieve the data, you have to invoke the Handle() method with two query parameters: state and code. In your URL, they will look like this: http://localhost:9090/auth/github/callback?state=xxxxxxxx&code=xxxxxxxx.
The Handle() method returns the user info, the token and error if there's one or nil.
If there are no errors, in the user variable you will find the logged in user information and in the token one, the token info (it's a oauth2.Token struct). The data of the user - which is a gocialite.User struct - are the following:

  • ID
  • FirstName
  • LastName
  • FullName
  • Email
  • Avatar (URL)
  • Raw (the full JSON returned by the provider)

Note that they can be empty.

func main() {
	router := gin.Default()

	router.GET("/auth/github", redirectHandler)
	router.GET("/auth/github/callback", callbackHandler)

	router.Run("127.0.0.1:9090")
}

// Redirect to correct oAuth URL
// Handle callback of provider
func callbackHandler(c *gin.Context) {
	// Retrieve query params for code and state
	code := c.Query("code")
	state := c.Query("state")

	// Handle callback and check for errors
	user, token, err := gocial.Handle(state, code)
	if err != nil {
		c.Writer.Write([]byte("Error: " + err.Error()))
		return
	}

	// Print in terminal user information
	fmt.Printf("%#v", token)
	fmt.Printf("%#v", user)

	// If no errors, show provider name
	c.Writer.Write([]byte("Hi, " + user.FullName))
}

Please take a look to multi provider example for a full working code with Gin Tonic and variable provider handler.

Contributors

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RegisterNewDriver

func RegisterNewDriver(driver string, defaultscopes []string, callback func(client *http.Client, u *structs.User), endpoint oauth2.Endpoint, apimap, usermap map[string]string)

RegisterNewDriver adds a new driver to the existing set

Types

type Dispatcher

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

Dispatcher allows to safely issue concurrent Gocials

func NewDispatcher

func NewDispatcher(c cachita.Cache) *Dispatcher

NewDispatcher creates new Dispatcher

func (*Dispatcher) Handle

func (d *Dispatcher) Handle(state, code string) (*structs.User, *oauth2.Token, error)

Handle callback. Can be called only once for given state.

func (*Dispatcher) New

func (d *Dispatcher) New() *Gocial

New Gocial instance

type Gocial

type Gocial struct {
	DriverName, State string
	ScopesArr         []string
	Conf              *oauth2.Config
	User              structs.User
	Token             *oauth2.Token
	// contains filtered or unexported fields
}

Gocial is the main struct of the package

func (*Gocial) Driver

func (g *Gocial) Driver(driver string) *Gocial

Driver is needed to choose the correct social

func (*Gocial) Handle

func (g *Gocial) Handle(state, code string) error

Handle callback from provider

func (*Gocial) Redirect

func (g *Gocial) Redirect(clientID, clientSecret, redirectURL string) (string, error)

Redirect returns an URL for the selected social oAuth login

func (*Gocial) Scopes

func (g *Gocial) Scopes(scopes []string) *Gocial

Scopes is used to set the oAuth scopes, for example "user", "calendar"

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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