auth

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2023 License: Apache-2.0 Imports: 14 Imported by: 3

README

Auth

ci codecov Go Reference

Auth is a RESTFul Authentication and Authorization package for Golang HTTP apps.

It handles the common tasks of registration, logging in, logging out, JWT token generation, and JWT token verification.

Installation

$ go get github.com/rest-go/auth

Usage

import auth to your app, create auth.Handler and auth.Middleware based on requirements.

package main

import (
	"log"
	"net/http"

	"github.com/rest-go/auth"
)

func handle(w http.ResponseWriter, req *http.Request) {
	user := auth.GetUser(req)
	if user.IsAnonymous() {
		w.WriteHeader(http.StatusUnauthorized)
	} else {
		w.WriteHeader(http.StatusOK)
	}
}

func main() {
	dbURL := "sqlite://my.db"
	jwtSecret := "my secret"
	authHandler, err := auth.NewHandler(dbURL, []byte(jwtSecret))
	if err != nil {
		log.Fatal(err)
	}
	http.Handle("/auth/", authHandler)

	middleware := auth.NewMiddleware([]byte(jwtSecret))
	http.Handle("/", middleware(http.HandlerFunc(handle)))
	log.Fatal(http.ListenAndServe(":8000", nil)) //nolint:gosec
}

Setup database

Send a POST request to /auth/setup to set up database tables for users. This will also create an admin user account and return the username and password in the response.

$ curl -XPOST "localhost:8000/auth/setup"

Auth handler

The Auth struct implements the http.Hanlder interface and provides the below endpoints for user management.

  1. Register
$ curl  -XPOST "localhost:8000/auth/register" -d '{"username":"hello", "password": "world"}'
  1. Login
$ curl  -XPOST "localhost:8000/auth/login" -d '{"username":"hello", "password": "world"}'
  1. Logout

Currently, the authentication mechanism is based on JWT token only, logout is a no-op on the server side, and the client should clear the token by itself.

$ curl  -XPOST "localhost:8000/auth/logout"

Auth middleware and GetUser

Auth middleware will parse JWT token in the HTTP header, and when successful, set the user in the request context, the GetUser method can be used to get the user from the request.

user := auth.GetUser(req)

Documentation

Overview

package auth provide restful interface for authentication

Index

Constants

View Source
const (
	AuthorizationHeader = "Authorization"
	AuthUserKey         = AuthUserCtxKey("auth-user")
)
View Source
const (
	// the name of the policies table
	PolicyTableName = "auth_policies"
)
View Source
const (
	// The name of the users table
	UserTableName = "auth_users"
)

Variables

This section is empty.

Functions

func GenJWTToken

func GenJWTToken(secret []byte, data map[string]any) (string, error)

GenJWTToken generate and return jwt token

func HashPassword

func HashPassword(password string) (string, error)

HashPassword generate the hashed password for a plain password

func ParseJWTToken

func ParseJWTToken(secret []byte, tokenString string) (map[string]any, error)

ParseJWTToken parse tokenString and return data if token is valid

func Setup

func Setup(db *sql.DB) (username, password string, err error)

Setup setup database tables and create an admin user account

Types

type Action

type Action int
const (
	ActionCreate Action = iota
	ActionRead
	ActionUpdate
	ActionDelete
	ActionReadMine // read with ?mine query, usually filter by user_id field
)

func (Action) String

func (a Action) String() string

type AuthUserCtxKey

type AuthUserCtxKey string

type Handler

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

Handler is handler with auth endpoints like `register`, `login`, and `logout`

func NewHandler

func NewHandler(dbURL string, secret []byte) (*Handler, error)

NewHandler return a Handler with provided database url and JWT secret

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler interface

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware is a type alias for http handler middleware

func NewMiddleware

func NewMiddleware(secret []byte) Middleware

NewMiddleware create a middleware using provided secret

type Policy

type Policy struct {
	ID          int64  `json:"id"`
	Description string `json:"description"`
	TableName   string `json:"table_name"`
	Action      string `json:"action"`
	Expression  string `json:"expression"`
}

Policy represents a security policy against a table

type User

type User struct {
	ID       int64  `json:"id"`
	Username string `json:"username"`
	Password string `json:"password"`
	IsAdmin  bool   `json:"is_admin"`
}

User represents a request user

func GetUser

func GetUser(r *http.Request) *User

GetUser return the user in request context

func (*User) HasPerm

func (u *User) HasPerm(table string, action Action, policies map[string]map[string]string) (hasPerm bool, withUserIDColumn string)

HasPerm check whether user has permission to perform action on the table with provided policies

func (*User) IsAnonymous

func (u *User) IsAnonymous() bool

IsAuthenticated returns a bool to indicate whether user is anonymous

func (*User) IsAuthenticated

func (u *User) IsAuthenticated() bool

IsAuthenticated returns a bool to indicate whether user is authenticated

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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