18 Commits

Author SHA1 Message Date
75d8250f72 cleanup code 2025-02-01 06:55:20 -06:00
f853b22b43 cleanup code 2025-02-01 06:54:40 -06:00
f421249943 remove user permission 2025-02-01 06:35:50 -06:00
6289faf1ba remove new customer endpoint 2025-02-01 06:33:43 -06:00
d58c69cb08 implement user_permission 2025-02-01 03:04:52 -06:00
72414bc8fb implement user_permission 2025-01-31 10:27:06 -06:00
9ee27f14cf implement and test forget and reset nkode 2025-01-31 10:26:30 -06:00
6dd84e4ca3 split sign and reset 2025-01-30 11:33:16 -06:00
597532bf26 implement gin nkode api 2025-01-27 02:54:35 -06:00
44bede14e4 refactor sqlite repository 2025-01-25 14:39:02 -06:00
0a1b8f9457 refactor var names 2025-01-25 14:30:06 -06:00
7f6c828ea5 don't use session 2025-01-23 14:54:05 -06:00
665341961d add delete session 2025-01-23 14:43:59 -06:00
d23671ff2b add delete session 2025-01-23 14:43:51 -06:00
c1ed5dafe3 add user login sessions 2025-01-23 14:42:34 -06:00
2eb72988e5 printf to log 2025-01-23 14:23:28 -06:00
536894c7dd fix make table order 2025-01-23 06:41:40 -06:00
3c0b3c04b7 implement cli 2025-01-23 06:33:29 -06:00
26 changed files with 1267 additions and 354 deletions

1
.gitignore vendored
View File

@@ -2,3 +2,4 @@
icons/
json_icon/
flaticon_colored_svgs/
nkode

View File

@@ -5,6 +5,7 @@ import (
"git.infra.nkode.tech/dkelly/nkode-core/config"
"git.infra.nkode.tech/dkelly/nkode-core/email"
"git.infra.nkode.tech/dkelly/nkode-core/entities"
"git.infra.nkode.tech/dkelly/nkode-core/memCache"
"git.infra.nkode.tech/dkelly/nkode-core/repository"
"git.infra.nkode.tech/dkelly/nkode-core/security"
"github.com/google/uuid"
@@ -20,28 +21,27 @@ const (
)
type NKodeAPI struct {
Db repository.CustomerUserRepository
SignupSessionCache *cache.Cache
EmailQueue *email.Queue
repo repository.CustomerUserRepository
signupSessionCache *cache.Cache
emailQueue *email.Queue
forgotNkodeCache memCache.ForgotNKodeCache
}
func NewNKodeAPI(db repository.CustomerUserRepository, queue *email.Queue) NKodeAPI {
func NewNKodeAPI(repo repository.CustomerUserRepository, queue *email.Queue) NKodeAPI {
return NKodeAPI{
Db: db,
EmailQueue: queue,
SignupSessionCache: cache.New(sessionExpiration, sessionCleanupInterval),
repo: repo,
emailQueue: queue,
signupSessionCache: cache.New(sessionExpiration, sessionCleanupInterval),
forgotNkodeCache: memCache.NewForgotNKodeCache(),
}
}
func (n *NKodeAPI) CreateNewCustomer(nkodePolicy entities.NKodePolicy, id *entities.CustomerId) (*entities.CustomerId, error) {
func (n *NKodeAPI) CreateNewCustomer(nkodePolicy entities.NKodePolicy) (*entities.CustomerId, error) {
newCustomer, err := entities.NewCustomer(nkodePolicy)
if id != nil {
newCustomer.Id = *id
}
if err != nil {
return nil, err
}
err = n.Db.CreateCustomer(*newCustomer)
err = n.repo.CreateCustomer(*newCustomer)
if err != nil {
return nil, err
@@ -49,8 +49,20 @@ func (n *NKodeAPI) CreateNewCustomer(nkodePolicy entities.NKodePolicy, id *entit
return &newCustomer.Id, nil
}
func (n *NKodeAPI) CreateCustomerWithID(id entities.CustomerId, nkodePolicy entities.NKodePolicy) error {
newCustomer, err := entities.NewCustomer(nkodePolicy)
if err != nil {
return err
}
newCustomer.Id = id
if err = n.repo.CreateCustomer(*newCustomer); err != nil {
return err
}
return nil
}
func (n *NKodeAPI) GenerateSignupResetInterface(userEmail entities.UserEmail, customerId entities.CustomerId, kp entities.KeypadDimension, reset bool) (*entities.SignupResetInterface, error) {
user, err := n.Db.GetUser(userEmail, customerId)
user, err := n.repo.GetUser(userEmail, customerId)
if err != nil {
return nil, err
}
@@ -58,7 +70,7 @@ func (n *NKodeAPI) GenerateSignupResetInterface(userEmail entities.UserEmail, cu
log.Printf("user %s already exists", string(userEmail))
return nil, config.ErrUserAlreadyExists
}
svgIdxInterface, err := n.Db.RandomSvgIdxInterface(kp)
svgIdxInterface, err := n.repo.RandomSvgIdxInterface(kp)
if err != nil {
return nil, err
}
@@ -66,11 +78,10 @@ func (n *NKodeAPI) GenerateSignupResetInterface(userEmail entities.UserEmail, cu
if err != nil {
return nil, err
}
if err := n.SignupSessionCache.Add(signupSession.Id.String(), *signupSession, sessionExpiration); err != nil {
if err := n.signupSessionCache.Add(signupSession.Id.String(), *signupSession, sessionExpiration); err != nil {
return nil, err
}
svgInterface, err := n.Db.GetSvgStringInterface(signupSession.LoginUserInterface.SvgId)
svgInterface, err := n.repo.GetSvgStringInterface(signupSession.LoginUserInterface.SvgId)
if err != nil {
return nil, err
}
@@ -84,12 +95,12 @@ func (n *NKodeAPI) GenerateSignupResetInterface(userEmail entities.UserEmail, cu
}
func (n *NKodeAPI) SetNKode(customerId entities.CustomerId, sessionId entities.SessionId, keySelection entities.KeySelection) (entities.IdxInterface, error) {
_, err := n.Db.GetCustomer(customerId)
_, err := n.repo.GetCustomer(customerId)
if err != nil {
return nil, err
}
session, exists := n.SignupSessionCache.Get(sessionId.String())
session, exists := n.signupSessionCache.Get(sessionId.String())
if !exists {
log.Printf("session id does not exist %s", sessionId)
return nil, config.ErrSignupSessionDNE
@@ -103,12 +114,12 @@ func (n *NKodeAPI) SetNKode(customerId entities.CustomerId, sessionId entities.S
if err != nil {
return nil, err
}
n.SignupSessionCache.Set(sessionId.String(), userSession, sessionExpiration)
n.signupSessionCache.Set(sessionId.String(), userSession, sessionExpiration)
return confirmInterface, nil
}
func (n *NKodeAPI) ConfirmNKode(customerId entities.CustomerId, sessionId entities.SessionId, keySelection entities.KeySelection) error {
session, exists := n.SignupSessionCache.Get(sessionId.String())
session, exists := n.signupSessionCache.Get(sessionId.String())
if !exists {
log.Printf("session id does not exist %s", sessionId)
return config.ErrSignupSessionDNE
@@ -118,7 +129,7 @@ func (n *NKodeAPI) ConfirmNKode(customerId entities.CustomerId, sessionId entiti
// handle the case where the type assertion fails
return config.ErrSignupSessionDNE
}
customer, err := n.Db.GetCustomer(customerId)
customer, err := n.repo.GetCustomer(customerId)
if err != nil {
return err
}
@@ -134,16 +145,16 @@ func (n *NKodeAPI) ConfirmNKode(customerId entities.CustomerId, sessionId entiti
return err
}
if userSession.Reset {
err = n.Db.UpdateUserNKode(*user)
err = n.repo.UpdateUserNKode(*user)
} else {
err = n.Db.WriteNewUser(*user)
err = n.repo.WriteNewUser(*user)
}
n.SignupSessionCache.Delete(userSession.Id.String())
n.signupSessionCache.Delete(userSession.Id.String())
return err
}
func (n *NKodeAPI) GetLoginInterface(userEmail entities.UserEmail, customerId entities.CustomerId) (*entities.LoginInterface, error) {
user, err := n.Db.GetUser(userEmail, customerId)
user, err := n.repo.GetUser(userEmail, customerId)
if err != nil {
return nil, err
}
@@ -151,7 +162,7 @@ func (n *NKodeAPI) GetLoginInterface(userEmail entities.UserEmail, customerId en
log.Printf("user %s for customer %s dne", userEmail, customerId)
return nil, config.ErrUserForCustomerDNE
}
svgInterface, err := n.Db.GetSvgStringInterface(user.Interface.SvgId)
svgInterface, err := n.repo.GetSvgStringInterface(user.Interface.SvgId)
if err != nil {
return nil, err
}
@@ -166,11 +177,11 @@ func (n *NKodeAPI) GetLoginInterface(userEmail entities.UserEmail, customerId en
}
func (n *NKodeAPI) Login(customerId entities.CustomerId, userEmail entities.UserEmail, keySelection entities.KeySelection) (*security.AuthenticationTokens, error) {
customer, err := n.Db.GetCustomer(customerId)
customer, err := n.repo.GetCustomer(customerId)
if err != nil {
return nil, err
}
user, err := n.Db.GetUser(userEmail, customerId)
user, err := n.repo.GetUser(userEmail, customerId)
if err != nil {
return nil, err
}
@@ -184,37 +195,38 @@ func (n *NKodeAPI) Login(customerId entities.CustomerId, userEmail entities.User
}
if user.Renew {
err = n.Db.RefreshUserPasscode(*user, passcode, customer.Attributes)
err = n.repo.RefreshUserPasscode(*user, passcode, customer.Attributes)
if err != nil {
return nil, err
}
}
jwtToken, err := security.NewAuthenticationTokens(string(user.Email), uuid.UUID(customerId))
if err != nil {
return nil, err
}
if err = n.Db.UpdateUserRefreshToken(user.Id, jwtToken.RefreshToken); err != nil {
if err = n.repo.UpdateUserRefreshToken(user.Id, jwtToken.RefreshToken); err != nil {
return nil, err
}
if err = user.Interface.LoginShuffle(); err != nil {
return nil, err
}
if err = n.Db.UpdateUserInterface(user.Id, user.Interface); err != nil {
if err = n.repo.UpdateUserInterface(user.Id, user.Interface); err != nil {
return nil, err
}
return &jwtToken, nil
}
func (n *NKodeAPI) RenewAttributes(customerId entities.CustomerId) error {
return n.Db.Renew(customerId)
return n.repo.Renew(customerId)
}
func (n *NKodeAPI) RandomSvgInterface() ([]string, error) {
return n.Db.RandomSvgInterface(entities.KeypadMax)
return n.repo.RandomSvgInterface(entities.KeypadMax)
}
func (n *NKodeAPI) RefreshToken(userEmail entities.UserEmail, customerId entities.CustomerId, refreshToken string) (string, error) {
user, err := n.Db.GetUser(userEmail, customerId)
user, err := n.repo.GetUser(userEmail, customerId)
if err != nil {
return "", err
}
@@ -236,8 +248,8 @@ func (n *NKodeAPI) RefreshToken(userEmail entities.UserEmail, customerId entitie
return security.EncodeAndSignClaims(newAccessClaims)
}
func (n *NKodeAPI) ResetNKode(userEmail entities.UserEmail, customerId entities.CustomerId) error {
user, err := n.Db.GetUser(userEmail, customerId)
func (n *NKodeAPI) ForgotNKode(userEmail entities.UserEmail, customerId entities.CustomerId) error {
user, err := n.repo.GetUser(userEmail, customerId)
if err != nil {
return fmt.Errorf("error getting user in rest nkode %v", err)
}
@@ -246,7 +258,7 @@ func (n *NKodeAPI) ResetNKode(userEmail entities.UserEmail, customerId entities.
return nil
}
nkodeResetJwt, err := security.ResetNKodeToken(string(userEmail), uuid.UUID(customerId))
nkodeResetJwt, err := security.ResetNKodeToken(string(userEmail), uuid.UUID(customerId).String())
if err != nil {
return err
}
@@ -261,6 +273,22 @@ func (n *NKodeAPI) ResetNKode(userEmail entities.UserEmail, customerId entities.
Subject: "nKode Reset",
Content: htmlBody,
}
n.EmailQueue.AddEmail(email)
n.emailQueue.AddEmail(email)
n.forgotNkodeCache.Set(userEmail, customerId)
return nil
}
func (n *NKodeAPI) Signout(userEmail entities.UserEmail, customerId entities.CustomerId) error {
user, err := n.repo.GetUser(userEmail, customerId)
if err != nil {
return err
}
if user == nil {
log.Printf("user %s for customer %s dne", userEmail, customerId)
return config.ErrUserForCustomerDNE
}
if err = n.repo.UpdateUserRefreshToken(user.Id, ""); err != nil {
return err
}
return nil
}

View File

@@ -6,7 +6,6 @@ import (
"git.infra.nkode.tech/dkelly/nkode-core/entities"
"git.infra.nkode.tech/dkelly/nkode-core/repository"
"git.infra.nkode.tech/dkelly/nkode-core/security"
"git.infra.nkode.tech/dkelly/nkode-core/sqlc"
"github.com/stretchr/testify/assert"
"log"
"os"
@@ -19,26 +18,18 @@ func TestNKodeAPI(t *testing.T) {
dbPath := os.Getenv("TEST_DB")
ctx := context.Background()
sqliteDb, err := sqlc.OpenSqliteDb(dbPath)
assert.NoError(t, err)
queue, err := sqlc.NewQueue(sqliteDb, ctx)
assert.NoError(t, err)
queue.Start()
defer func(queue *sqlc.Queue) {
if err := queue.Stop(); err != nil {
sqlitedb, err := repository.NewSqliteRepository(ctx, dbPath)
if err != nil {
log.Fatal(err)
}
sqlitedb.Start()
defer func(sqldb *repository.SqliteRepository) {
if err := sqldb.Stop(); err != nil {
log.Fatal(err)
}
}(queue)
sqlitedb := repository.NewSqliteRepository(queue, ctx)
testNKodeAPI(t, &sqlitedb)
}(sqlitedb)
testNKodeAPI(t, sqlitedb)
//if _, err := os.Stat(dbPath); err == nil {
// err = os.Remove(dbPath)
// assert.NoError(t, err)
//} else {
// assert.NoError(t, err)
//}
}
func testNKodeAPI(t *testing.T, db repository.CustomerUserRepository) {
@@ -51,12 +42,12 @@ func testNKodeAPI(t *testing.T, db repository.CustomerUserRepository) {
attrsPerKey := 5
numbOfKeys := 4
for idx := 0; idx < 1; idx++ {
userEmail := entities.UserEmail("test_username" + security.GenerateRandomString(12) + "@example.com")
userEmail := entities.UserEmail("test_username" + security.GenerateNonSecureRandomString(12) + "@example.com")
passcodeLen := 4
nkodePolicy := entities.NewDefaultNKodePolicy()
keypadSize := entities.KeypadDimension{AttrsPerKey: attrsPerKey, NumbOfKeys: numbOfKeys}
nkodeApi := NewNKodeAPI(db, queue)
customerId, err := nkodeApi.CreateNewCustomer(nkodePolicy, nil)
customerId, err := nkodeApi.CreateNewCustomer(nkodePolicy)
assert.NoError(t, err)
signupResponse, err := nkodeApi.GenerateSignupResetInterface(userEmail, *customerId, keypadSize, false)
assert.NoError(t, err)

View File

@@ -1,258 +1,86 @@
package main
import (
"context"
"database/sql"
"encoding/json"
_ "embed"
"flag"
"fmt"
_ "github.com/mattn/go-sqlite3" // Import the SQLite3 driver
"io/ioutil"
"git.infra.nkode.tech/dkelly/nkode-core/repository"
"git.infra.nkode.tech/dkelly/nkode-core/sqlite"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
"path/filepath"
"strings"
)
type Icon struct {
Body string `json:"body"`
Width *int `json:"width,omitempty"`
}
// Root Define the Root struct to represent the entire JSON structure
type Root struct {
Prefix string `json:"prefix"`
Icons map[string]Icon `json:"icons"`
Height int `json:"height"`
}
func main() {
testDbPath := os.Getenv("TEST_DB_PATH")
dbPath := os.Getenv("DB_PATH")
dbPaths := []string{testDbPath, dbPath}
flaticonSvgDir := os.Getenv("SVG_DIR")
//dbPath := "/Users/donov/Desktop/nkode.db"
//dbPaths := []string{dbPath}
//outputStr := MakeSvgFiles()
for _, path := range dbPaths {
MakeTables(path)
FlaticonToSqlite(path, flaticonSvgDir)
//SvgToSqlite(path, outputStr)
}
}
func FlaticonToSqlite(dbPath string, svgDir string) {
db, err := sql.Open("sqlite3", dbPath)
sqliteSchema, err := sqlite.FS.ReadFile("schema.sql")
if err != nil {
log.Fatal(err)
}
defer db.Close()
commandLine := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
dbPath := commandLine.String("db-path", "", "Path to the database")
svgPath := commandLine.String("svg-path", "", "Path to the SVG directory")
if err = commandLine.Parse(os.Args[1:]); err != nil {
log.Fatalf("Failed to parse flags: %v", err)
}
if err = MakeTables(*dbPath, string(sqliteSchema)); err != nil {
log.Fatal(err)
}
ctx := context.Background()
sqliteRepo, err := repository.NewSqliteRepository(ctx, *dbPath)
sqliteRepo.Start()
defer func(sqliteRepo *repository.SqliteRepository) {
if err := sqliteRepo.Stop(); err != nil {
log.Fatal(err)
}
}(sqliteRepo)
// Open the directory
FlaticonToSqlite(sqliteRepo, *svgPath)
log.Println(fmt.Sprintf("Successfully added all SVGs in %s to the database at %s\n", *svgPath, *dbPath))
}
func FlaticonToSqlite(repo *repository.SqliteRepository, svgDir string) {
files, err := os.ReadDir(svgDir)
if err != nil {
log.Fatal(err)
}
for _, file := range files {
// Check if it is a regular file (not a directory) and has a .svg extension
if file.IsDir() || filepath.Ext(file.Name()) != ".svg" {
continue
}
filePath := filepath.Join(svgDir, file.Name())
// Read the file contents
content, err := os.ReadFile(filePath)
if err != nil {
log.Println("Error reading file:", filePath, err)
continue
}
// Print the file name and first few bytes of the file content
insertSql := `
INSERT INTO svg_icon (svg)
VALUES (?)
`
_, err = db.Exec(insertSql, string(content))
if err != nil {
if err = repo.AddSvg(string(content)); err != nil {
log.Fatal(err)
}
}
}
func SvgToSqlite(dbPath string, outputStr string) {
func MakeTables(dbPath string, schema string) error {
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
if err = os.MkdirAll(filepath.Dir(dbPath), 0755); err != nil {
return err
}
if _, err = os.Create(dbPath); err != nil {
return err
}
}
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
log.Fatal(err)
return err
}
defer db.Close()
lines := strings.Split(outputStr, "\n")
insertSql := `
INSERT INTO svg_icon (svg)
VALUES (?)
`
for _, line := range lines {
if line == "" {
continue
}
_, err := db.Exec(insertSql, line)
if err != nil {
log.Fatal(err)
}
}
}
func MakeSvgFiles() string {
jsonFiles, err := GetAllFiles("./core/sqlite-init/json")
if err != nil {
log.Fatalf("Error getting JSON files: %v", err)
}
if len(jsonFiles) == 0 {
log.Fatal("No JSON files found in ./json folder")
}
var outputStr string
strSet := make(map[string]struct{})
for _, filename := range jsonFiles {
fileData, err := LoadJson(filename)
if err != nil {
log.Print("Error loading JSON file: ", err)
continue
}
height := fileData.Height
for name, icon := range fileData.Icons {
width := height
parts := strings.Split(name, "-")
if len(parts) <= 0 {
log.Print(name, " has no parts")
continue
}
part0 := parts[0]
_, exists := strSet[part0]
if exists {
continue
}
if icon.Width != nil {
width = *icon.Width
}
strSet[part0] = struct{}{}
if icon.Body == "" {
continue
}
outputStr = fmt.Sprintf("%s<svg viewBox=\"0 0 %d %d\" xmlns=\"http://www.w3.org/2000/svg\">%s</svg>\n", outputStr, width, height, icon.Body)
}
}
return outputStr
}
func GetAllFiles(dir string) ([]string, error) {
// Use ioutil.ReadDir to list all files in the directory
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("unable to read directory: %v", err)
}
// Create a slice to hold the JSON filenames
var jsonFiles []string
// Loop through the files and filter out JSON files
for _, file := range files {
if !file.IsDir() && filepath.Ext(file.Name()) == ".json" {
jsonFiles = append(jsonFiles, filepath.Join(dir, file.Name()))
}
}
return jsonFiles, nil
}
func LoadJson(filename string) (*Root, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read file %s: %v", filename, err)
}
var root Root
err = json.Unmarshal(data, &root)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal JSON: %v", err)
}
return &root, nil
}
func MakeTables(dbPath string) {
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
log.Fatal(err)
}
defer db.Close()
createTable := `
PRAGMA journal_mode=WAL;
--PRAGMA busy_timeout = 5000; -- Wait up to 5 seconds
--PRAGMA synchronous = NORMAL; -- Reduce sync frequency for less locking
--PRAGMA cache_size = -16000; -- Increase cache size (16MB)PRAGMA
CREATE TABLE IF NOT EXISTS customer (
id TEXT NOT NULL PRIMARY KEY
,max_nkode_len INTEGER NOT NULL
,min_nkode_len INTEGER NOT NULL
,distinct_sets INTEGER NOT NULL
,distinct_attributes INTEGER NOT NULL
,lock_out INTEGER NOT NULL
,expiration INTEGER NOT NULL
,attribute_values BLOB NOT NULL
,set_values BLOB NOT NULL
,last_renew TEXT NOT NULL
,created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS user (
id TEXT NOT NULL PRIMARY KEY
,email TEXT NOT NULL
-- first_name TEXT NOT NULL
-- last_name TEXT NOT NULL
,renew INT NOT NULL
,refresh_token TEXT
,customer_id TEXT NOT NULL
-- Enciphered Passcode
,code TEXT NOT NULL
,mask TEXT NOT NULL
-- Keypad Dimensions
,attributes_per_key INT NOT NULL
,number_of_keys INT NOT NULL
-- User Keys
,alpha_key BLOB NOT NULL
,set_key BLOB NOT NULL
,pass_key BLOB NOT NULL
,mask_key BLOB NOT NULL
,salt BLOB NOT NULL
,max_nkode_len INT NOT NULL
-- User Interface
,idx_interface BLOB NOT NULL
,svg_id_interface BLOB NOT NULL
,last_login TEXT NULL
,created_at TEXT
,FOREIGN KEY (customer_id) REFERENCES customer(id)
,UNIQUE(customer_id, email)
);
CREATE TABLE IF NOT EXISTS svg_icon (
id INTEGER PRIMARY KEY AUTOINCREMENT
,svg TEXT NOT NULL
);
`
_, err = db.Exec(createTable)
if err != nil {
log.Fatal(err)
if _, err = db.Exec(schema); err != nil {
return err
}
return db.Close()
}

View File

@@ -14,6 +14,13 @@ import (
"time"
)
const (
EmailRetryExpiration = 5 * time.Minute
SesCleanupInterval = 10 * time.Minute
EmailQueueBufferSize = 100
MaxEmailsPerSecond = 13
)
type Client interface {
SendEmail(Email) error
}
@@ -36,14 +43,9 @@ type SESClient struct {
ResetCache *cache.Cache
}
const (
emailRetryExpiration = 5 * time.Minute
sesCleanupInterval = 10 * time.Minute
)
func NewSESClient() SESClient {
return SESClient{
ResetCache: cache.New(emailRetryExpiration, sesCleanupInterval),
ResetCache: cache.New(EmailRetryExpiration, SesCleanupInterval),
}
}
@@ -79,7 +81,7 @@ func (s *SESClient) SendEmail(email Email) error {
Source: aws.String(email.Sender),
}
if err = s.ResetCache.Add(email.Recipient, nil, emailRetryExpiration); err != nil {
if err = s.ResetCache.Add(email.Recipient, nil, EmailRetryExpiration); err != nil {
return err
}

View File

@@ -11,14 +11,19 @@ type KeySelection []int
type CustomerId uuid.UUID
func CustomerIdToString(customerId CustomerId) string {
customerUuid := uuid.UUID(customerId)
return customerUuid.String()
func (c *CustomerId) String() string {
id := uuid.UUID(*c)
return id.String()
}
type SessionId uuid.UUID
type UserId uuid.UUID
func (u *UserId) String() string {
id := uuid.UUID(*u)
return id.String()
}
func UserIdFromString(userId string) UserId {
id, err := uuid.Parse(userId)
if err != nil {
@@ -99,3 +104,14 @@ type LoginInterface struct {
NumbOfKeys int `json:"numb_of_keys"`
Colors []RGBColor `json:"colors"`
}
type UserPermission int
const (
Default UserPermission = iota
Admin
)
func (p UserPermission) String() string {
return [...]string{"Default", "Admin"}[p]
}

View File

@@ -3,12 +3,12 @@ package entities
import "git.infra.nkode.tech/dkelly/nkode-core/config"
type NKodePolicy struct {
MaxNkodeLen int `json:"max_nkode_len"`
MinNkodeLen int `json:"min_nkode_len"`
DistinctSets int `json:"distinct_sets"`
DistinctAttributes int `json:"distinct_attributes"`
LockOut int `json:"lock_out"`
Expiration int `json:"expiration"` // seconds, -1 no expiration
MaxNkodeLen int `form:"max_nkode_len"`
MinNkodeLen int `form:"min_nkode_len"`
DistinctSets int `form:"distinct_sets"`
DistinctAttributes int `form:"distinct_attributes"`
LockOut int `form:"lock_out"`
Expiration int `form:"expiration"` // seconds, -1 no expiration
}
func NewDefaultNKodePolicy() NKodePolicy {

View File

@@ -123,11 +123,4 @@ func TestUserInterface_PartialInterfaceShuffle(t *testing.T) {
return n == true
})
assert.False(t, allTrue)
allFalse := all.All[bool](shuffleCompare, func(n bool) bool {
return n == false
})
assert.False(t, allFalse)
}

25
go.mod
View File

@@ -27,8 +27,33 @@ require (
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.10 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.33.9 // indirect
github.com/aws/smithy-go v1.22.1 // indirect
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.10.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.29.0 // indirect
golang.org/x/text v0.21.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

70
go.sum
View File

@@ -28,31 +28,101 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.33.9 h1:BRVDbewN6VZcwr+FBOszDKvYeXY1
github.com/aws/aws-sdk-go-v2/service/sts v1.33.9/go.mod h1:f6vjfZER1M17Fokn0IzssOTMT2N8ZSq+7jnNF0tArvw=
github.com/aws/smithy-go v1.22.1 h1:/HPHZQ0g7f4eUeK6HKglFz8uwVfZKgoI25rb/J+dnro=
github.com/aws/smithy-go v1.22.1/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg=
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM=
github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

401
handler/handler.go Normal file
View File

@@ -0,0 +1,401 @@
package handler
import (
"errors"
"git.infra.nkode.tech/dkelly/nkode-core/api"
"git.infra.nkode.tech/dkelly/nkode-core/config"
"git.infra.nkode.tech/dkelly/nkode-core/entities"
"git.infra.nkode.tech/dkelly/nkode-core/models"
"git.infra.nkode.tech/dkelly/nkode-core/security"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"log"
"strings"
)
type NkodeHandler struct {
API api.NKodeAPI
Logger *log.Logger
}
const (
malformedCustomerId = "malformed customer id"
malformedUserEmail = "malformed user email"
malformedSessionId = "malformed session id"
invalidKeypadDimensions = "invalid keypad dimensions"
)
func (h *NkodeHandler) RegisterRoutes(r *gin.Engine) {
r.Group("/v1/nkode")
{
// r.POST("/create-new-customer", h.CreateNewCustomerHandler)
r.POST("/signup", h.SignupHandler)
r.POST("/set-nkode", h.SetNKodeHandler)
r.POST("/confirm-nkode", h.ConfirmNKodeHandler)
r.POST("/get-login-interface", h.GetLoginInterfaceHandler)
r.POST("/login", h.LoginHandler)
r.POST("/renew-attributes", h.RenewAttributesHandler)
r.POST("/random-svg-interface", h.RandomSvgInterfaceHandler)
r.POST("/refresh-token", h.RefreshTokenHandler)
r.POST("/forgot-nkode", h.ForgotNKodeHandler)
r.POST("/signout", h.SignoutHandler)
r.POST("/reset-nkode", h.ResetHandler)
}
}
func (h *NkodeHandler) CreateNewCustomerHandler(c *gin.Context) {
h.Logger.Println("create new customer")
var newCustomerPost entities.NKodePolicy
if err := c.ShouldBind(&newCustomerPost); err != nil {
handleError(c, err)
return
}
customerId, err := h.API.CreateNewCustomer(newCustomerPost)
if err != nil {
c.String(500, "Internal Server Error")
return
}
h.Logger.Println("create new customer")
c.JSON(200, gin.H{"customer_id": customerId.String()})
}
func (h *NkodeHandler) SignupHandler(c *gin.Context) {
h.Logger.Println("generate signup reset interface")
var postBody models.SignupPostBody
if err := c.ShouldBind(&postBody); err != nil {
handleError(c, err)
return
}
kp := entities.KeypadDimension{
AttrsPerKey: postBody.AttrsPerKey,
NumbOfKeys: postBody.NumbOfKeys,
}
if err := kp.IsValidKeypadDimension(); err != nil {
c.String(400, invalidKeypadDimensions)
return
}
customerId, err := uuid.Parse(postBody.CustomerId)
if err != nil {
c.String(400, malformedCustomerId)
return
}
userEmail, err := entities.ParseEmail(postBody.UserEmail)
if err != nil {
c.String(400, malformedUserEmail)
return
}
resp, err := h.API.GenerateSignupResetInterface(userEmail, entities.CustomerId(customerId), kp, false)
if err != nil {
handleError(c, err)
return
}
c.JSON(200, resp)
}
func (h *NkodeHandler) SetNKodeHandler(c *gin.Context) {
h.Logger.Println("set nkode")
var postBody models.SetNKodePost
if err := c.ShouldBindJSON(&postBody); err != nil {
handleError(c, err)
return
}
customerId, err := uuid.Parse(postBody.CustomerId)
if err != nil {
c.String(400, malformedCustomerId)
return
}
sessionId, err := uuid.Parse(postBody.SessionId)
if err != nil {
c.String(400, malformedSessionId)
return
}
confirmInterface, err := h.API.SetNKode(entities.CustomerId(customerId), entities.SessionId(sessionId), postBody.KeySelection)
if err != nil {
handleError(c, err)
return
}
resp := models.SetNKodeResp{UserInterface: confirmInterface}
c.JSON(200, resp)
}
func (h *NkodeHandler) ConfirmNKodeHandler(c *gin.Context) {
h.Logger.Println("confirm nkode")
var postBody models.ConfirmNKodePost
if err := c.ShouldBindJSON(&postBody); err != nil {
handleError(c, err)
return
}
customerId, err := uuid.Parse(postBody.CustomerId)
if err != nil {
c.String(400, malformedCustomerId)
return
}
sessionId, err := uuid.Parse(postBody.SessionId)
if err != nil {
c.String(400, malformedSessionId)
return
}
if err := h.API.ConfirmNKode(entities.CustomerId(customerId), entities.SessionId(sessionId), postBody.KeySelection); err != nil {
handleError(c, err)
return
}
c.Status(200)
}
func (h *NkodeHandler) GetLoginInterfaceHandler(c *gin.Context) {
h.Logger.Println("get login interface")
var loginInterfacePost models.LoginInterfacePost
if err := c.ShouldBind(&loginInterfacePost); err != nil {
handleError(c, err)
return
}
customerId, err := uuid.Parse(loginInterfacePost.CustomerId)
if err != nil {
c.String(400, malformedCustomerId)
return
}
userEmail, err := entities.ParseEmail(loginInterfacePost.UserEmail)
if err != nil {
c.String(400, malformedUserEmail)
return
}
postBody, err := h.API.GetLoginInterface(userEmail, entities.CustomerId(customerId))
if err != nil {
handleError(c, err)
return
}
c.JSON(200, postBody)
}
func (h *NkodeHandler) LoginHandler(c *gin.Context) {
h.Logger.Println("login")
var loginPost models.LoginPost
if err := c.ShouldBindJSON(&loginPost); err != nil {
handleError(c, err)
return
}
customerId, err := uuid.Parse(loginPost.CustomerId)
if err != nil {
c.String(400, malformedCustomerId)
return
}
userEmail, err := entities.ParseEmail(loginPost.UserEmail)
if err != nil {
c.String(400, malformedUserEmail)
return
}
jwtToken, err := h.API.Login(entities.CustomerId(customerId), userEmail, loginPost.KeySelection)
if err != nil {
handleError(c, err)
return
}
c.JSON(200, jwtToken)
}
func (h *NkodeHandler) RenewAttributesHandler(c *gin.Context) {
h.Logger.Println("renew attributes")
var renewAttributesPost models.RenewAttributesPost
if err := c.ShouldBind(&renewAttributesPost); err != nil {
handleError(c, err)
return
}
customerId, err := uuid.Parse(renewAttributesPost.CustomerId)
if err != nil {
c.String(400, malformedCustomerId)
return
}
if err = h.API.RenewAttributes(entities.CustomerId(customerId)); err != nil {
handleError(c, err)
return
}
c.Status(200)
}
func (h *NkodeHandler) RandomSvgInterfaceHandler(c *gin.Context) {
h.Logger.Println("random svg interface")
svgs, err := h.API.RandomSvgInterface()
if err != nil {
handleError(c, err)
return
}
resp := models.RandomSvgInterfaceResp{Svgs: svgs}
c.JSON(200, resp)
}
func (h *NkodeHandler) RefreshTokenHandler(c *gin.Context) {
h.Logger.Println("refresh token")
refreshToken, err := getBearerToken(c)
if err != nil {
c.String(403, "forbidden")
return
}
refreshClaims, err := security.ParseRegisteredClaimToken(refreshToken)
if err != nil {
c.String(500, "Internal Error")
return
}
customerId, err := uuid.Parse(refreshClaims.Issuer)
if err != nil {
c.String(400, malformedCustomerId)
return
}
userEmail, err := entities.ParseEmail(refreshClaims.Subject)
if err != nil {
c.String(400, malformedUserEmail)
return
}
accessToken, err := h.API.RefreshToken(userEmail, entities.CustomerId(customerId), refreshToken)
if err != nil {
handleError(c, err)
return
}
c.JSON(200, gin.H{"access_token": accessToken})
}
func (h *NkodeHandler) ForgotNKodeHandler(c *gin.Context) {
h.Logger.Println("forgot nkode")
var forgotNKodePost models.ForgotNKodePost
if err := c.ShouldBind(&forgotNKodePost); err != nil {
handleError(c, err)
return
}
customerId, err := uuid.Parse(forgotNKodePost.CustomerId)
if err != nil {
c.String(400, malformedCustomerId)
return
}
userEmail, err := entities.ParseEmail(forgotNKodePost.UserEmail)
if err != nil {
c.String(400, malformedUserEmail)
return
}
if err := h.API.ForgotNKode(userEmail, entities.CustomerId(customerId)); err != nil {
handleError(c, err)
return
}
c.Status(200)
}
func (h *NkodeHandler) SignoutHandler(c *gin.Context) {
h.Logger.Println("signout")
token, err := getBearerToken(c)
if err != nil {
c.String(403, "forbidden")
return
}
accessClaims, err := security.ParseRegisteredClaimToken(token)
if err != nil {
handleError(c, err)
return
}
customerId, err := uuid.Parse(accessClaims.Issuer)
if err != nil {
c.String(400, malformedCustomerId)
return
}
userEmail, err := entities.ParseEmail(accessClaims.Subject)
if err != nil {
c.String(400, malformedUserEmail)
return
}
if err = h.API.Signout(userEmail, entities.CustomerId(customerId)); err != nil {
handleError(c, err)
return
}
c.Status(200)
}
func (h *NkodeHandler) ResetHandler(c *gin.Context) {
h.Logger.Println("reset")
token, err := getBearerToken(c)
if err != nil {
c.String(403, "forbidden")
return
}
resetClaims, err := security.ParseRestNKodeToken(token)
if err != nil {
handleError(c, err)
return
}
var postBody models.SignupPostBody
if err = c.ShouldBind(&postBody); err != nil {
handleError(c, err)
return
}
customerId, err := uuid.Parse(postBody.CustomerId)
if err != nil {
c.String(400, malformedCustomerId)
return
}
userEmail, err := entities.ParseEmail(postBody.UserEmail)
if err != nil {
c.String(400, malformedUserEmail)
return
}
if postBody.UserEmail != resetClaims.Subject ||
postBody.CustomerId != resetClaims.Issuer {
c.String(403, "forbidden")
return
}
kp := entities.KeypadDimension{
AttrsPerKey: postBody.AttrsPerKey,
NumbOfKeys: postBody.NumbOfKeys,
}
if err := kp.IsValidKeypadDimension(); err != nil {
c.String(400, invalidKeypadDimensions)
return
}
resp, err := h.API.GenerateSignupResetInterface(userEmail, entities.CustomerId(customerId), kp, true)
if err != nil {
handleError(c, err)
return
}
c.JSON(200, resp)
}
func handleError(c *gin.Context, err error) {
log.Print("handling error: ", err)
statusCode, _ := config.HttpErrMap[err]
switch statusCode {
case 400:
c.String(400, err.Error())
case 403:
c.String(403, err.Error())
case 500:
c.String(500, "Internal Server Error")
default:
log.Print("unknown error: ", err)
c.String(500, "Internal Server Error")
}
}
func getBearerToken(c *gin.Context) (string, error) {
authHeader := c.GetHeader("Authorization")
// Check if the Authorization header is present and starts with "Bearer "
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
return "", errors.New("forbidden")
}
token := strings.TrimPrefix(authHeader, "Bearer ")
return token, nil
}

364
handler/handler_test.go Normal file
View File

@@ -0,0 +1,364 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"fmt"
"git.infra.nkode.tech/dkelly/nkode-core/api"
"git.infra.nkode.tech/dkelly/nkode-core/email"
"git.infra.nkode.tech/dkelly/nkode-core/entities"
"git.infra.nkode.tech/dkelly/nkode-core/models"
"git.infra.nkode.tech/dkelly/nkode-core/repository"
"git.infra.nkode.tech/dkelly/nkode-core/security"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
)
func TestNKodeAPI(t *testing.T) {
tr := NewTestRouter()
tr.Start()
defer func(tr *TestRouter) {
err := tr.Stop()
assert.NoError(t, err)
}(tr)
// *** Create New Customer with invalid access token ***
customerID, err := tr.CreateNewCustomerDefaultPolicy()
assert.NoError(t, err)
attrPerKey := 9
numKeys := 6
userEmail := "test_username" + security.GenerateNonSecureRandomString(12) + "@example.com"
// *** Signup ***
resp, status, err := tr.Signup(customerID, attrPerKey, numKeys, userEmail)
assert.NoError(t, err)
assert.Equal(t, 200, status)
passcodeLen := 4
userPasscode := resp.UserIdxInterface[:passcodeLen]
kpSet := entities.KeypadDimension{
AttrsPerKey: numKeys,
NumbOfKeys: numKeys,
}
setKeySelection, err := entities.SelectKeyByAttrIdx(resp.UserIdxInterface, userPasscode, kpSet)
assert.NoError(t, err)
// *** Set nKode ***
confirmInterface, status, err := tr.SetNKode(customerID, setKeySelection, resp.SessionId)
assert.NoError(t, err)
assert.Equal(t, 200, status)
confirmKeySelection, err := entities.SelectKeyByAttrIdx(confirmInterface, userPasscode, kpSet)
assert.NoError(t, err)
// *** Confirm nKode ***
status, err = tr.ConfirmNKode(customerID, confirmKeySelection, resp.SessionId)
assert.NoError(t, err)
assert.Equal(t, 200, status)
// *** Get Login Interface ***
loginInterface, status, err := tr.GetLoginInterface(userEmail, customerID)
assert.NoError(t, err)
assert.Equal(t, 200, status)
kp := entities.KeypadDimension{
AttrsPerKey: attrPerKey,
NumbOfKeys: numKeys,
}
loginKeySelection, err := entities.SelectKeyByAttrIdx(loginInterface.UserIdxInterface, userPasscode, kp)
assert.NoError(t, err)
// *** Login ***
tokens, status, err := tr.Login(customerID, userEmail, loginKeySelection)
assert.NoError(t, err)
assert.Equal(t, 200, status)
assert.NotEmpty(t, tokens.AccessToken)
assert.NotEmpty(t, tokens.RefreshToken)
// *** Renew Attributes ***
status, err = tr.RenewAttributes(customerID)
assert.NoError(t, err)
assert.Equal(t, 200, status)
loginInterface, status, err = tr.GetLoginInterface(userEmail, customerID)
assert.NoError(t, err)
loginKeySelection, err = entities.SelectKeyByAttrIdx(loginInterface.UserIdxInterface, userPasscode, kp)
assert.NoError(t, err)
tokens, status, err = tr.Login(customerID, userEmail, loginKeySelection)
assert.NoError(t, err)
// *** Test Forgot nKode ***
status, err = tr.ForgotNKode(customerID, userEmail)
assert.NoError(t, err)
assert.Equal(t, 200, status)
// *** Test Reset nKode ***
nkodeResetJwt, err := security.ResetNKodeToken(userEmail, customerID)
assert.NoError(t, err)
resetResp, status, err := tr.Reset(customerID, attrPerKey, numKeys, userEmail, nkodeResetJwt)
assert.NoError(t, err)
assert.Equal(t, 200, status)
assert.NotEmpty(t, resetResp.SessionId)
userPasscode = resetResp.UserIdxInterface[:passcodeLen]
setKeySelection, err = entities.SelectKeyByAttrIdx(resetResp.UserIdxInterface, userPasscode, kpSet)
assert.NoError(t, err)
confirmInterface, status, err = tr.SetNKode(customerID, setKeySelection, resetResp.SessionId)
assert.NoError(t, err)
assert.Equal(t, 200, status)
confirmKeySelection, err = entities.SelectKeyByAttrIdx(confirmInterface, userPasscode, kpSet)
assert.NoError(t, err)
status, err = tr.ConfirmNKode(customerID, confirmKeySelection, resetResp.SessionId)
assert.NoError(t, err)
assert.Equal(t, 200, status)
loginInterface, status, err = tr.GetLoginInterface(userEmail, customerID)
assert.NoError(t, err)
assert.Equal(t, 200, status)
loginKeySelection, err = entities.SelectKeyByAttrIdx(loginInterface.UserIdxInterface, userPasscode, kp)
assert.NoError(t, err)
tokens, status, err = tr.Login(customerID, userEmail, loginKeySelection)
assert.NoError(t, err)
assert.Equal(t, 200, status)
assert.NotEmpty(t, tokens.AccessToken)
assert.NotEmpty(t, tokens.RefreshToken)
// *** Test Reset nKode with invalid token ***
_, status, err = tr.Reset(customerID, attrPerKey, numKeys, userEmail, "invalid token")
assert.Error(t, err)
assert.Equal(t, 403, status)
}
type TestRouter struct {
router *gin.Engine
emailQueue *email.Queue
repo *repository.SqliteRepository
handler *NkodeHandler
}
func NewTestRouter() *TestRouter {
gin.SetMode(gin.TestMode)
router := gin.Default()
logger := log.Default()
ctx := context.Background()
dbPath := os.Getenv("TEST_DB")
repo, err := repository.NewSqliteRepository(ctx, dbPath)
if err != nil {
log.Fatal(err)
}
emailClient := email.TestEmailClient{}
emailQueue := email.NewEmailQueue(email.EmailQueueBufferSize, email.MaxEmailsPerSecond, &emailClient)
nkodeAPI := api.NewNKodeAPI(repo, emailQueue)
h := NkodeHandler{
API: nkodeAPI,
Logger: logger,
}
h.RegisterRoutes(router)
return &TestRouter{
handler: &h,
router: router,
emailQueue: emailQueue,
repo: repo,
}
}
func (r *TestRouter) Start() {
r.repo.Start()
r.emailQueue.Start()
}
func (r *TestRouter) Stop() error {
r.emailQueue.Stop()
return r.repo.Stop()
}
func (r *TestRouter) CreateNewCustomerDefaultPolicy() (string, error) {
customerId, err := r.handler.API.CreateNewCustomer(entities.NewDefaultNKodePolicy())
if err != nil {
return "", err
}
return customerId.String(), nil
}
func (r *TestRouter) Signup(
customerID string,
attrsPerKey int,
numberOfKeys int,
userEmail string,
) (*entities.SignupResetInterface, int, error) {
body := bytes.NewBufferString(fmt.Sprintf(
"customer_id=%s&attrs_per_key=%d&numb_of_keys=%d&email=%s",
customerID,
attrsPerKey,
numberOfKeys,
userEmail,
))
req := httptest.NewRequest(http.MethodPost, "/signup", body)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
r.router.ServeHTTP(rec, req)
var resp entities.SignupResetInterface
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
return nil, rec.Code, err
}
return &resp, rec.Code, nil
}
func (r *TestRouter) SetNKode(
customerID string,
selection []int,
sessionID string,
) ([]int, int, error) {
data := models.SetNKodePost{
CustomerId: customerID,
KeySelection: selection,
SessionId: sessionID,
}
body, err := json.Marshal(data)
if err != nil {
return nil, 0, err
}
req := httptest.NewRequest(http.MethodPost, "/set-nkode", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
r.router.ServeHTTP(rec, req)
var resp struct {
UserInterface []int `json:"user_interface"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
return nil, rec.Code, err
}
return resp.UserInterface, rec.Code, nil
}
func (r *TestRouter) ConfirmNKode(
customerID string,
selection entities.KeySelection,
sessionID string,
) (int, error) {
data := models.ConfirmNKodePost{
CustomerId: customerID,
KeySelection: selection,
SessionId: sessionID,
}
body, err := json.Marshal(data)
if err != nil {
return 0, err
}
req := httptest.NewRequest(http.MethodPost, "/confirm-nkode", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
r.router.ServeHTTP(rec, req)
return rec.Code, nil
}
func (r *TestRouter) GetLoginInterface(
userEmail string,
customerID string,
) (entities.LoginInterface, int, error) {
body := bytes.NewBufferString(fmt.Sprintf(
"email=%s&customer_id=%s",
userEmail,
customerID,
))
req := httptest.NewRequest(http.MethodPost, "/get-login-interface", body)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
r.router.ServeHTTP(rec, req)
var resp entities.LoginInterface
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
return entities.LoginInterface{}, rec.Code, err
}
return resp, rec.Code, nil
}
func (r *TestRouter) Login(
customerID string,
userEmail string,
selection []int,
) (security.AuthenticationTokens, int, error) {
data := models.LoginPost{
CustomerId: customerID,
UserEmail: userEmail,
KeySelection: selection,
}
body, err := json.Marshal(data)
if err != nil {
return security.AuthenticationTokens{}, 0, err
}
req := httptest.NewRequest(http.MethodPost, "/login", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
r.router.ServeHTTP(rec, req)
var resp security.AuthenticationTokens
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
return security.AuthenticationTokens{}, rec.Code, err
}
return resp, rec.Code, nil
}
func (r *TestRouter) RenewAttributes(
customerID string,
) (int, error) {
data := models.RenewAttributesPost{
CustomerId: customerID,
}
body, err := json.Marshal(data)
if err != nil {
return 0, err
}
req := httptest.NewRequest(http.MethodPost, "/renew-attributes", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
r.router.ServeHTTP(rec, req)
return rec.Code, nil
}
func (r *TestRouter) ForgotNKode(
customerID string,
userEmail string,
) (int, error) {
data := models.ForgotNKodePost{
CustomerId: customerID,
UserEmail: userEmail,
}
body, err := json.Marshal(data)
if err != nil {
return 0, err
}
req := httptest.NewRequest(http.MethodPost, "/forgot-nkode", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
r.router.ServeHTTP(rec, req)
return rec.Code, nil
}
func (r *TestRouter) Reset(
customerID string,
attrsPerKey int,
numberOfKeys int,
userEmail string,
resetAuthToken string,
) (*entities.SignupResetInterface, int, error) {
body := bytes.NewBufferString(fmt.Sprintf(
"customer_id=%s&attrs_per_key=%d&numb_of_keys=%d&email=%s",
customerID,
attrsPerKey,
numberOfKeys,
userEmail,
))
req := httptest.NewRequest(http.MethodPost, "/reset-nkode", body)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", "Bearer "+resetAuthToken)
rec := httptest.NewRecorder()
r.router.ServeHTTP(rec, req)
var resp entities.SignupResetInterface
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
return nil, rec.Code, err
}
return &resp, rec.Code, nil
}

38
memCache/forgot_nkode.go Normal file
View File

@@ -0,0 +1,38 @@
package memCache
import (
"git.infra.nkode.tech/dkelly/nkode-core/entities"
"github.com/patrickmn/go-cache"
"time"
)
const (
forgotExpiration = 5 * time.Minute
forgotCleanupInterval = 10 * time.Minute
)
type ForgotNKodeCache struct {
innerCache *cache.Cache
}
func NewForgotNKodeCache() ForgotNKodeCache {
forgotCache := cache.New(forgotExpiration, forgotCleanupInterval)
return ForgotNKodeCache{forgotCache}
}
func (f *ForgotNKodeCache) Set(userEmail entities.UserEmail, customerId entities.CustomerId) {
f.innerCache.Set(key(userEmail, customerId), true, forgotExpiration)
}
func (f *ForgotNKodeCache) Get(userEmail entities.UserEmail, customerId entities.CustomerId) bool {
_, found := f.innerCache.Get(key(userEmail, customerId))
return found
}
func (f *ForgotNKodeCache) Delete(userEmail entities.UserEmail, customerId entities.CustomerId) {
f.innerCache.Delete(key(userEmail, customerId))
}
func key(email entities.UserEmail, id entities.CustomerId) string {
return string(email) + id.String()
}

59
models/models.go Normal file
View File

@@ -0,0 +1,59 @@
package models
import "git.infra.nkode.tech/dkelly/nkode-core/entities"
type SetNKodeResp struct {
UserInterface []int `json:"user_interface"`
}
type RandomSvgInterfaceResp struct {
Svgs []string `form:"svgs" binding:"required"`
Colors []entities.RGBColor `form:"colors" binding:"required"`
}
type RefreshTokenResp struct {
AccessToken string `form:"access_token" binding:"required"`
}
type SignupPostBody struct {
CustomerId string `form:"customer_id"`
AttrsPerKey int `form:"attrs_per_key"`
NumbOfKeys int `form:"numb_of_keys"`
UserEmail string `form:"email"`
}
type SetNKodePost struct {
CustomerId string `json:"customer_id" binding:"required"`
KeySelection []int `json:"key_selection" binding:"required"`
SessionId string `json:"session_id" binding:"required"`
}
type ConfirmNKodePost struct {
CustomerId string `json:"customer_id" binding:"required"`
KeySelection []int `json:"key_selection" binding:"required"`
SessionId string `json:"session_id" binding:"required"`
}
type LoginInterfacePost struct {
UserEmail string `form:"email" binding:"required"`
CustomerId string `form:"customer_id" binding:"required"`
}
type LoginPost struct {
CustomerId string `form:"customer_id" binding:"required"`
UserEmail string `form:"email" binding:"required"`
KeySelection entities.KeySelection `form:"key_selection" binding:"required"`
}
type RenewAttributesPost struct {
CustomerId string `form:"customer_id" binding:"required"`
}
type ForgotNKodePost struct {
UserEmail string `form:"email" binding:"required"`
CustomerId string `form:"customer_id" binding:"required"`
}
type CreateNewCustomerResp struct {
CustomerId string `form:"customer_id" binding:"required"`
}

View File

@@ -5,7 +5,6 @@ import (
"database/sql"
"errors"
"fmt"
"git.infra.nkode.tech/dkelly/nkode-core/config"
"git.infra.nkode.tech/dkelly/nkode-core/entities"
"git.infra.nkode.tech/dkelly/nkode-core/security"
"git.infra.nkode.tech/dkelly/nkode-core/sqlc"
@@ -20,11 +19,27 @@ type SqliteRepository struct {
ctx context.Context
}
func NewSqliteRepository(queue *sqlc.Queue, ctx context.Context) SqliteRepository {
return SqliteRepository{
func NewSqliteRepository(ctx context.Context, dbPath string) (*SqliteRepository, error) {
sqliteDb, err := sqlc.OpenSqliteDb(dbPath)
if err != nil {
return nil, err
}
queue, err := sqlc.NewQueue(sqliteDb, ctx)
if err != nil {
return nil, err
}
return &SqliteRepository{
Queue: queue,
ctx: ctx,
}
}, nil
}
func (d *SqliteRepository) Start() {
d.Queue.Start()
}
func (d *SqliteRepository) Stop() error {
return d.Queue.Stop()
}
func (d *SqliteRepository) CreateCustomer(c entities.Customer) error {
@@ -162,8 +177,7 @@ func (d *SqliteRepository) Renew(id entities.CustomerId) error {
if err != nil {
return err
}
customerId := entities.CustomerIdToString(id)
userRenewRows, err := d.Queue.Queries.GetUserRenew(d.ctx, customerId)
userRenewRows, err := d.Queue.Queries.GetUserRenew(d.ctx, id.String())
if err != nil {
return err
}
@@ -264,6 +278,17 @@ func (d *SqliteRepository) RefreshUserPasscode(user entities.User, passcodeIdx [
return d.Queue.EnqueueWriteTx(queryFunc, params)
}
func (d *SqliteRepository) AddSvg(svg string) error {
queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error {
params, ok := args.(string)
if !ok {
return fmt.Errorf("invalid argument type: expected AddSvg")
}
return q.AddSvg(ctx, params)
}
return d.Queue.EnqueueWriteTx(queryFunc, svg)
}
func (d *SqliteRepository) GetCustomer(id entities.CustomerId) (*entities.Customer, error) {
customer, err := d.Queue.Queries.GetCustomer(d.ctx, uuid.UUID(id).String())
if err != nil {
@@ -350,6 +375,26 @@ func (d *SqliteRepository) GetSvgStringInterface(idxs entities.SvgIdInterface) (
return d.getSvgsById(idxs)
}
// Is this even useful?
func (d *SqliteRepository) AddUserPermission(userEmail entities.UserEmail, customerId entities.CustomerId, permission entities.UserPermission) error {
user, err := d.GetUser(userEmail, customerId)
if err != nil {
return err
}
queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error {
params, ok := args.(sqlc.AddUserPermissionParams)
if !ok {
return fmt.Errorf("invalid argument type: expected AddUserPermissionParams")
}
return q.AddUserPermission(ctx, params)
}
params := sqlc.AddUserPermissionParams{
UserID: user.Id.String(),
Permission: permission.String(),
}
return d.Queue.EnqueueWriteTx(queryFunc, params)
}
func (d *SqliteRepository) getSvgsById(ids []int) ([]string, error) {
svgs := make([]string, len(ids))
for idx, id := range ids {
@@ -363,39 +408,12 @@ func (d *SqliteRepository) getSvgsById(ids []int) ([]string, error) {
}
func (d *SqliteRepository) getRandomIds(count int) ([]int, error) {
tx, err := d.Queue.Db.Begin()
totalRows, err := d.Queue.Queries.GetSvgCount(d.ctx)
if err != nil {
log.Print(err)
return nil, config.ErrSqliteTx
}
rows, err := tx.Query("SELECT COUNT(*) as count FROM svg_icon;")
if err != nil {
log.Print(err)
return nil, config.ErrSqliteTx
}
var tableLen int
if !rows.Next() {
return nil, config.ErrEmptySvgTable
}
if err = rows.Scan(&tableLen); err != nil {
log.Print(err)
return nil, config.ErrSqliteTx
}
perm, err := security.RandomPermutation(tableLen)
if err != nil {
return nil, err
}
for idx := range perm {
perm[idx] += 1
}
if err = tx.Commit(); err != nil {
log.Print(err)
return nil, config.ErrSqliteTx
}
perm, err := security.RandomPermutation(int(totalRows))
return perm[:count], nil
}

View File

@@ -3,7 +3,6 @@ package repository
import (
"context"
"git.infra.nkode.tech/dkelly/nkode-core/entities"
"git.infra.nkode.tech/dkelly/nkode-core/sqlc"
"github.com/stretchr/testify/assert"
"os"
"testing"
@@ -11,20 +10,16 @@ import (
func TestNewSqliteDB(t *testing.T) {
dbPath := os.Getenv("TEST_DB")
// sql_driver.MakeTables(dbFile)
ctx := context.Background()
sqliteDb, err := sqlc.OpenSqliteDb(dbPath)
sqliteDb, err := NewSqliteRepository(ctx, dbPath)
assert.NoError(t, err)
queue, err := sqlc.NewQueue(sqliteDb, ctx)
assert.NoError(t, err)
queue.Start()
defer queue.Stop()
db := NewSqliteRepository(queue, ctx)
assert.NoError(t, err)
testSignupLoginRenew(t, &db)
testSqliteDBRandomSvgInterface(t, &db)
sqliteDb.Start()
defer func(t *testing.T, sqliteDb *SqliteRepository) {
err := sqliteDb.Stop()
assert.NoError(t, err)
}(t, sqliteDb)
testSignupLoginRenew(t, sqliteDb)
testSqliteDBRandomSvgInterface(t, sqliteDb)
}
func testSignupLoginRenew(t *testing.T, db CustomerUserRepository) {

View File

@@ -65,6 +65,7 @@ func NewAuthenticationTokens(username string, customerId uuid.UUID) (Authenticat
}
func NewAccessClaim(username string, customerId uuid.UUID) jwt.RegisteredClaims {
// TODO: CHANGE ISSUER TO BE URL
return jwt.RegisteredClaims{
Subject: username,
Issuer: customerId.String(),
@@ -85,6 +86,10 @@ func ParseRestNKodeToken(resetNKodeToken string) (*ResetNKodeClaims, error) {
return parseJwt[*ResetNKodeClaims](resetNKodeToken, &ResetNKodeClaims{})
}
func ParseResetNKodeClaim(token string) (*ResetNKodeClaims, error) {
return parseJwt[*ResetNKodeClaims](token, &ResetNKodeClaims{})
}
func parseJwt[T *ResetNKodeClaims | *jwt.RegisteredClaims](tokenStr string, claim jwt.Claims) (T, error) {
token, err := jwt.ParseWithClaims(tokenStr, claim, func(token *jwt.Token) (interface{}, error) {
return secret, nil
@@ -110,12 +115,12 @@ func ClaimExpired(claims jwt.RegisteredClaims) error {
return config.ErrClaimExpOrNil
}
func ResetNKodeToken(userEmail string, customerId uuid.UUID) (string, error) {
func ResetNKodeToken(userEmail string, customerId string) (string, error) {
resetClaims := ResetNKodeClaims{
true,
jwt.RegisteredClaims{
Subject: userEmail,
Issuer: customerId.String(),
Issuer: customerId,
ExpiresAt: jwt.NewNumericDate(time.Now().Add(resetNKodeTokenExp)),
},
}

View File

@@ -19,7 +19,7 @@ func TestJwtClaims(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, refreshToken.Subject, email)
assert.NoError(t, ClaimExpired(*refreshToken))
resetNKode, err := ResetNKodeToken(email, customerId)
resetNKode, err := ResetNKodeToken(email, customerId.String())
assert.NoError(t, err)
resetToken, err := ParseRestNKodeToken(resetNKode)
assert.NoError(t, err)

View File

@@ -268,8 +268,7 @@ func Choice[T any](items []T) T {
return items[r.Intn(len(items))]
}
// GenerateRandomString creates a random string of a specified length.
func GenerateRandomString(length int) string {
func GenerateNonSecureRandomString(length int) string {
charset := []rune("abcdefghijklmnopqrstuvwxyz0123456789")
b := make([]rune, length)
for i := range b {

View File

@@ -6,4 +6,4 @@ sql:
gen:
go:
package: "sqlc"
out: "./pkg/nkode-core/sqlc"
out: "./sqlc"

View File

@@ -48,3 +48,9 @@ type User struct {
LastLogin interface{}
CreatedAt sql.NullString
}
type UserPermission struct {
ID int64
UserID string
Permission string
}

View File

@@ -10,6 +10,29 @@ import (
"database/sql"
)
const addSvg = `-- name: AddSvg :exec
INSERT INTO svg_icon (svg) VALUES (?)
`
func (q *Queries) AddSvg(ctx context.Context, svg string) error {
_, err := q.db.ExecContext(ctx, addSvg, svg)
return err
}
const addUserPermission = `-- name: AddUserPermission :exec
INSERT INTO user_permission (user_id, permission) VALUES (?, ?)
`
type AddUserPermissionParams struct {
UserID string
Permission string
}
func (q *Queries) AddUserPermission(ctx context.Context, arg AddUserPermissionParams) error {
_, err := q.db.ExecContext(ctx, addUserPermission, arg.UserID, arg.Permission)
return err
}
const createCustomer = `-- name: CreateCustomer :exec
INSERT INTO customer (
id
@@ -259,6 +282,33 @@ func (q *Queries) GetUser(ctx context.Context, arg GetUserParams) (GetUserRow, e
return i, err
}
const getUserPermissions = `-- name: GetUserPermissions :many
SELECT permission FROM user_permission WHERE user_id = ?
`
func (q *Queries) GetUserPermissions(ctx context.Context, userID string) ([]string, error) {
rows, err := q.db.QueryContext(ctx, getUserPermissions, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []string
for rows.Next() {
var permission string
if err := rows.Scan(&permission); err != nil {
return nil, err
}
items = append(items, permission)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getUserRenew = `-- name: GetUserRenew :many
SELECT
id

View File

@@ -10,11 +10,11 @@ import (
const writeBufferSize = 100
type SqlcGeneric func(*Queries, context.Context, any) error
type GenericQuery func(*Queries, context.Context, any) error
type WriteTx struct {
ErrChan chan error
Query SqlcGeneric
Query GenericQuery
Args interface{}
}
@@ -63,7 +63,7 @@ func (d *Queue) Stop() error {
return d.Db.Close()
}
func (d *Queue) EnqueueWriteTx(queryFunc SqlcGeneric, args any) error {
func (d *Queue) EnqueueWriteTx(queryFunc GenericQuery, args any) error {
select {
case <-d.ctx.Done():
return errors.New("database is shutting down")

6
sqlite/embed.go Normal file
View File

@@ -0,0 +1,6 @@
package sqlite
import "embed"
//go:embed schema.sql
var FS embed.FS

View File

@@ -37,6 +37,9 @@ INSERT INTO user (
)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);
-- name: AddSvg :exec
INSERT INTO svg_icon (svg) VALUES (?);
-- name: UpdateUser :exec
UPDATE user
SET renew = ?
@@ -134,3 +137,9 @@ WHERE id = ?;
-- name: GetSvgCount :one
SELECT COUNT(*) as count FROM svg_icon;
-- name: GetUserPermissions :many
SELECT permission FROM user_permission WHERE user_id = ?;
-- name: AddUserPermission :exec
INSERT INTO user_permission (user_id, permission) VALUES (?, ?);

View File

@@ -55,3 +55,12 @@ CREATE TABLE IF NOT EXISTS svg_icon (
id INTEGER PRIMARY KEY AUTOINCREMENT
,svg TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS user_permission (
id INTEGER PRIMARY KEY AUTOINCREMENT
,user_id TEXT NOT NULL
,permission TEXT NOT NULL
,FOREIGN KEY (user_id) REFERENCES user(id)
,UNIQUE(user_id, permission)
);