jwtauth

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2020 License: MIT Imports: 14 Imported by: 0

README

JWT Auth Golang for Postgres

About this Project

The idea of the App is:

"A library to auth with jwt in golang with postgres".

Why?

This project is part of my personal portfolio, so, I'll be happy if you could provide me any feedback about the project, code, structure or anything that you can report that could make me a better developer!

Email-me: boscardinvinicius@gmail.com

Connect with me at LinkedIn.

Functionalities

  • Verify auth and generete a token object with 40 seconds expiration to manage access.

  • Get a refreshed token.

Getting Started

Prerequisites

To run this project in the development mode, you'll need to have a basic environment to run:

  • A Golang SDK, that can be found here.
Installing

Using lib

Config two tables into your database exactly like this!



$ go get github.com/booscaaa/jwtauth


Config the file .env with .env.example
DB_HOST=
DB_USER=
DB_PASSWORD=
DB_NAME=
BCRYPT_HASH_SECRET=    #secret hash for reniew token
HASH_CRYPT=    #secret hash for JWT



Import lib

import (
	"github.com/booscaaa/jwtauth"
)


Call SessionCreate to create a valid session
func Create(writer http.ResponseWriter, r *http.Request) {
	if r.Method == "OPTIONS" {
		writer.WriteHeader(http.StatusOK)
	} else {
		var access jwtauth.Access
		if err := json.NewDecoder(r.Body).Decode(&access); err != nil {
			writer.WriteHeader(http.StatusInternalServerError)
			writer.Write([]byte("500 - Something bad happened!"))
		} else {
			defer r.Body.Close()
			SessionCreate(access, writer)
		}
	}
}


Call SessionRefresh to create new valid session

func Refresh(writer http.ResponseWriter, r *http.Request) {
	if r.Method == "OPTIONS" {
		writer.WriteHeader(http.StatusOK)
	} else {
		bearToken := r.Header.Get("Authorization")  // this bear token must be 4 params -- Bearer <token> <refreshCryptToken> <typeToken>
		SessionRefresh(bearToken, writer)
	}
}


Then create a middleware to manage the auth token in your application
func auth(next http.Handler) http.Handler {
	return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
		bearToken := request.Header.Get("Authorization") // bear token must be 2 params -- Bearer <token>
		if isAuth, access := VerifyToken(bearToken); isAuth {
			fmt.Println(access.Login)
			request = SetContextData(request, &access) // passing access struct to the request context to get it into controller method
			next.ServeHTTP(response, request)
		} else {
			response.WriteHeader(http.StatusUnauthorized)
			response.Write(ReturnMessage("Acesso negado"))
		}
	})
}



To get the access struct into your controller method just do it:
func YourMethodController(response http.ResponseWriter, request *http.Request) {
	a := GetContextData(request)
}

Libs to build the application

  • JWT - Library for golang jwt
  • Env - To get .env file
  • PQ - To get access to postgres database
  • Map struct - To convert jwt claims to structs
  • Crypto - To get a BCrypt hash to manage the token

You can send how many PR's do you want, I'll be glad to analyse and accept them! And if you have any question about the project...

Email-me: boscardinvinicius@gmail.com

Connect with me at LinkedIn

Thank you!

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractToken

func ExtractToken(bearToken string) string

func GetConnection

func GetConnection() *sql.DB

func ReturnMessage

func ReturnMessage(message string) []byte

ReturnMessage .

func SessionCreate

func SessionCreate(access Access, writer http.ResponseWriter)

SessionCreate .

func SessionRefresh

func SessionRefresh(bearToken string, writer http.ResponseWriter)

SessionRefresh .

func SetContextData

func SetContextData(r *http.Request, d *Access) (ro *http.Request)

Types

type Access

type Access struct {
	ID       int64  `json:"id"`
	Login    string `json:"login"`
	Password string `json:"password"`
	Email    string `json:"email"`
}

Access .

func GetContextData

func GetContextData(r *http.Request) (d Access)

func VerifyToken

func VerifyToken(bearToken string) (bool, Access)

VerifyToken .

type Auth

type Auth struct {
	Token   string `json:"token"`
	Refresh string `json:"refresh"`
	Type    string `json:"type"`
}

Auth .

func CreateToken

func CreateToken(tokenAuth TokenAuth, hash string) Auth

CreateToken .

type Message

type Message struct {
	Message string `json:"message"`
}

Message .

type MyError

type MyError struct {
	Code          pq.ErrorCode `json:"code"`
	Error         string       `json:"error"`
	Message       string       `json:"message"`
	InternalQuery error        `json:"internalQuery"`
}

MyError .

func CheckErr

func CheckErr(err error) (MyError, bool)

CheckErr .

func (MyError) ReturnError

func (e MyError) ReturnError() []byte

ReturnError .

type Session

type Session struct {
	Hash      string
	IsRevoked bool
	Access    Access
	Auth      Auth
	DB        *sql.DB
}

type TokenAuth

type TokenAuth struct {
	Access Access `json:"access,omitempty"`
	Exp    int64  `json:"exp,omitempty"`
	jwt.StandardClaims
}

TokenAuth .

Jump to

Keyboard shortcuts

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