From 6b8887832ee9aa24b8e89dade166ada3d75964b3 Mon Sep 17 00:00:00 2001 From: Donovan Date: Wed, 12 Feb 2025 06:39:51 -0600 Subject: [PATCH 1/5] add license --- LICENSE | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4026186 --- /dev/null +++ b/LICENSE @@ -0,0 +1,2 @@ +This software is provided for personal and non-commercial use only. +Any commercial use, including but not limited to resale, incorporation into a commercial product, or use in a for-profit service, is strictly prohibited without prior written permission from the author. \ No newline at end of file -- 2.49.1 From f948a06b661d0f329d27e89a8373fe1769bc7155 Mon Sep 17 00:00:00 2001 From: Donovan Date: Thu, 13 Feb 2025 07:37:06 -0600 Subject: [PATCH 2/5] add sessions --- sqlc/models.go | 7 +++++++ sqlc/query.sql.go | 46 +++++++++++++++++++++++++++++++++++++++++++++- sqlite/query.sql | 16 +++++++++++++++- sqlite/schema.sql | 8 ++++++++ 4 files changed, 75 insertions(+), 2 deletions(-) diff --git a/sqlc/models.go b/sqlc/models.go index fdea8e3..9a5dabb 100644 --- a/sqlc/models.go +++ b/sqlc/models.go @@ -57,6 +57,13 @@ type Customer struct { CreatedAt string } +type Session struct { + ID string + UserID string + CreatedAt sql.NullTime + ExpiresAt time.Time +} + type SvgIcon struct { ID int64 Svg string diff --git a/sqlc/query.sql.go b/sqlc/query.sql.go index b6aa826..9af1949 100644 --- a/sqlc/query.sql.go +++ b/sqlc/query.sql.go @@ -176,6 +176,22 @@ func (q *Queries) CreateRedirectURI(ctx context.Context, arg CreateRedirectURIPa return err } +const createSession = `-- name: CreateSession :exec +INSERT INTO sessions (id, user_id, expires_at) +VALUES (?, ?, ?) +` + +type CreateSessionParams struct { + ID string + UserID string + ExpiresAt time.Time +} + +func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) error { + _, err := q.db.ExecContext(ctx, createSession, arg.ID, arg.UserID, arg.ExpiresAt) + return err +} + const createToken = `-- name: CreateToken :exec INSERT INTO tokens (token_type, token_value, user_id, client_id, scope, expires_at) VALUES (?, ?, ?, ?, ?, ?) @@ -291,6 +307,16 @@ func (q *Queries) DeleteOldAuthCodes(ctx context.Context) error { return err } +const deleteOldSessions = `-- name: DeleteOldSessions :exec +DELETE FROM sessions +WHERE expires_at < CURRENT_TIMESTAMP +` + +func (q *Queries) DeleteOldSessions(ctx context.Context) error { + _, err := q.db.ExecContext(ctx, deleteOldSessions) + return err +} + const deleteOldTokens = `-- name: DeleteOldTokens :exec DELETE FROM tokens WHERE expires_at < CURRENT_TIMESTAMP @@ -434,6 +460,24 @@ func (q *Queries) GetOIDCClientByID(ctx context.Context, id string) (Client, err return i, err } +const getSessionByID = `-- name: GetSessionByID :one +SELECT id, user_id, created_at, expires_at +FROM sessions +WHERE id = ? +` + +func (q *Queries) GetSessionByID(ctx context.Context, id string) (Session, error) { + row := q.db.QueryRowContext(ctx, getSessionByID, id) + var i Session + err := row.Scan( + &i.ID, + &i.UserID, + &i.CreatedAt, + &i.ExpiresAt, + ) + return i, err +} + const getSvgCount = `-- name: GetSvgCount :one SELECT COUNT(*) as count FROM svg_icon ` @@ -554,7 +598,7 @@ FROM clients WHERE owner = ? ` -// -------- go-oidc +// -------- go-oidc ---------- func (q *Queries) GetUserClients(ctx context.Context, owner string) ([]Client, error) { rows, err := q.db.QueryContext(ctx, getUserClients, owner) if err != nil { diff --git a/sqlite/query.sql b/sqlite/query.sql index 936ea66..5eeb82c 100644 --- a/sqlite/query.sql +++ b/sqlite/query.sql @@ -145,7 +145,7 @@ SELECT permission FROM user_permission WHERE user_id = ?; INSERT INTO user_permission (user_id, permission) VALUES (?, ?); ----------- go-oidc +---------- go-oidc ---------- -- name: GetUserClients :many SELECT * @@ -191,6 +191,10 @@ WHERE expires_at < CURRENT_TIMESTAMP; DELETE FROM tokens WHERE expires_at < CURRENT_TIMESTAMP; +-- name: DeleteOldSessions :exec +DELETE FROM sessions +WHERE expires_at < CURRENT_TIMESTAMP; + -- name: GetTokenByValue :one SELECT * FROM tokens @@ -212,3 +216,13 @@ WHERE user_id = ? AND client_id = ?; -- name: DeleteAuthCode :exec DELETE FROM authorization_codes WHERE code = ?; + +-- name: GetSessionByID :one +SELECT * +FROM sessions +WHERE id = ?; + +-- name: CreateSession :exec +INSERT INTO sessions (id, user_id, expires_at) +VALUES (?, ?, ?); + diff --git a/sqlite/schema.sql b/sqlite/schema.sql index 6cc6a92..922c791 100644 --- a/sqlite/schema.sql +++ b/sqlite/schema.sql @@ -123,3 +123,11 @@ CREATE TABLE IF NOT EXISTS client_approvals ( ,FOREIGN KEY (user_id) REFERENCES users (id) ,FOREIGN KEY (client_id) REFERENCES clients (id) ); + +CREATE TABLE IF NOT EXISTS sessions ( + id TEXT PRIMARY KEY + ,user_id TEXT NOT NULL + ,created_at DATETIME DEFAULT CURRENT_TIMESTAMP + ,expires_at DATETIME NOT NULL + ,FOREIGN KEY (user_id) REFERENCES user (id) +); -- 2.49.1 From 32facb1767b24d48c6a892e4bc0fc071c8f129b2 Mon Sep 17 00:00:00 2001 From: Donovan Date: Thu, 13 Feb 2025 08:00:49 -0600 Subject: [PATCH 3/5] replace Id with ID --- Taskfile.yaml | 3 ++ api/nkode_api.go | 42 ++++++++-------- api/nkode_api_test.go | 8 +-- entities/customer.go | 6 +-- entities/customer_test.go | 4 +- entities/models.go | 30 +++++------ entities/user.go | 8 +-- entities/user_interface.go | 6 +-- entities/user_signup_session.go | 10 ++-- entities/user_test.go | 6 +-- handler/handler.go | 70 +++++++++++++------------- handler/handler_test.go | 24 ++++----- memcache/forgot_nkode.go | 8 +-- models/models.go | 20 ++++---- repository/customer_user_repository.go | 14 +++--- repository/sqlite_nkode_repo.go | 66 ++++++++++++------------ repository/sqlite_nkode_repo_test.go | 8 +-- sqlc/query.sql.go | 6 +-- sqlite/query.sql | 2 +- 19 files changed, 172 insertions(+), 169 deletions(-) diff --git a/Taskfile.yaml b/Taskfile.yaml index e6d3f3c..f55d42c 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -3,6 +3,7 @@ version: "3" vars: test_db: "~/databases/test.db" schema_db: "./sqlite/schema.sql" + svg_path: "~/svgs/flaticon_colored_svgs" tasks: sqlc: cmds: @@ -10,5 +11,7 @@ tasks: rebuild_test_db: cmds: + - go build cmd/nkode/nkode.go - rm {{.test_db}} - sqlite3 {{.test_db}} < {{.schema_db}} + - ./nkode -db-path {{.test_db}} -svg-path {{.svg_path}} diff --git a/api/nkode_api.go b/api/nkode_api.go index 42d027e..050c342 100644 --- a/api/nkode_api.go +++ b/api/nkode_api.go @@ -36,7 +36,7 @@ func NewNKodeAPI(repo repository.CustomerUserRepository, queue *email.Queue) NKo } } -func (n *NKodeAPI) CreateNewCustomer(nkodePolicy entities.NKodePolicy) (*entities.CustomerId, error) { +func (n *NKodeAPI) CreateNewCustomer(nkodePolicy entities.NKodePolicy) (*entities.CustomerID, error) { newCustomer, err := entities.NewCustomer(nkodePolicy) if err != nil { return nil, err @@ -46,22 +46,22 @@ func (n *NKodeAPI) CreateNewCustomer(nkodePolicy entities.NKodePolicy) (*entitie if err != nil { return nil, err } - return &newCustomer.Id, nil + return &newCustomer.ID, nil } -func (n *NKodeAPI) CreateCustomerWithID(id entities.CustomerId, nkodePolicy entities.NKodePolicy) error { +func (n *NKodeAPI) CreateCustomerWithID(id entities.CustomerID, nkodePolicy entities.NKodePolicy) error { newCustomer, err := entities.NewCustomer(nkodePolicy) if err != nil { return err } - newCustomer.Id = id + 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) { +func (n *NKodeAPI) GenerateSignupResetInterface(userEmail entities.UserEmail, customerId entities.CustomerID, kp entities.KeypadDimension, reset bool) (*entities.SignupResetInterface, error) { user, err := n.repo.GetUser(userEmail, customerId) if err != nil { return nil, err @@ -78,23 +78,23 @@ 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.repo.GetSvgStringInterface(signupSession.LoginUserInterface.SvgId) + svgInterface, err := n.repo.GetSvgStringInterface(signupSession.LoginUserInterface.SvgID) if err != nil { return nil, err } resp := entities.SignupResetInterface{ UserIdxInterface: signupSession.SetIdxInterface, SvgInterface: svgInterface, - SessionId: uuid.UUID(signupSession.Id).String(), + SessionID: uuid.UUID(signupSession.ID).String(), Colors: signupSession.Colors, } return &resp, nil } -func (n *NKodeAPI) SetNKode(customerId entities.CustomerId, sessionId entities.SessionId, keySelection entities.KeySelection) (entities.IdxInterface, error) { +func (n *NKodeAPI) SetNKode(customerId entities.CustomerID, sessionId entities.SessionID, keySelection entities.KeySelection) (entities.IdxInterface, error) { _, err := n.repo.GetCustomer(customerId) if err != nil { @@ -118,7 +118,7 @@ func (n *NKodeAPI) SetNKode(customerId entities.CustomerId, sessionId entities.S return confirmInterface, nil } -func (n *NKodeAPI) ConfirmNKode(customerId entities.CustomerId, sessionId entities.SessionId, keySelection entities.KeySelection) error { +func (n *NKodeAPI) ConfirmNKode(customerId entities.CustomerID, sessionId entities.SessionID, keySelection entities.KeySelection) error { session, exists := n.signupSessionCache.Get(sessionId.String()) if !exists { log.Printf("session id does not exist %s", sessionId) @@ -149,11 +149,11 @@ func (n *NKodeAPI) ConfirmNKode(customerId entities.CustomerId, sessionId entiti } else { 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) { +func (n *NKodeAPI) GetLoginInterface(userEmail entities.UserEmail, customerId entities.CustomerID) (*entities.LoginInterface, error) { user, err := n.repo.GetUser(userEmail, customerId) if err != nil { return nil, err @@ -162,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.repo.GetSvgStringInterface(user.Interface.SvgId) + svgInterface, err := n.repo.GetSvgStringInterface(user.Interface.SvgID) if err != nil { return nil, err } @@ -176,7 +176,7 @@ func (n *NKodeAPI) GetLoginInterface(userEmail entities.UserEmail, customerId en return &resp, nil } -func (n *NKodeAPI) Login(customerId entities.CustomerId, userEmail entities.UserEmail, keySelection entities.KeySelection) (*security.AuthenticationTokens, error) { +func (n *NKodeAPI) Login(customerId entities.CustomerID, userEmail entities.UserEmail, keySelection entities.KeySelection) (*security.AuthenticationTokens, error) { customer, err := n.repo.GetCustomer(customerId) if err != nil { return nil, err @@ -205,19 +205,19 @@ func (n *NKodeAPI) Login(customerId entities.CustomerId, userEmail entities.User if err != nil { return nil, err } - if err = n.repo.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.repo.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 { +func (n *NKodeAPI) RenewAttributes(customerId entities.CustomerID) error { return n.repo.Renew(customerId) } @@ -225,7 +225,7 @@ func (n *NKodeAPI) RandomSvgInterface() ([]string, error) { return n.repo.RandomSvgInterface(entities.KeypadMax) } -func (n *NKodeAPI) RefreshToken(userEmail entities.UserEmail, customerId entities.CustomerId, refreshToken string) (string, error) { +func (n *NKodeAPI) RefreshToken(userEmail entities.UserEmail, customerId entities.CustomerID, refreshToken string) (string, error) { user, err := n.repo.GetUser(userEmail, customerId) if err != nil { return "", err @@ -248,7 +248,7 @@ func (n *NKodeAPI) RefreshToken(userEmail entities.UserEmail, customerId entitie return security.EncodeAndSignClaims(newAccessClaims) } -func (n *NKodeAPI) ForgotNKode(userEmail entities.UserEmail, customerId entities.CustomerId) error { +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) @@ -278,7 +278,7 @@ func (n *NKodeAPI) ForgotNKode(userEmail entities.UserEmail, customerId entities return nil } -func (n *NKodeAPI) Signout(userEmail entities.UserEmail, customerId entities.CustomerId) error { +func (n *NKodeAPI) Signout(userEmail entities.UserEmail, customerId entities.CustomerID) error { user, err := n.repo.GetUser(userEmail, customerId) if err != nil { return err @@ -287,7 +287,7 @@ func (n *NKodeAPI) Signout(userEmail entities.UserEmail, customerId entities.Cus log.Printf("user %s for customer %s dne", userEmail, customerId) return config.ErrUserForCustomerDNE } - if err = n.repo.UpdateUserRefreshToken(user.Id, ""); err != nil { + if err = n.repo.UpdateUserRefreshToken(user.ID, ""); err != nil { return err } return nil diff --git a/api/nkode_api_test.go b/api/nkode_api_test.go index d153f03..daf9ef8 100644 --- a/api/nkode_api_test.go +++ b/api/nkode_api_test.go @@ -52,8 +52,8 @@ func testNKodeAPI(t *testing.T, db repository.CustomerUserRepository) { signupResponse, err := nkodeApi.GenerateSignupResetInterface(userEmail, *customerId, keypadSize, false) assert.NoError(t, err) setInterface := signupResponse.UserIdxInterface - sessionIdStr := signupResponse.SessionId - sessionId, err := entities.SessionIdFromString(sessionIdStr) + sessionIdStr := signupResponse.SessionID + sessionId, err := entities.SessionIDFromString(sessionIdStr) assert.NoError(t, err) keypadSize = entities.KeypadDimension{AttrsPerKey: numbOfKeys, NumbOfKeys: numbOfKeys} userPasscode := setInterface[:passcodeLen] @@ -89,8 +89,8 @@ func testNKodeAPI(t *testing.T, db repository.CustomerUserRepository) { resetResponse, err := nkodeApi.GenerateSignupResetInterface(userEmail, *customerId, keypadSize, true) assert.NoError(t, err) setInterface = resetResponse.UserIdxInterface - sessionIdStr = resetResponse.SessionId - sessionId, err = entities.SessionIdFromString(sessionIdStr) + sessionIdStr = resetResponse.SessionID + sessionId, err = entities.SessionIDFromString(sessionIdStr) assert.NoError(t, err) keypadSize = entities.KeypadDimension{AttrsPerKey: numbOfKeys, NumbOfKeys: numbOfKeys} userPasscode = setInterface[:passcodeLen] diff --git a/entities/customer.go b/entities/customer.go index 916f8b9..3015b74 100644 --- a/entities/customer.go +++ b/entities/customer.go @@ -10,7 +10,7 @@ import ( ) type Customer struct { - Id CustomerId + ID CustomerID NKodePolicy NKodePolicy Attributes CustomerAttributes } @@ -21,7 +21,7 @@ func NewCustomer(nkodePolicy NKodePolicy) (*Customer, error) { return nil, err } customer := Customer{ - Id: CustomerId(uuid.New()), + ID: CustomerID(uuid.New()), NKodePolicy: nkodePolicy, Attributes: *customerAttrs, } @@ -87,7 +87,7 @@ func (c *Customer) RenewKeys() ([]uint64, []uint64, error) { func (c *Customer) ToSqlcCreateCustomerParams() sqlc.CreateCustomerParams { return sqlc.CreateCustomerParams{ - ID: uuid.UUID(c.Id).String(), + ID: uuid.UUID(c.ID).String(), MaxNkodeLen: int64(c.NKodePolicy.MaxNkodeLen), MinNkodeLen: int64(c.NKodePolicy.MinNkodeLen), DistinctSets: int64(c.NKodePolicy.DistinctSets), diff --git a/entities/customer_test.go b/entities/customer_test.go index 89cf83f..7133714 100644 --- a/entities/customer_test.go +++ b/entities/customer_test.go @@ -21,7 +21,7 @@ func testCustomerValidKeyEntry(t *testing.T) { nkodePolicy := NewDefaultNKodePolicy() customer, err := NewCustomer(nkodePolicy) assert.NoError(t, err) - mockSvgInterface := make(SvgIdInterface, kp.TotalAttrs()) + mockSvgInterface := make(SvgIDInterface, kp.TotalAttrs()) userInterface, err := NewUserInterface(&kp, mockSvgInterface) assert.NoError(t, err) userEmail := "testing@example.com" @@ -45,7 +45,7 @@ func testCustomerIsValidNKode(t *testing.T) { nkodePolicy := NewDefaultNKodePolicy() customer, err := NewCustomer(nkodePolicy) assert.NoError(t, err) - mockSvgInterface := make(SvgIdInterface, kp.TotalAttrs()) + mockSvgInterface := make(SvgIDInterface, kp.TotalAttrs()) userInterface, err := NewUserInterface(&kp, mockSvgInterface) assert.NoError(t, err) userEmail := "testing123@example.com" diff --git a/entities/models.go b/entities/models.go index 7aea5d9..a27e5a2 100644 --- a/entities/models.go +++ b/entities/models.go @@ -9,30 +9,30 @@ import ( type KeySelection []int -type CustomerId uuid.UUID +type CustomerID uuid.UUID -func (c *CustomerId) String() string { +func (c *CustomerID) String() string { id := uuid.UUID(*c) return id.String() } -type SessionId uuid.UUID -type UserId uuid.UUID +type SessionID uuid.UUID +type UserID uuid.UUID -func (u *UserId) String() string { +func (u *UserID) String() string { id := uuid.UUID(*u) return id.String() } -func UserIdFromString(userId string) UserId { - id, err := uuid.Parse(userId) +func UserIDFromString(userID string) UserID { + id, err := uuid.Parse(userID) if err != nil { fmt.Errorf("unable to parse user id %+v", err) } - return UserId(id) + return UserID(id) } -func (s *SessionId) String() string { +func (s *SessionID) String() string { id := uuid.UUID(*s) return id.String() } @@ -49,15 +49,15 @@ func ParseEmail(email string) (UserEmail, error) { } type IdxInterface []int -type SvgIdInterface []int +type SvgIDInterface []int -func SessionIdFromString(sessionId string) (SessionId, error) { - id, err := uuid.Parse(sessionId) +func SessionIDFromString(sessionID string) (SessionID, error) { + id, err := uuid.Parse(sessionID) if err != nil { - return SessionId{}, err + return SessionID{}, err } - return SessionId(id), nil + return SessionID(id), nil } type EncipheredNKode struct { @@ -91,7 +91,7 @@ var SetColors = []RGBColor{ } type SignupResetInterface struct { - SessionId string `json:"session_id"` + SessionID string `json:"session_id"` UserIdxInterface IdxInterface `json:"user_interface"` SvgInterface []string `json:"svg_interface"` Colors []RGBColor `json:"colors"` diff --git a/entities/user.go b/entities/user.go index c701bc3..176225b 100644 --- a/entities/user.go +++ b/entities/user.go @@ -8,8 +8,8 @@ import ( ) type User struct { - Id UserId - CustomerId CustomerId + ID UserID + CustomerID CustomerID Email UserEmail EncipheredPasscode EncipheredNKode Kp KeypadDimension @@ -130,13 +130,13 @@ func NewUser(customer Customer, userEmail string, passcodeIdx []int, ui UserInte return nil, err } newUser := User{ - Id: UserId(uuid.New()), + ID: UserID(uuid.New()), Email: UserEmail(userEmail), EncipheredPasscode: *encipheredNKode, CipherKeys: *newKeys, Interface: ui, Kp: kp, - CustomerId: customer.Id, + CustomerID: customer.ID, } return &newUser, nil } diff --git a/entities/user_interface.go b/entities/user_interface.go index 1c0e473..23d377b 100644 --- a/entities/user_interface.go +++ b/entities/user_interface.go @@ -9,15 +9,15 @@ import ( type UserInterface struct { IdxInterface IdxInterface - SvgId SvgIdInterface + SvgID SvgIDInterface Kp *KeypadDimension } -func NewUserInterface(kp *KeypadDimension, svgId SvgIdInterface) (*UserInterface, error) { +func NewUserInterface(kp *KeypadDimension, svgID SvgIDInterface) (*UserInterface, error) { idxInterface := security.IdentityArray(kp.TotalAttrs()) userInterface := UserInterface{ IdxInterface: idxInterface, - SvgId: svgId, + SvgID: svgID, Kp: kp, } if err := userInterface.RandomShuffle(); err != nil { diff --git a/entities/user_signup_session.go b/entities/user_signup_session.go index fa9c9ff..42d0190 100644 --- a/entities/user_signup_session.go +++ b/entities/user_signup_session.go @@ -11,8 +11,8 @@ import ( ) type UserSignSession struct { - Id SessionId - CustomerId CustomerId + ID SessionID + CustomerID CustomerID LoginUserInterface UserInterface Kp KeypadDimension SetIdxInterface IdxInterface @@ -24,7 +24,7 @@ type UserSignSession struct { Colors []RGBColor } -func NewSignupResetSession(userEmail UserEmail, kp KeypadDimension, customerId CustomerId, svgInterface SvgIdInterface, reset bool) (*UserSignSession, error) { +func NewSignupResetSession(userEmail UserEmail, kp KeypadDimension, customerId CustomerID, svgInterface SvgIDInterface, reset bool) (*UserSignSession, error) { loginInterface, err := NewUserInterface(&kp, svgInterface) if err != nil { return nil, err @@ -34,8 +34,8 @@ func NewSignupResetSession(userEmail UserEmail, kp KeypadDimension, customerId C return nil, err } session := UserSignSession{ - Id: SessionId(uuid.New()), - CustomerId: customerId, + ID: SessionID(uuid.New()), + CustomerID: customerId, LoginUserInterface: *loginInterface, SetIdxInterface: signupInterface.IdxInterface, ConfirmIdxInterface: nil, diff --git a/entities/user_test.go b/entities/user_test.go index 2bba0c8..069a9cb 100644 --- a/entities/user_test.go +++ b/entities/user_test.go @@ -64,7 +64,7 @@ func TestUserInterface_RandomShuffle(t *testing.T) { AttrsPerKey: 10, NumbOfKeys: 8, } - mockSvgInterface := make(SvgIdInterface, kp.TotalAttrs()) + mockSvgInterface := make(SvgIDInterface, kp.TotalAttrs()) userInterface, err := NewUserInterface(&kp, mockSvgInterface) assert.NoError(t, err) userInterfaceCopy := make([]int, len(userInterface.IdxInterface)) @@ -87,7 +87,7 @@ func TestUserInterface_DisperseInterface(t *testing.T) { for idx := 0; idx < 10000; idx++ { kp := KeypadDimension{AttrsPerKey: 7, NumbOfKeys: 10} - mockSvgInterface := make(SvgIdInterface, kp.TotalAttrs()) + mockSvgInterface := make(SvgIDInterface, kp.TotalAttrs()) userInterface, err := NewUserInterface(&kp, mockSvgInterface) assert.NoError(t, err) preDispersion, err := userInterface.AttributeAdjacencyGraph() @@ -106,7 +106,7 @@ func TestUserInterface_DisperseInterface(t *testing.T) { func TestUserInterface_PartialInterfaceShuffle(t *testing.T) { kp := KeypadDimension{AttrsPerKey: 7, NumbOfKeys: 10} - mockSvgInterface := make(SvgIdInterface, kp.TotalAttrs()) + mockSvgInterface := make(SvgIDInterface, kp.TotalAttrs()) userInterface, err := NewUserInterface(&kp, mockSvgInterface) assert.NoError(t, err) preShuffle := userInterface.IdxInterface diff --git a/handler/handler.go b/handler/handler.go index a58015e..34d7680 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -19,9 +19,9 @@ type NkodeHandler struct { } const ( - malformedCustomerId = "malformed customer id" + malformedCustomerID = "malformed customer id" malformedUserEmail = "malformed user email" - malformedSessionId = "malformed session id" + malformedSessionID = "malformed session id" invalidKeypadDimensions = "invalid keypad dimensions" ) @@ -78,9 +78,9 @@ func (h *NkodeHandler) SignupHandler(c *gin.Context) { return } - customerId, err := uuid.Parse(postBody.CustomerId) + customerId, err := uuid.Parse(postBody.CustomerID) if err != nil { - c.String(400, malformedCustomerId) + c.String(400, malformedCustomerID) return } @@ -90,7 +90,7 @@ func (h *NkodeHandler) SignupHandler(c *gin.Context) { return } - resp, err := h.API.GenerateSignupResetInterface(userEmail, entities.CustomerId(customerId), kp, false) + resp, err := h.API.GenerateSignupResetInterface(userEmail, entities.CustomerID(customerId), kp, false) if err != nil { handleError(c, err) return @@ -106,18 +106,18 @@ func (h *NkodeHandler) SetNKodeHandler(c *gin.Context) { handleError(c, err) return } - customerId, err := uuid.Parse(postBody.CustomerId) + customerId, err := uuid.Parse(postBody.CustomerID) if err != nil { - c.String(400, malformedCustomerId) + c.String(400, malformedCustomerID) return } - sessionId, err := uuid.Parse(postBody.SessionId) + sessionId, err := uuid.Parse(postBody.SessionID) if err != nil { - c.String(400, malformedSessionId) + c.String(400, malformedSessionID) return } - confirmInterface, err := h.API.SetNKode(entities.CustomerId(customerId), entities.SessionId(sessionId), postBody.KeySelection) + confirmInterface, err := h.API.SetNKode(entities.CustomerID(customerId), entities.SessionID(sessionId), postBody.KeySelection) if err != nil { handleError(c, err) return @@ -133,17 +133,17 @@ func (h *NkodeHandler) ConfirmNKodeHandler(c *gin.Context) { handleError(c, err) return } - customerId, err := uuid.Parse(postBody.CustomerId) + customerId, err := uuid.Parse(postBody.CustomerID) if err != nil { - c.String(400, malformedCustomerId) + c.String(400, malformedCustomerID) return } - sessionId, err := uuid.Parse(postBody.SessionId) + sessionId, err := uuid.Parse(postBody.SessionID) if err != nil { - c.String(400, malformedSessionId) + c.String(400, malformedSessionID) return } - if err := h.API.ConfirmNKode(entities.CustomerId(customerId), entities.SessionId(sessionId), postBody.KeySelection); err != nil { + if err := h.API.ConfirmNKode(entities.CustomerID(customerId), entities.SessionID(sessionId), postBody.KeySelection); err != nil { handleError(c, err) return } @@ -158,9 +158,9 @@ func (h *NkodeHandler) GetLoginInterfaceHandler(c *gin.Context) { return } - customerId, err := uuid.Parse(loginInterfacePost.CustomerId) + customerId, err := uuid.Parse(loginInterfacePost.CustomerID) if err != nil { - c.String(400, malformedCustomerId) + c.String(400, malformedCustomerID) return } @@ -169,7 +169,7 @@ func (h *NkodeHandler) GetLoginInterfaceHandler(c *gin.Context) { c.String(400, malformedUserEmail) return } - postBody, err := h.API.GetLoginInterface(userEmail, entities.CustomerId(customerId)) + postBody, err := h.API.GetLoginInterface(userEmail, entities.CustomerID(customerId)) if err != nil { handleError(c, err) return @@ -185,9 +185,9 @@ func (h *NkodeHandler) LoginHandler(c *gin.Context) { handleError(c, err) return } - customerId, err := uuid.Parse(loginPost.CustomerId) + customerId, err := uuid.Parse(loginPost.CustomerID) if err != nil { - c.String(400, malformedCustomerId) + c.String(400, malformedCustomerID) return } @@ -196,7 +196,7 @@ func (h *NkodeHandler) LoginHandler(c *gin.Context) { c.String(400, malformedUserEmail) return } - jwtToken, err := h.API.Login(entities.CustomerId(customerId), userEmail, loginPost.KeySelection) + jwtToken, err := h.API.Login(entities.CustomerID(customerId), userEmail, loginPost.KeySelection) if err != nil { handleError(c, err) return @@ -213,13 +213,13 @@ func (h *NkodeHandler) RenewAttributesHandler(c *gin.Context) { return } - customerId, err := uuid.Parse(renewAttributesPost.CustomerId) + customerId, err := uuid.Parse(renewAttributesPost.CustomerID) if err != nil { - c.String(400, malformedCustomerId) + c.String(400, malformedCustomerID) return } - if err = h.API.RenewAttributes(entities.CustomerId(customerId)); err != nil { + if err = h.API.RenewAttributes(entities.CustomerID(customerId)); err != nil { handleError(c, err) return } @@ -251,7 +251,7 @@ func (h *NkodeHandler) RefreshTokenHandler(c *gin.Context) { } customerId, err := uuid.Parse(refreshClaims.Issuer) if err != nil { - c.String(400, malformedCustomerId) + c.String(400, malformedCustomerID) return } userEmail, err := entities.ParseEmail(refreshClaims.Subject) @@ -259,7 +259,7 @@ func (h *NkodeHandler) RefreshTokenHandler(c *gin.Context) { c.String(400, malformedUserEmail) return } - accessToken, err := h.API.RefreshToken(userEmail, entities.CustomerId(customerId), refreshToken) + accessToken, err := h.API.RefreshToken(userEmail, entities.CustomerID(customerId), refreshToken) if err != nil { handleError(c, err) return @@ -274,9 +274,9 @@ func (h *NkodeHandler) ForgotNKodeHandler(c *gin.Context) { handleError(c, err) return } - customerId, err := uuid.Parse(forgotNKodePost.CustomerId) + customerId, err := uuid.Parse(forgotNKodePost.CustomerID) if err != nil { - c.String(400, malformedCustomerId) + c.String(400, malformedCustomerID) return } userEmail, err := entities.ParseEmail(forgotNKodePost.UserEmail) @@ -285,7 +285,7 @@ func (h *NkodeHandler) ForgotNKodeHandler(c *gin.Context) { return } - if err := h.API.ForgotNKode(userEmail, entities.CustomerId(customerId)); err != nil { + if err := h.API.ForgotNKode(userEmail, entities.CustomerID(customerId)); err != nil { handleError(c, err) return } @@ -306,7 +306,7 @@ func (h *NkodeHandler) SignoutHandler(c *gin.Context) { } customerId, err := uuid.Parse(accessClaims.Issuer) if err != nil { - c.String(400, malformedCustomerId) + c.String(400, malformedCustomerID) return } userEmail, err := entities.ParseEmail(accessClaims.Subject) @@ -314,7 +314,7 @@ func (h *NkodeHandler) SignoutHandler(c *gin.Context) { c.String(400, malformedUserEmail) return } - if err = h.API.Signout(userEmail, entities.CustomerId(customerId)); err != nil { + if err = h.API.Signout(userEmail, entities.CustomerID(customerId)); err != nil { handleError(c, err) return } @@ -339,9 +339,9 @@ func (h *NkodeHandler) ResetHandler(c *gin.Context) { handleError(c, err) return } - customerId, err := uuid.Parse(postBody.CustomerId) + customerId, err := uuid.Parse(postBody.CustomerID) if err != nil { - c.String(400, malformedCustomerId) + c.String(400, malformedCustomerID) return } userEmail, err := entities.ParseEmail(postBody.UserEmail) @@ -350,7 +350,7 @@ func (h *NkodeHandler) ResetHandler(c *gin.Context) { return } if postBody.UserEmail != resetClaims.Subject || - postBody.CustomerId != resetClaims.Issuer { + postBody.CustomerID != resetClaims.Issuer { c.String(403, "forbidden") return } @@ -364,7 +364,7 @@ func (h *NkodeHandler) ResetHandler(c *gin.Context) { c.String(400, invalidKeypadDimensions) return } - resp, err := h.API.GenerateSignupResetInterface(userEmail, entities.CustomerId(customerId), kp, true) + resp, err := h.API.GenerateSignupResetInterface(userEmail, entities.CustomerID(customerId), kp, true) if err != nil { handleError(c, err) return diff --git a/handler/handler_test.go b/handler/handler_test.go index 4080926..f50ff9b 100644 --- a/handler/handler_test.go +++ b/handler/handler_test.go @@ -49,7 +49,7 @@ func TestNKodeAPI(t *testing.T) { assert.NoError(t, err) // *** Set nKode *** - confirmInterface, status, err := tr.SetNKode(customerID, setKeySelection, resp.SessionId) + confirmInterface, status, err := tr.SetNKode(customerID, setKeySelection, resp.SessionID) assert.NoError(t, err) assert.Equal(t, 200, status) @@ -57,7 +57,7 @@ func TestNKodeAPI(t *testing.T) { assert.NoError(t, err) // *** Confirm nKode *** - status, err = tr.ConfirmNKode(customerID, confirmKeySelection, resp.SessionId) + status, err = tr.ConfirmNKode(customerID, confirmKeySelection, resp.SessionID) assert.NoError(t, err) assert.Equal(t, 200, status) @@ -101,16 +101,16 @@ func TestNKodeAPI(t *testing.T) { resetResp, status, err := tr.Reset(customerID, attrPerKey, numKeys, userEmail, nkodeResetJwt) assert.NoError(t, err) assert.Equal(t, 200, status) - assert.NotEmpty(t, resetResp.SessionId) + 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) + 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) + status, err = tr.ConfirmNKode(customerID, confirmKeySelection, resetResp.SessionID) assert.NoError(t, err) assert.Equal(t, 200, status) loginInterface, status, err = tr.GetLoginInterface(userEmail, customerID) @@ -211,9 +211,9 @@ func (r *TestRouter) SetNKode( sessionID string, ) ([]int, int, error) { data := models.SetNKodePost{ - CustomerId: customerID, + CustomerID: customerID, KeySelection: selection, - SessionId: sessionID, + SessionID: sessionID, } body, err := json.Marshal(data) @@ -240,9 +240,9 @@ func (r *TestRouter) ConfirmNKode( sessionID string, ) (int, error) { data := models.ConfirmNKodePost{ - CustomerId: customerID, + CustomerID: customerID, KeySelection: selection, - SessionId: sessionID, + SessionID: sessionID, } body, err := json.Marshal(data) if err != nil { @@ -282,7 +282,7 @@ func (r *TestRouter) Login( selection []int, ) (security.AuthenticationTokens, int, error) { data := models.LoginPost{ - CustomerId: customerID, + CustomerID: customerID, UserEmail: userEmail, KeySelection: selection, } @@ -305,7 +305,7 @@ func (r *TestRouter) RenewAttributes( customerID string, ) (int, error) { data := models.RenewAttributesPost{ - CustomerId: customerID, + CustomerID: customerID, } body, err := json.Marshal(data) if err != nil { @@ -323,7 +323,7 @@ func (r *TestRouter) ForgotNKode( userEmail string, ) (int, error) { data := models.ForgotNKodePost{ - CustomerId: customerID, + CustomerID: customerID, UserEmail: userEmail, } body, err := json.Marshal(data) diff --git a/memcache/forgot_nkode.go b/memcache/forgot_nkode.go index fa15878..82e4744 100644 --- a/memcache/forgot_nkode.go +++ b/memcache/forgot_nkode.go @@ -20,19 +20,19 @@ func NewForgotNKodeCache() ForgotNKodeCache { return ForgotNKodeCache{forgotCache} } -func (f *ForgotNKodeCache) Set(userEmail entities.UserEmail, customerId entities.CustomerId) { +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 { +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) { +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 { +func key(email entities.UserEmail, id entities.CustomerID) string { return string(email) + id.String() } diff --git a/models/models.go b/models/models.go index 1c14191..b9ddca5 100644 --- a/models/models.go +++ b/models/models.go @@ -16,44 +16,44 @@ type RefreshTokenResp struct { } type SignupPostBody struct { - CustomerId string `form:"customer_id"` + 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"` + CustomerID string `json:"customer_id" binding:"required"` KeySelection []int `json:"key_selection" binding:"required"` - SessionId string `json:"session_id" binding:"required"` + SessionID string `json:"session_id" binding:"required"` } type ConfirmNKodePost struct { - CustomerId string `json:"customer_id" binding:"required"` + CustomerID string `json:"customer_id" binding:"required"` KeySelection []int `json:"key_selection" binding:"required"` - SessionId string `json:"session_id" 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"` + CustomerID string `form:"customer_id" binding:"required"` } type LoginPost struct { - CustomerId string `form:"customer_id" binding:"required"` + 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"` + CustomerID string `form:"customer_id" binding:"required"` } type ForgotNKodePost struct { UserEmail string `form:"email" binding:"required"` - CustomerId string `form:"customer_id" binding:"required"` + CustomerID string `form:"customer_id" binding:"required"` } type CreateNewCustomerResp struct { - CustomerId string `form:"customer_id" binding:"required"` + CustomerID string `form:"customer_id" binding:"required"` } diff --git a/repository/customer_user_repository.go b/repository/customer_user_repository.go index 984f8db..f75e62b 100644 --- a/repository/customer_user_repository.go +++ b/repository/customer_user_repository.go @@ -5,16 +5,16 @@ import ( ) type CustomerUserRepository interface { - GetCustomer(entities.CustomerId) (*entities.Customer, error) - GetUser(entities.UserEmail, entities.CustomerId) (*entities.User, error) + GetCustomer(entities.CustomerID) (*entities.Customer, error) + GetUser(entities.UserEmail, entities.CustomerID) (*entities.User, error) CreateCustomer(entities.Customer) error WriteNewUser(entities.User) error UpdateUserNKode(entities.User) error - UpdateUserInterface(entities.UserId, entities.UserInterface) error - UpdateUserRefreshToken(entities.UserId, string) error - Renew(entities.CustomerId) error + UpdateUserInterface(entities.UserID, entities.UserInterface) error + UpdateUserRefreshToken(entities.UserID, string) error + Renew(entities.CustomerID) error RefreshUserPasscode(entities.User, []int, entities.CustomerAttributes) error RandomSvgInterface(entities.KeypadDimension) ([]string, error) - RandomSvgIdxInterface(entities.KeypadDimension) (entities.SvgIdInterface, error) - GetSvgStringInterface(entities.SvgIdInterface) ([]string, error) + RandomSvgIdxInterface(entities.KeypadDimension) (entities.SvgIDInterface, error) + GetSvgStringInterface(entities.SvgIDInterface) ([]string, error) } diff --git a/repository/sqlite_nkode_repo.go b/repository/sqlite_nkode_repo.go index 6fb320b..58cf52d 100644 --- a/repository/sqlite_nkode_repo.go +++ b/repository/sqlite_nkode_repo.go @@ -70,11 +70,11 @@ func (d *SqliteNKodeRepo) WriteNewUser(u entities.User) error { } // Map entities.User to CreateUserParams params := sqlc.CreateUserParams{ - ID: uuid.UUID(u.Id).String(), + ID: uuid.UUID(u.ID).String(), Email: string(u.Email), Renew: int64(renew), RefreshToken: sql.NullString{String: u.RefreshToken, Valid: u.RefreshToken != ""}, - CustomerID: uuid.UUID(u.CustomerId).String(), + CustomerID: uuid.UUID(u.CustomerID).String(), Code: u.EncipheredPasscode.Code, Mask: u.EncipheredPasscode.Mask, AttributesPerKey: int64(u.Kp.AttrsPerKey), @@ -86,7 +86,7 @@ func (d *SqliteNKodeRepo) WriteNewUser(u entities.User) error { Salt: u.CipherKeys.Salt, MaxNkodeLen: int64(u.CipherKeys.MaxNKodeLen), IdxInterface: security.IntArrToByteArr(u.Interface.IdxInterface), - SvgIDInterface: security.IntArrToByteArr(u.Interface.SvgId), + SvgIDInterface: security.IntArrToByteArr(u.Interface.SvgID), CreatedAt: sql.NullString{String: utils.TimeStamp(), Valid: true}, } return d.Queue.EnqueueWriteTx(queryFunc, params) @@ -109,7 +109,7 @@ func (d *SqliteNKodeRepo) UpdateUserNKode(u entities.User) error { Email: string(u.Email), Renew: int64(renew), RefreshToken: sql.NullString{String: u.RefreshToken, Valid: u.RefreshToken != ""}, - CustomerID: uuid.UUID(u.CustomerId).String(), + CustomerID: uuid.UUID(u.CustomerID).String(), Code: u.EncipheredPasscode.Code, Mask: u.EncipheredPasscode.Mask, AttributesPerKey: int64(u.Kp.AttrsPerKey), @@ -121,12 +121,12 @@ func (d *SqliteNKodeRepo) UpdateUserNKode(u entities.User) error { Salt: u.CipherKeys.Salt, MaxNkodeLen: int64(u.CipherKeys.MaxNKodeLen), IdxInterface: security.IntArrToByteArr(u.Interface.IdxInterface), - SvgIDInterface: security.IntArrToByteArr(u.Interface.SvgId), + SvgIDInterface: security.IntArrToByteArr(u.Interface.SvgID), } return d.Queue.EnqueueWriteTx(queryFunc, params) } -func (d *SqliteNKodeRepo) UpdateUserInterface(id entities.UserId, ui entities.UserInterface) error { +func (d *SqliteNKodeRepo) UpdateUserInterface(id entities.UserID, ui entities.UserInterface) error { queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error { params, ok := args.(sqlc.UpdateUserInterfaceParams) if !ok { @@ -143,7 +143,7 @@ func (d *SqliteNKodeRepo) UpdateUserInterface(id entities.UserId, ui entities.Us return d.Queue.EnqueueWriteTx(queryFunc, params) } -func (d *SqliteNKodeRepo) UpdateUserRefreshToken(id entities.UserId, refreshToken string) error { +func (d *SqliteNKodeRepo) UpdateUserRefreshToken(id entities.UserID, refreshToken string) error { queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error { params, ok := args.(sqlc.UpdateUserRefreshTokenParams) if !ok { @@ -172,7 +172,7 @@ func (d *SqliteNKodeRepo) RenewCustomer(renewParams sqlc.RenewCustomerParams) er return d.Queue.EnqueueWriteTx(queryFunc, renewParams) } -func (d *SqliteNKodeRepo) Renew(id entities.CustomerId) error { +func (d *SqliteNKodeRepo) Renew(id entities.CustomerID) error { setXor, attrXor, err := d.renewCustomer(id) if err != nil { return err @@ -192,8 +192,8 @@ func (d *SqliteNKodeRepo) Renew(id entities.CustomerId) error { for _, row := range userRenewRows { user := entities.User{ - Id: entities.UserIdFromString(row.ID), - CustomerId: entities.CustomerId{}, + ID: entities.UserIDFromString(row.ID), + CustomerID: entities.CustomerID{}, Email: "", EncipheredPasscode: entities.EncipheredNKode{}, Kp: entities.KeypadDimension{ @@ -215,7 +215,7 @@ func (d *SqliteNKodeRepo) Renew(id entities.CustomerId) error { AlphaKey: security.Uint64ArrToByteArr(user.CipherKeys.AlphaKey), SetKey: security.Uint64ArrToByteArr(user.CipherKeys.SetKey), Renew: 1, - ID: uuid.UUID(user.Id).String(), + ID: uuid.UUID(user.ID).String(), } if err = d.Queue.EnqueueWriteTx(queryFunc, params); err != nil { return err @@ -224,7 +224,7 @@ func (d *SqliteNKodeRepo) Renew(id entities.CustomerId) error { return nil } -func (d *SqliteNKodeRepo) renewCustomer(id entities.CustomerId) ([]uint64, []uint64, error) { +func (d *SqliteNKodeRepo) renewCustomer(id entities.CustomerID) ([]uint64, []uint64, error) { customer, err := d.GetCustomer(id) if err != nil { return nil, nil, err @@ -244,7 +244,7 @@ func (d *SqliteNKodeRepo) renewCustomer(id entities.CustomerId) ([]uint64, []uin params := sqlc.RenewCustomerParams{ AttributeValues: security.Uint64ArrToByteArr(customer.Attributes.AttrVals), SetValues: security.Uint64ArrToByteArr(customer.Attributes.SetVals), - ID: uuid.UUID(customer.Id).String(), + ID: uuid.UUID(customer.ID).String(), } if err = d.Queue.EnqueueWriteTx(queryFunc, params); err != nil { @@ -273,7 +273,7 @@ func (d *SqliteNKodeRepo) RefreshUserPasscode(user entities.User, passcodeIdx [] PassKey: security.Uint64ArrToByteArr(user.CipherKeys.PassKey), MaskKey: security.Uint64ArrToByteArr(user.CipherKeys.MaskKey), Salt: user.CipherKeys.Salt, - ID: uuid.UUID(user.Id).String(), + ID: uuid.UUID(user.ID).String(), } return d.Queue.EnqueueWriteTx(queryFunc, params) } @@ -289,14 +289,14 @@ func (d *SqliteNKodeRepo) AddSvg(svg string) error { return d.Queue.EnqueueWriteTx(queryFunc, svg) } -func (d *SqliteNKodeRepo) GetCustomer(id entities.CustomerId) (*entities.Customer, error) { +func (d *SqliteNKodeRepo) GetCustomer(id entities.CustomerID) (*entities.Customer, error) { customer, err := d.Queue.Queries.GetCustomer(d.ctx, uuid.UUID(id).String()) if err != nil { return nil, err } return &entities.Customer{ - Id: id, + ID: id, NKodePolicy: entities.NKodePolicy{ MaxNkodeLen: int(customer.MaxNkodeLen), MinNkodeLen: int(customer.MinNkodeLen), @@ -309,10 +309,10 @@ func (d *SqliteNKodeRepo) GetCustomer(id entities.CustomerId) (*entities.Custome }, nil } -func (d *SqliteNKodeRepo) GetUser(email entities.UserEmail, customerId entities.CustomerId) (*entities.User, error) { +func (d *SqliteNKodeRepo) GetUser(email entities.UserEmail, customerID entities.CustomerID) (*entities.User, error) { userRow, err := d.Queue.Queries.GetUser(d.ctx, sqlc.GetUserParams{ Email: string(email), - CustomerID: uuid.UUID(customerId).String(), + CustomerID: uuid.UUID(customerID).String(), }) if err != nil { if errors.Is(err, sql.ErrNoRows) { @@ -331,8 +331,8 @@ func (d *SqliteNKodeRepo) GetUser(email entities.UserEmail, customerId entities. renew = true } user := entities.User{ - Id: entities.UserIdFromString(userRow.ID), - CustomerId: customerId, + ID: entities.UserIDFromString(userRow.ID), + CustomerID: customerID, Email: email, EncipheredPasscode: entities.EncipheredNKode{ Code: userRow.Code, @@ -350,7 +350,7 @@ func (d *SqliteNKodeRepo) GetUser(email entities.UserEmail, customerId entities. }, Interface: entities.UserInterface{ IdxInterface: security.ByteArrToIntArr(userRow.IdxInterface), - SvgId: security.ByteArrToIntArr(userRow.SvgIDInterface), + SvgID: security.ByteArrToIntArr(userRow.SvgIDInterface), Kp: &kp, }, Renew: renew, @@ -360,24 +360,24 @@ func (d *SqliteNKodeRepo) GetUser(email entities.UserEmail, customerId entities. } func (d *SqliteNKodeRepo) RandomSvgInterface(kp entities.KeypadDimension) ([]string, error) { - ids, err := d.getRandomIds(kp.TotalAttrs()) + ids, err := d.getRandomIDs(kp.TotalAttrs()) if err != nil { return nil, err } - return d.getSvgsById(ids) + return d.getSvgsByID(ids) } -func (d *SqliteNKodeRepo) RandomSvgIdxInterface(kp entities.KeypadDimension) (entities.SvgIdInterface, error) { - return d.getRandomIds(kp.TotalAttrs()) +func (d *SqliteNKodeRepo) RandomSvgIdxInterface(kp entities.KeypadDimension) (entities.SvgIDInterface, error) { + return d.getRandomIDs(kp.TotalAttrs()) } -func (d *SqliteNKodeRepo) GetSvgStringInterface(idxs entities.SvgIdInterface) ([]string, error) { - return d.getSvgsById(idxs) +func (d *SqliteNKodeRepo) GetSvgStringInterface(idxs entities.SvgIDInterface) ([]string, error) { + return d.getSvgsByID(idxs) } // Is this even useful? -func (d *SqliteNKodeRepo) AddUserPermission(userEmail entities.UserEmail, customerId entities.CustomerId, permission entities.UserPermission) error { - user, err := d.GetUser(userEmail, customerId) +func (d *SqliteNKodeRepo) AddUserPermission(userEmail entities.UserEmail, customerID entities.CustomerID, permission entities.UserPermission) error { + user, err := d.GetUser(userEmail, customerID) if err != nil { return err } @@ -389,16 +389,16 @@ func (d *SqliteNKodeRepo) AddUserPermission(userEmail entities.UserEmail, custom return q.AddUserPermission(ctx, params) } params := sqlc.AddUserPermissionParams{ - UserID: user.Id.String(), + UserID: user.ID.String(), Permission: permission.String(), } return d.Queue.EnqueueWriteTx(queryFunc, params) } -func (d *SqliteNKodeRepo) getSvgsById(ids []int) ([]string, error) { +func (d *SqliteNKodeRepo) getSvgsByID(ids []int) ([]string, error) { svgs := make([]string, len(ids)) for idx, id := range ids { - svg, err := d.Queue.Queries.GetSvgId(d.ctx, int64(id)) + svg, err := d.Queue.Queries.GetSvgID(d.ctx, int64(id)) if err != nil { return nil, err } @@ -407,7 +407,7 @@ func (d *SqliteNKodeRepo) getSvgsById(ids []int) ([]string, error) { return svgs, nil } -func (d *SqliteNKodeRepo) getRandomIds(count int) ([]int, error) { +func (d *SqliteNKodeRepo) getRandomIDs(count int) ([]int, error) { totalRows, err := d.Queue.Queries.GetSvgCount(d.ctx) if err != nil { log.Print(err) diff --git a/repository/sqlite_nkode_repo_test.go b/repository/sqlite_nkode_repo_test.go index a3d8eef..063aac0 100644 --- a/repository/sqlite_nkode_repo_test.go +++ b/repository/sqlite_nkode_repo_test.go @@ -28,24 +28,24 @@ func testSignupLoginRenew(t *testing.T, db CustomerUserRepository) { assert.NoError(t, err) err = db.CreateCustomer(*customerOrig) assert.NoError(t, err) - customer, err := db.GetCustomer(customerOrig.Id) + customer, err := db.GetCustomer(customerOrig.ID) assert.NoError(t, err) assert.Equal(t, customerOrig, customer) username := "test_user@example.com" kp := entities.KeypadDefault passcodeIdx := []int{0, 1, 2, 3} - mockSvgInterface := make(entities.SvgIdInterface, kp.TotalAttrs()) + mockSvgInterface := make(entities.SvgIDInterface, kp.TotalAttrs()) ui, err := entities.NewUserInterface(&kp, mockSvgInterface) assert.NoError(t, err) userOrig, err := entities.NewUser(*customer, username, passcodeIdx, *ui, kp) assert.NoError(t, err) err = db.WriteNewUser(*userOrig) assert.NoError(t, err) - user, err := db.GetUser(entities.UserEmail(username), customer.Id) + user, err := db.GetUser(entities.UserEmail(username), customer.ID) assert.NoError(t, err) assert.Equal(t, userOrig, user) - err = db.Renew(customer.Id) + err = db.Renew(customer.ID) assert.NoError(t, err) } diff --git a/sqlc/query.sql.go b/sqlc/query.sql.go index 9af1949..6a4ca76 100644 --- a/sqlc/query.sql.go +++ b/sqlc/query.sql.go @@ -489,14 +489,14 @@ func (q *Queries) GetSvgCount(ctx context.Context) (int64, error) { return count, err } -const getSvgId = `-- name: GetSvgId :one +const getSvgID = `-- name: GetSvgID :one SELECT svg FROM svg_icon WHERE id = ? ` -func (q *Queries) GetSvgId(ctx context.Context, id int64) (string, error) { - row := q.db.QueryRowContext(ctx, getSvgId, id) +func (q *Queries) GetSvgID(ctx context.Context, id int64) (string, error) { + row := q.db.QueryRowContext(ctx, getSvgID, id) var svg string err := row.Scan(&svg) return svg, err diff --git a/sqlite/query.sql b/sqlite/query.sql index 5eeb82c..ec99f6c 100644 --- a/sqlite/query.sql +++ b/sqlite/query.sql @@ -130,7 +130,7 @@ SELECT FROM user WHERE user.email = ? AND user.customer_id = ?; --- name: GetSvgId :one +-- name: GetSvgID :one SELECT svg FROM svg_icon WHERE id = ?; -- 2.49.1 From 9bfc591fcc89fee4f45191c840db87668dfa94e0 Mon Sep 17 00:00:00 2001 From: Donovan Date: Thu, 13 Feb 2025 13:00:21 -0600 Subject: [PATCH 4/5] add revoke client approval --- go.mod | 2 +- go.sum | 6 ++++++ sqlc/query.sql.go | 15 +++++++++++++++ sqlite/query.sql | 3 +++ 4 files changed, 25 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index f3412a9..3da1b80 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/aws/aws-sdk-go-v2 v1.33.0 github.com/aws/aws-sdk-go-v2/config v1.29.1 github.com/aws/aws-sdk-go-v2/service/ses v1.29.6 + github.com/gin-gonic/gin v1.10.0 github.com/golang-jwt/jwt/v5 v5.2.1 github.com/google/uuid v1.6.0 github.com/mattn/go-sqlite3 v1.14.24 @@ -34,7 +35,6 @@ require ( 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 diff --git a/go.sum b/go.sum index 2012b38..87bb657 100644 --- a/go.sum +++ b/go.sum @@ -45,6 +45,8 @@ 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/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= 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= @@ -55,6 +57,8 @@ 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/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 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= @@ -115,6 +119,8 @@ 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= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 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= diff --git a/sqlc/query.sql.go b/sqlc/query.sql.go index 6a4ca76..f6ca203 100644 --- a/sqlc/query.sql.go +++ b/sqlc/query.sql.go @@ -783,6 +783,21 @@ func (q *Queries) RenewUser(ctx context.Context, arg RenewUserParams) error { return err } +const revokeClientApproval = `-- name: RevokeClientApproval :exec +DELETE FROM client_approvals +WHERE user_id = ? AND client_id = ? +` + +type RevokeClientApprovalParams struct { + UserID string + ClientID string +} + +func (q *Queries) RevokeClientApproval(ctx context.Context, arg RevokeClientApprovalParams) error { + _, err := q.db.ExecContext(ctx, revokeClientApproval, arg.UserID, arg.ClientID) + return err +} + const updateUser = `-- name: UpdateUser :exec UPDATE user SET renew = ? diff --git a/sqlite/query.sql b/sqlite/query.sql index ec99f6c..889120d 100644 --- a/sqlite/query.sql +++ b/sqlite/query.sql @@ -226,3 +226,6 @@ WHERE id = ?; INSERT INTO sessions (id, user_id, expires_at) VALUES (?, ?, ?); +-- name: RevokeClientApproval :exec +DELETE FROM client_approvals +WHERE user_id = ? AND client_id = ?; -- 2.49.1 From 37862e747f26d781446833a0528b2feef912225c Mon Sep 17 00:00:00 2001 From: Donovan Date: Fri, 14 Feb 2025 10:59:51 -0600 Subject: [PATCH 5/5] implement delete session --- sqlc/query.sql.go | 10 ++++++++++ sqlite/query.sql | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/sqlc/query.sql.go b/sqlc/query.sql.go index f6ca203..fc118fe 100644 --- a/sqlc/query.sql.go +++ b/sqlc/query.sql.go @@ -342,6 +342,16 @@ func (q *Queries) DeleteRedirectURI(ctx context.Context, arg DeleteRedirectURIPa return err } +const deleteSession = `-- name: DeleteSession :exec +DELETE FROM sessions +WHERE id = ? +` + +func (q *Queries) DeleteSession(ctx context.Context, id string) error { + _, err := q.db.ExecContext(ctx, deleteSession, id) + return err +} + const getAuthorizationCode = `-- name: GetAuthorizationCode :one SELECT id, code, code_challenge, code_challenge_method, user_id, client_id, scope, redirect_uri, created_at, expires_at, used_at FROM authorization_codes diff --git a/sqlite/query.sql b/sqlite/query.sql index 889120d..a808f51 100644 --- a/sqlite/query.sql +++ b/sqlite/query.sql @@ -226,6 +226,10 @@ WHERE id = ?; INSERT INTO sessions (id, user_id, expires_at) VALUES (?, ?, ?); +-- name: DeleteSession :exec +DELETE FROM sessions +WHERE id = ?; + -- name: RevokeClientApproval :exec DELETE FROM client_approvals WHERE user_id = ? AND client_id = ?; -- 2.49.1