net

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2021 License: MIT Imports: 8 Imported by: 7

README

go-network

Go Reference

A library exposing an implementation of tools usually required for communicating with RESTFul requests. You can find intercepting and authenticating middlewares as well as methods to authenticate jwt tokens. There are some utility methods for extracting values from request's query parameters as well.

Installation

The recommended way to get started using the Network driver is by using go modules to install the dependency in your project. This can be done either by importing packages from go-network and having the build step install the dependency or by explicitly running

go get github.com/atulanand206/go-network

How to implement

  • There are a couple of environment variables that you can set for using the jwt token authenticator.

  • There are additional methods which accepts the client secrets and expiry times if you'd like to use them directly.

  • CLIENT_SECRET : Client secret to be used for creating and authenticating access token.

  • TOKEN_EXPIRE_MINUTES : Duration of the validity of access token. The token gets expired after this duration.

  • REFRESH_CLIENT_SECRET : Client secret to be used for creating and authenticating refresh token.

  • REFRESH_TOKEN_EXPIRE_MINUTES : Duration of the validity of refresh token. The token gets expired after this duration.

  • The middleware interceptors can be used directly.

  • The CORS interceptor expects an environment variable for setting the allowed origin address.

  • CORS_ORIGIN : Set this as * or the url you'd like to allow the origin to accept the network requests.

  • There are examples available for refernce.

Author

  • Atul Anand

Documentation

Index

Examples

Constants

View Source
const (
	// Headers keys
	Accept         = "Accept"
	ContentTypeKey = "Content-Type"
	CorsOrigin     = "Access-Control-Allow-Origin"
	CorsHeaders    = "Access-Control-Allow-Headers"
	CorsMethods    = "Access-Control-Allow-Methods"

	// Headers values
	ApplicationJson = "application/json"
	Authorization   = "Authorization"

	// CORS value
	ValueCorsOrigin = "CORS_ORIGIN"

	// Token secret and expiry
	ClientSecret              = "CLIENT_SECRET"
	TokenExpireMinutes        = "TOKEN_EXPIRE_MINUTES"
	RefreshClientSecret       = "REFRESH_CLIENT_SECRET"
	RefreshTokenExpireMinutes = "REFRESH_TOKEN_EXPIRE_MINUTES"
)

Variables

This section is empty.

Functions

func Authenticate

func Authenticate(r *http.Request, secret string) (jwt.MapClaims, error)

Authenticates the jwt token with the given secret.

Example
claims := jwt.MapClaims{}
claims["name"] = "Judd"
secret := "this is a secret key"
expires := "1000"
token, _ := net.CreateToken(claims, secret, expires)

r, _ := http.NewRequest(http.MethodGet, "", nil)
r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
decryptedClaims, _ := net.Authenticate(r, secret)
name := decryptedClaims["name"]
fmt.Println(name)
Output:

Judd

func AuthenticateAccessToken

func AuthenticateAccessToken(r *http.Request) (jwt.MapClaims, error)

Authenticates the access token present in the request headers.

Example
claims := jwt.MapClaims{}
claims["name"] = "Judd"
secret := "this is a secret key"
expires := "1000"
os.Setenv("CLIENT_SECRET", secret)
os.Setenv("TOKEN_EXPIRE_MINUTES", expires)
token, _ := net.CreateAccessToken(claims)

r, _ := http.NewRequest(http.MethodGet, "", nil)
r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
decryptedClaims, _ := net.AuthenticateAccessToken(r)
name := decryptedClaims["name"]
fmt.Println(name)
// Output :
// Judd
Output:

func AuthenticateRefreshToken

func AuthenticateRefreshToken(r *http.Request) (jwt.MapClaims, error)

Authenticates the refresh token present in the request headers.

Example
claims := jwt.MapClaims{}
claims["name"] = "Judd"
secret := "this is a secret key"
expires := "1000"
os.Setenv("REFRESH_CLIENT_SECRET", secret)
os.Setenv("REFRESH_TOKEN_EXPIRE_MINUTES", expires)
token, _ := net.CreateRefreshToken(claims)

r, _ := http.NewRequest(http.MethodGet, "", nil)
r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
decryptedClaims, _ := net.AuthenticateRefreshToken(r)
name := decryptedClaims["name"]
fmt.Println(name)
// Output :
// Judd
Output:

func CreateAccessToken

func CreateAccessToken(claims jwt.MapClaims) (string, error)

Creates the access token for the username.

Example
claims := jwt.MapClaims{}
claims["name"] = "Judd"
secret := "this is a secret key"
expires := "1000"
os.Setenv("CLIENT_SECRET", secret)
os.Setenv("TOKEN_EXPIRE_MINUTES", expires)
token, _ := net.CreateAccessToken(claims)
fmt.Println(token)
Output:

func CreateRefreshToken

func CreateRefreshToken(claims jwt.MapClaims) (string, error)

Creates the refresh token for the username.

Example
claims := jwt.MapClaims{}
claims["name"] = "Judd"
secret := "this is a secret key"
expires := "1000"
os.Setenv("REFRESH_CLIENT_SECRET", secret)
os.Setenv("REFRESH_TOKEN_EXPIRE_MINUTES", expires)
token, _ := net.CreateRefreshToken(claims)
fmt.Println(token)
Output:

func CreateToken

func CreateToken(claims jwt.MapClaims, secret string, expires string) (string, error)

Creates the jwt token for the given parameters.

Example
claims := jwt.MapClaims{}
claims["name"] = "Judd"
secret := "this is a secret key"
expires := "1000"
token, _ := net.CreateToken(claims, secret, expires)
fmt.Println(token)
Output:

func ParamInt

func ParamInt(values url.Values, key string, def int) int

Extracts an int parameter from the values of query params.

Example
package main

import (
	"fmt"
	"net/url"

	net "github.com/atulanand206/go-network"
)

func main() {
	uri, _ := url.Parse("http://search.com?score=43&rating=93")
	v := uri.Query()
	v.Set("score", "43")
	v.Set("rating", "93")
	fmt.Println(net.ParamInt(v, "score", 3))
	fmt.Println(net.ParamInt(v, "rating", 3))
	fmt.Println(net.ParamInt(v, "wons", 9))
}
Output:

43
93
9

func ParamString

func ParamString(values url.Values, key string, def string) string

Extracts a string parameter from the values of query params.

Example
package main

import (
	"fmt"
	"net/url"

	net "github.com/atulanand206/go-network"
)

func main() {
	uri, _ := url.Parse("http://search.com?name=Ash&friend=Jess")
	v := uri.Query()
	fmt.Println(net.ParamString(v, "name", "Sara"))
	fmt.Println(net.ParamString(v, "friend", "Mark"))
	fmt.Println(net.ParamString(v, "winner", "Jamie"))
}
Output:

Ash
Jess
Jamie

Types

type MiddlewareChain

type MiddlewareChain []MiddlewareInterceptor

Type used for the Middleware chain as an array of MiddlewareInterceptor.

func (MiddlewareChain) Add

func (mwc MiddlewareChain) Add(interceptor ...MiddlewareInterceptor) MiddlewareChain

Adds an array of interceptors to the MiddlewareInterceptor chain.

func (MiddlewareChain) Handler

func (chain MiddlewareChain) Handler(handler http.HandlerFunc) http.HandlerFunc

Method used for attaching the MiddlewareChain for interception of http request.

type MiddlewareHandlerFunc

type MiddlewareHandlerFunc http.HandlerFunc

Type used for handling function after intercepting http request.

func (MiddlewareHandlerFunc) Intercept

Method called after intercepting http request.

type MiddlewareInterceptor

type MiddlewareInterceptor func(http.ResponseWriter, *http.Request, http.HandlerFunc)

Type used for intercepting http requests.

func ApplicationJsonInterceptor

func ApplicationJsonInterceptor() MiddlewareInterceptor

Interceptor which sets the content type as application/json.

func AuthenticationInterceptor

func AuthenticationInterceptor() MiddlewareInterceptor

Interceptor which checks if the header has the correct accessToken.

func CorsInterceptor

func CorsInterceptor(methods string) MiddlewareInterceptor

Interceptor which adds CORS related headers.

func RefreshAuthenticationInterceptor

func RefreshAuthenticationInterceptor() MiddlewareInterceptor

Interceptor which checks if the header has the correct refreshToken.

Jump to

Keyboard shortcuts

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