auth

package module
v1.2.5-alpha Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2020 License: Apache-2.0 Imports: 16 Imported by: 2

README

Go Oauth2 Helper Module

Canonical source at https://gitlab.com/rwxrob/auth

Oauth2 Session

GoDoc License Go Report Card Coverage

Designed to help make command line Oauth2 easier to implement and use from shell scripts and other command line utilities.

Example Usage

Main
auth <name>
auth token <name>
auth grant <name>
auth refresh <name>
auth help
Create, Replace, Update, Delete (CRUD)
auth add
auth rm <name>
auth edit
auth export <file> [<name> ...]
auth import <file> [<name> ...]
View / Output
auth ls
auth conf 
auth json <name>
auth get access <name>
auth get refresh <name>
auth get type <name>
auth get expiry <name>
auth get state <name>
auth get code <name>
auth get id <name>
auth get secret <name>
auth get scopes <name>
auth get redirecturl <name>
auth get authurl <name>
auth get tokenurl <name>
auth get style <name>
Embed
curl -H "Authorization: Bearer $(auth <name>)" https://api.example.com/some

The auth command can be used in place of sensitive token and other credential information within shell scripts. By default, the user will be prompted when further authorization flow steps are needed, including the opening of a local graphical web browser automatically. The level of interaction can be isolated for scripts that must run without blocking on waits for interactivity.

Unlike many other authorization solutions, auth starts a local web server to handle the redirection and safely intercept the token that was upgraded from the authorization code. Other tools generally prompt for this to be cut and pasted in. If the opening of the web browser fails, a prompt is shown instead.

TODO

  • Add Oauth 1.0a support (twitter)
  • Add token revocation
  • As much test coverage as we can achieve without a mock token server
  • Add some detection of changes to the file since opened so don't overwrite with currently running process with the cache open (like vi)

Documentation

Overview

Package auth contains mostly Oauth2-specific convenience functions and structures to pick up where the official package leaves of. For example, caching of tokens and other related data in a way that is localized to the current user and easily retrievable by scripts and other Go code running with the permissions of that user.

The auth command is included under cmd. It is designed to be used by shell scripts to facilitate use of a common authentication cache for the current user.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddSession

func AddSession(a *App)

AddSession adds an authorization session for the given app to the internal sessions map for the package. SetAuthState() is called on the App and the state is used internally as the unique key for the session. Safe for concurrency through use of sync.RWMutex.

func ConfigFilePath

func ConfigFilePath() string

ConfigFilePath returns the path to the configuration file. First the AUTHCONF env var is checked and if not found the os.UserConfigDir will be checked for an auth/config.json file.

func Grant

func Grant(this interface{}) error

Grant runs through the Oauth2 authorization code grant flow avoiding interactive user input when possible by starting up a local HTTP server (or using the one that has already been started) to capture the incoming redirected data. Remember to Store after a Grant if needed.

func HandleRedirect

func HandleRedirect(w http.ResponseWriter, req *http.Request)

HandleRedirect processes all awaiting Oauth2 grant authorization sessions checking the states, receiving the code, and then upgrading the code to a token writing flushed simple text status messages along the way.

func Has

func Has(name string) int8

Has returns 1 if the given name exists in the cache, 0 if not, and -1 if cannot determine.

func Lookup

func Lookup(name string) (Config, *App, error)

Lookup returns a Config loaded from the configuration file cache and a reference to the specified app if found. An error is also returned to explain if either of them are nil for any reason.

Example
package main

import (
	"fmt"

	"gitlab.com/rwxrob/auth"
)

func main() {
	config, app, err := auth.Lookup("some")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(config.Has("some"))
	fmt.Println(err)
	fmt.Println(app.Name)
}
Output:

func OpenResource

func OpenResource(res string) error

OpenResource opens the the specified resource (URL, file, etc.) using the opener of the current system. Currently only linux, windows, and darwin are supported.

func StartLocalServer

func StartLocalServer() error

StartLocalServer start the main HTTP server locally to receive redirects from Authorize. The same server is used for everything that requires one in this package so care has been taken to ensure requests are handled such that they are safe for concurrency. The server is currently hard coded to the address localhost:8080 (and not :8080 which would expose the server to other external interfaces). Only the /redirected route is currently supported.

func Use

func Use(name string) (Config, *App, error)

Use is a the highest level entry point to this package. It returns the same values as Lookup() but also does whatever work is necessary to ensure that the named application has an updated access token. This includes potentially triggering the interactive flow with the user requiring authentication to the application through their web browser. For this reason Use() should not be called in situations where blocking on such interaction is not wanted. In such cases use Lookup() instead. Note that the named application should already exist and be present in the file located at ConfigFilePath().

func Valid

func Valid(name string) int8

Valid returns one of four values: 1 if an access token exists for the given name and has not expired, 0 if a token exists but has expired or has no refresh token, -1 if there is no access token, and -2 if an error prevents determining if it exists.

Types

type App

type App struct {
	Name      string
	AuthState string
	AuthCode  string
	sync.RWMutex
	oauth2.Config
	oauth2.Token
}

App is an oath2-centric data structure designed to potentially hold configuration data for other authentication methods supported by this package. The oauth2.Config is embedded as is oauth2.Token. This allows referencing different client applications by their user-friendly names while still using App exactly as would be done with either struct by itself.

func GetSession

func GetSession(state string) *App

GetSession returns a session from the internal map cache if found, otherwise nil.

func (App) JSON

func (a App) JSON() []byte

JSON returns a bytes buffer of compressed JSON suitable for saving and streaming. Otherwise it's the same as String().

func (*App) Load

func (a *App) Load(path string) error

Load loads the JSON data from the specified path.

func (*App) Parse

func (a *App) Parse(buf []byte) error

Parse is simply a wrapper for json.Unmarshal().

func (App) ParseRedirectURL

func (a App) ParseRedirectURL() (*url.URL, error)

ParseRedirectURI calls ParseRequestURI on RedirectURI.

func (App) Print

func (a App) Print()

Print prints as string to stdout.

func (App) RedirectHost

func (a App) RedirectHost() string

RedirectHost returns just the Host and Port portions of the RedirectURL suitable for passing to ListenAndServe() (addr) when starting the local server.

func (*App) Refresh

func (a *App) Refresh() error

Refresh calls Refresh only if needed. Does not grant.

func (*App) RefreshNow

func (a *App) RefreshNow() error

RefreshNow submits the refresh_token grant request to the app.TokenURL.

func (App) Save

func (a App) Save(path string) error

Save writes the App to disk at the specified path.

func (*App) SetAuthCode

func (a *App) SetAuthCode(code string)

SetAuthCode updates the AuthCode safely.

func (*App) SetAuthState

func (a *App) SetAuthState()

SetAuthState updates the state to a new unique (base32) string.

func (App) String

func (a App) String() string

String implements the Stringer interface as long form JSON.

type Config

type Config map[string]*App

Config contains a collection of App structures in a way that is designed to be stored as a single file to facilitate encoding, transfer, and encryption.

func OpenConfig

func OpenConfig() (Config, error)

OpenConfig loads the configuration file (see Config). Returns nil if unable to load.

func (Config) Has

func (c Config) Has(name string) bool

Has returns true of the name exists.

func (Config) JSON

func (c Config) JSON() []byte

JSON returns a bytes buffer of compressed JSON suitable for streaming. Otherwise it's the same as String().

func (*Config) Load

func (c *Config) Load(path string) error

Load reads the JSON data from the specified path.

func (*Config) Open

func (c *Config) Open() error

Open loads the JSON data from the ConfigFilePath path.

func (*Config) Parse

func (c *Config) Parse(buf []byte) error

Parse is simply a wrapper for json.Unmarshal().

func (Config) Print

func (c Config) Print()

Print prints as string to stdout.

func (Config) Save

func (c Config) Save(path string) error

Save writes the config JSON data to a file at specified path.

func (Config) Store

func (c Config) Store() error

Store saves to the file specified by ConfigFilePath(). See Save().

func (Config) String

func (c Config) String() string

String implements the Stringer interface as long form JSON.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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