jwtpg

package
v0.0.48 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2023 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package jwtpg содержит реализацию jwt провайдера с одним единовременным токеном с использованием базы данных postgresql.

Для работы с пакетом токены должны храниться в таблицах такого вида:

   Column   |     Type      | Collation | Nullable | Default
------------+---------------+-----------+----------+---------
 id         | bigint        |           | not null |
 number     | bigint        |           | not null |
 purpose    | integer       |           | not null |
 secret     | character(64) |           | not null |
 expires_at | bigint        |           | not null |

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthorizationMaker

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

AuthorizationMaker - структура, имплементирующая интерфейс провайдера

func NewMaker

func NewMaker(tokenTables map[structs.Role]string, key string, queue *workerpoolpg.Queue,
	loader func(ctx context.Context, tx *pg.Transaction, acc *structs.Account) proto.Message,
	accessTokenTimeout, refreshTokenTimeout, authTimeout time.Duration) *AuthorizationMaker

NewMaker - создание AuthorizationMaker. tokenTables - названия таблиц с токенами, key - секретный ключ, queue - очередь для контроля потока запросов, loader - функция получения полного авторизационного ответа по аккаунту, accessTokenTimeout - время жизни access токена, refreshTokenTimeout - время жизни refresh токена, authTimeout - таймаут одной операции авторизации

func (*AuthorizationMaker) Auth

func (m *AuthorizationMaker) Auth(ctx context.Context, token string, purpose jwt2.Purpose,
	platform structs.Platform, versions []string, disabled ...structs.Role) (*structs.Account, int64, error)

Auth - реализация метода Auth интерфейса AuthProvider

Example
package main

import (
	"context"
	"fmt"
	"github.com/custom-app/sdk-go/auth/jwt"
	"github.com/custom-app/sdk-go/auth/jwt/jwtpg"
	"github.com/custom-app/sdk-go/service/workerpool/workerpoolpg"
	"github.com/custom-app/sdk-go/structs"
	"log"
	"time"
)

func main() {
	// создаем очередь для управления потоком запросов в бд
	authWorkers := make([]*workerpoolpg.Worker, 2)
	authQueue := workerpoolpg.NewQueue(10)
	for i := range authWorkers {
		authWorkers[i] = workerpoolpg.NewWorker(authQueue.GetQueue())
		go authWorkers[i].Run()
	}
	defer authQueue.Close()

	// инициализируем провайдера
	provider := jwtpg.NewMaker(map[structs.Role]string{
		0: "first_role_tokens",
		1: "second_role_tokens",
	}, "r3vbrb3b3fb3", authQueue, nil, time.Minute, time.Hour, time.Second)
	jwt.SetDefaultAuth(provider)

	// допустим, секрет токена найдется в таблице first_role_tokens
	res, num, err := jwt.Auth(context.Background(), "jwt-token", jwt.PurposeAccess, 0, []string{"0.0.1"})
	if err != nil {
		log.Panicln(err)
	}
	fmt.Println(res.Id, res.Role, res.Platform, res.Versions, num)
}
Output:

1 0 0 {0.0.1} 0

func (*AuthorizationMaker) AuthWithInfo

func (m *AuthorizationMaker) AuthWithInfo(ctx context.Context, token string, purpose jwt2.Purpose, platform structs.Platform,
	versions []string, disabled ...structs.Role) (*structs.Account, int64, proto.Message, error)

AuthWithInfo - реализация метода AuthWithInfo интерфейса AuthProvider

Example
package main

import (
	"context"
	"fmt"
	"github.com/custom-app/sdk-go/auth/jwt"
	"github.com/custom-app/sdk-go/auth/jwt/jwtpg"
	"github.com/custom-app/sdk-go/db/pg"
	"github.com/custom-app/sdk-go/service/workerpool/workerpoolpg"
	"github.com/custom-app/sdk-go/structs"
	"google.golang.org/protobuf/proto"
	"log"
	"time"
)

func main() {
	// создаем очередь для управления потоком запросов в бд
	authWorkers := make([]*workerpoolpg.Worker, 2)
	authQueue := workerpoolpg.NewQueue(10)
	for i := range authWorkers {
		authWorkers[i] = workerpoolpg.NewWorker(authQueue.GetQueue())
		go authWorkers[i].Run()
	}
	defer authQueue.Close()

	// инициализируем провайдера
	provider := jwtpg.NewMaker(map[structs.Role]string{
		0: "first_role_tokens",
		1: "second_role_tokens",
	}, "r3vbrb3b3fb3", authQueue,
		func(ctx context.Context, tx *pg.Transaction, acc *structs.Account) proto.Message {
			// код, вытягивающий данные аккаунта в Response
			return nil
		}, time.Minute, time.Hour, time.Second)
	jwt.SetDefaultAuth(provider)

	// допустим, секрет токена найдется в таблице first_role_tokens
	res, num, resp, err := jwt.AuthWithInfo(context.Background(), "jwt-token", jwt.PurposeAccess, 0, []string{"0.0.1"})
	if err != nil {
		log.Panicln(err)
	}
	fmt.Println(res.Id, res.Role, res.Platform, res.Versions, num)
	
Output:

...

func (*AuthorizationMaker) CreateTokens

func (m *AuthorizationMaker) CreateTokens(ctx context.Context, role structs.Role,
	id int64) (accessToken string, accessExpires int64, refreshToken string, refreshExpires int64, err error)

CreateTokens - реализация метода CreateTokens интерфейса AuthProvider

Example
package main

import (
	"context"
	"fmt"
	"github.com/custom-app/sdk-go/auth/jwt"
	"github.com/custom-app/sdk-go/auth/jwt/jwtpg"
	"github.com/custom-app/sdk-go/service/workerpool/workerpoolpg"
	"github.com/custom-app/sdk-go/structs"
	"log"
	"time"
)

func main() {
	// создаем очередь для управления потоком запросов в бд
	authWorkers := make([]*workerpoolpg.Worker, 2)
	authQueue := workerpoolpg.NewQueue(10)
	for i := range authWorkers {
		authWorkers[i] = workerpoolpg.NewWorker(authQueue.GetQueue())
		go authWorkers[i].Run()
	}
	defer authQueue.Close()

	// инициализируем провайдера
	provider := jwtpg.NewMaker(map[structs.Role]string{
		0: "first_role_tokens",
		1: "second_role_tokens",
	}, "r3vbrb3b3fb3", authQueue, nil, time.Minute, time.Hour, time.Second)
	jwt.SetDefaultAuth(provider)

	// создаем токен
	accessToken, accessExpiresAt, refreshToken, refreshExpiresAt, err := jwt.CreateTokens(context.Background(), 0, 1)
	if err != nil {
		log.Panicln(err)
	}
	fmt.Println(accessToken, accessExpiresAt)
	
Output:

token now + time.Hour

func (*AuthorizationMaker) CreateTokensWithTx

func (m *AuthorizationMaker) CreateTokensWithTx(ctx context.Context, tx *pg.Transaction, role structs.Role,
	id int64) (accessToken string, accessExpires int64, refreshToken string, refreshExpires int64, err error)

CreateTokensWithTx - вспомогательная функция создания токенов с открытой бд-транзакцией

func (*AuthorizationMaker) DropAllTokens

func (m *AuthorizationMaker) DropAllTokens(ctx context.Context, tx *pg.Transaction, role structs.Role, id int64) error

DropAllTokens - функция удаления всех токенов аккаунта

func (*AuthorizationMaker) DropOldTokens

func (m *AuthorizationMaker) DropOldTokens(ctx context.Context, timestamp int64) error

DropOldTokens - функция удаления устаревших токенов

func (*AuthorizationMaker) DropTokens

func (m *AuthorizationMaker) DropTokens(ctx context.Context, role structs.Role, id, number int64) error

DropTokens - реализация метода DropTokens интерфейса AuthProvider

func (*AuthorizationMaker) Logout

func (m *AuthorizationMaker) Logout(ctx context.Context, role structs.Role, id int64) error

Logout - реализация метода Logout интерфейса AuthProvider

func (*AuthorizationMaker) ReCreateTokens

func (m *AuthorizationMaker) ReCreateTokens(ctx context.Context, role structs.Role,
	id, number int64) (accessToken string, accessExpires int64, refreshToken string, refreshExpires int64, err error)

ReCreateTokens - реализация метода ReCreateTokens интерфейса AuthProvider

Example
package main

import (
	"context"
	"fmt"
	"github.com/custom-app/sdk-go/auth/jwt"
	"github.com/custom-app/sdk-go/auth/jwt/jwtpg"
	"github.com/custom-app/sdk-go/service/workerpool/workerpoolpg"
	"github.com/custom-app/sdk-go/structs"
	"log"
	"time"
)

func main() {
	// создаем очередь для управления потоком запросов в бд
	authWorkers := make([]*workerpoolpg.Worker, 2)
	authQueue := workerpoolpg.NewQueue(10)
	for i := range authWorkers {
		authWorkers[i] = workerpoolpg.NewWorker(authQueue.GetQueue())
		go authWorkers[i].Run()
	}
	defer authQueue.Close()

	// инициализируем провайдера
	provider := jwtpg.NewMaker(map[structs.Role]string{
		0: "first_role_tokens",
		1: "second_role_tokens",
	}, "r3vbrb3b3fb3", authQueue, nil, time.Minute, time.Hour, time.Second)
	jwt.SetDefaultAuth(provider)

	// пересоздаем токен
	accessToken, accessExpiresAt, refreshToken, refreshExpiresAt, err := jwt.ReCreateTokens(context.Background(), 0, 1, 0)
	if err != nil {
		log.Panicln(err)
	}
	fmt.Println(accessToken, accessExpiresAt)
	
Output:

token now + time.Hour

Jump to

Keyboard shortcuts

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