basicpg

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: 10 Imported by: 0

Documentation

Overview

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

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(roleQueries []RoleQuery, queue *workerpoolpg.Queue,
	loader func(ctx context.Context, tx *pg.Transaction, acc *structs.Account) proto.Message,
	authTimeout time.Duration) *AuthorizationMaker

NewMaker - создание AuthorizationMaker. roleQueries используется для перебора по логин/паролю, queue - очередь для контроля потока запросов, loader - функция получения полного авторизационного ответа по аккаунту, authTimeout - таймаут одной операции авторизации

func (*AuthorizationMaker) Auth

func (m *AuthorizationMaker) Auth(ctx context.Context, login, password string, platform structs.Platform,
	versions []string, disabled ...structs.Role) (*structs.Account, error)

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

Example
package main

import (
	"context"
	"fmt"
	"github.com/custom-app/sdk-go/auth/basic"
	"github.com/custom-app/sdk-go/auth/basic/basicpg"
	"github.com/custom-app/sdk-go/service/workerpool/workerpoolpg"
	"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 := basicpg.NewMaker([]basicpg.RoleQuery{
		{
			Query: "select id from table_name where login=$1 and password=$2",
			Role:  1,
		},
		{
			Query: "select id from table_name2 where login=$1 and password=$2",
			Role:  2,
		},
	},
		authQueue, // очередь
		nil,       // в этом примере опущу для простоты
		time.Second)
	basic.SetDefaultAuth(provider)

	// предположим в таблице table_name2 есть запись id: 1, login: test, password: 954d5a49fd70d9b8bcdb35d252267829957f7ef7fa6c74f88419bdc5e82209f4
	res, err := basic.Auth(context.Background(), "test",
		"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", 0, []string{"0.0.1"})
	if err != nil {
		log.Panicln(err)
	}
	fmt.Println(res.Id, res.Role, res.Platform, res.Versions)
}
Output:

1 2 0 {0.0.1}

func (*AuthorizationMaker) AuthWithInfo

func (m *AuthorizationMaker) AuthWithInfo(ctx context.Context, login, password string, platform structs.Platform,
	versions []string, disabled ...structs.Role) (*structs.Account, proto.Message, error)

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

Example
package main

import (
	"context"
	"fmt"
	"github.com/custom-app/sdk-go/auth/basic"
	"github.com/custom-app/sdk-go/auth/basic/basicpg"
	"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 := basicpg.NewMaker([]basicpg.RoleQuery{
		{
			Query: "select id from table_name where login=$1 and password=$2",
			Role:  1,
		},
		{
			Query: "select id from table_name2 where login=$1 and password=$2",
			Role:  2,
		},
	},
		authQueue, // очередь
		func(ctx context.Context, tx *pg.Transaction, acc *structs.Account) proto.Message {
			// код, вытягивающий данные аккаунта в Response
			return nil
		}, // в этом примере опущу для простоты
		time.Second)
	basic.SetDefaultAuth(provider)

	// предположим в таблице table_name2 есть запись id: 1, login: test, password: 954d5a49fd70d9b8bcdb35d252267829957f7ef7fa6c74f88419bdc5e82209f4
	res, resp, err := basic.AuthWithInfo(context.Background(), "test",
		"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", 0, []string{"0.0.1"})
	if err != nil {
		log.Panicln(err)
	}
	fmt.Println(res.Id, res.Role, res.Platform, res.Versions)
	
Output:

...

func (*AuthorizationMaker) AuthWithTx

func (m *AuthorizationMaker) AuthWithTx(ctx context.Context, tx *pg.Transaction, login, password string,
	platform structs.Platform, versions []string, disabled ...structs.Role) (*structs.Account, error)

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

func (*AuthorizationMaker) Logout

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

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

type RoleQuery

type RoleQuery struct {
	Query string       // команда
	Role  structs.Role // роль для команды
}

RoleQuery - sql-команда для получения из бд айди аккаунта по логину и паролю

Jump to

Keyboard shortcuts

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