Skip to content

Commit

Permalink
feat: single-user mode WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
rolznz committed Jan 19, 2024
1 parent 3f50a60 commit 778c249
Show file tree
Hide file tree
Showing 30 changed files with 121 additions and 638 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Connect applications like [Damus](https://damus.io/) or [Amethyst](https://linkt

The application has no runtime dependencies. (simple Go executable).

As data storage SQLite or PostgreSQL (recommended) can be used.
As data storage SQLite is used.

$ cp .env.example .env
# edit the config for your needs
Expand Down Expand Up @@ -78,7 +78,7 @@ _If you get a blank screen the first load, close the window and start the app ag
- `RELAY`: default: "wss://relay.getalby.com/v1"
- `PUBLIC_RELAY`: optional relay URL to be used in connection strings if `RELAY` is an internal URL
- `COOKIE_SECRET`: a randomly generated secret string.
- `DATABASE_URI`: a postgres connection string or sqlite filename. Default: nostr-wallet-connect.db (sqlite)
- `DATABASE_URI`: a sqlite filename. Default: nwc.db (sqlite)
- `PORT`: the port on which the app should listen on (default: 8080)
- `LN_BACKEND_TYPE`: LND or BREEZ

Expand Down
37 changes: 15 additions & 22 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import (

// TODO: these methods should be moved to a separate object, not in Service

// TODO: remove user parameter in single-user fork
func (svc *Service) CreateApp(createAppRequest *api.CreateAppRequest) (*api.CreateAppResponse, error) {
name := createAppRequest.Name
var pairingPublicKey string
Expand All @@ -35,15 +34,6 @@ func (svc *Service) CreateApp(createAppRequest *api.CreateAppRequest) (*api.Crea
}
}

// make sure there is not already a pubkey is already associated with an app
// as apps are currently indexed by pubkey
// TODO: shouldn't this be a database constraint?
existingApp := App{}
findResult := svc.db.Where("user_id = ? AND nostr_pubkey = ?", user.ID, pairingPublicKey).First(&existingApp)
if findResult.RowsAffected > 0 {
return nil, errors.New("Pubkey already in use: " + existingApp.NostrPubkey)
}

app := App{Name: name, NostrPubkey: pairingPublicKey}
maxAmount := createAppRequest.MaxAmount
budgetRenewal := createAppRequest.BudgetRenewal
Expand All @@ -63,7 +53,7 @@ func (svc *Service) CreateApp(createAppRequest *api.CreateAppRequest) (*api.Crea
}

err := svc.db.Transaction(func(tx *gorm.DB) error {
err := tx.Model(&user).Association("Apps").Append(&app)
err := tx.Save(&app).Error
if err != nil {
return err
}
Expand Down Expand Up @@ -116,18 +106,18 @@ func (svc *Service) CreateApp(createAppRequest *api.CreateAppRequest) (*api.Crea
query := returnToUrl.Query()
query.Add("relay", publicRelayUrl)
query.Add("pubkey", svc.cfg.IdentityPubkey)
if user.LightningAddress != "" {
query.Add("lud16", user.LightningAddress)
}
// if user.LightningAddress != "" {
// query.Add("lud16", user.LightningAddress)
// }
returnToUrl.RawQuery = query.Encode()
responseBody.ReturnTo = returnToUrl.String()
}
}

var lud16 string
if user.LightningAddress != "" {
lud16 = fmt.Sprintf("&lud16=%s", user.LightningAddress)
}
// if user.LightningAddress != "" {
// lud16 = fmt.Sprintf("&lud16=%s", user.LightningAddress)
// }
responseBody.PairingUri = fmt.Sprintf("nostr+walletconnect://%s?relay=%s&secret=%s%s", svc.cfg.IdentityPubkey, publicRelayUrl, pairingSecretKey, lud16)
return responseBody, nil
}
Expand Down Expand Up @@ -186,9 +176,12 @@ func (svc *Service) GetApp(userApp *App) *api.App {

}

func (svc *Service) ListApps(userApps *[]App) ([]api.App, error) {
apps := []api.App{}
for _, userApp := range *userApps {
func (svc *Service) ListApps() ([]api.App, error) {
apps := []App{}
svc.db.Find(&apps)

apiApps := []api.App{}
for _, userApp := range apps {
apiApp := api.App{
// ID: app.ID,
Name: userApp.Name,
Expand All @@ -207,9 +200,9 @@ func (svc *Service) ListApps(userApps *[]App) ([]api.App, error) {
if result.RowsAffected > 0 {
apiApp.LastEventAt = &lastEvent.CreatedAt
}
apps = append(apps, apiApp)
apiApps = append(apiApps, apiApp)
}
return apps, nil
return apiApps, nil
}

func (svc *Service) GetInfo() *api.InfoResponse {
Expand Down
14 changes: 1 addition & 13 deletions breez.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,7 @@ func (BreezListener) OnEvent(e breez_sdk.BreezEvent) {
log.Printf("received event %#v", e)
}

func NewBreezService(nwcSvc *Service, mnemonic, apiKey, inviteCode, workDir string) (result LNClient, err error) {
// FIXME: split single and multi user app
//add default user to db
user := &User{}
err = nwcSvc.db.FirstOrInit(user, User{AlbyIdentifier: "breez"}).Error
if err != nil {
return nil, err
}
err = nwcSvc.db.Save(user).Error
if err != nil {
return nil, err
}

func NewBreezService(mnemonic, apiKey, inviteCode, workDir string) (result LNClient, err error) {
//create dir if not exists
newpath := filepath.Join(".", workDir)
err = os.MkdirAll(newpath, os.ModePerm)
Expand Down
117 changes: 0 additions & 117 deletions breez/breez.go

This file was deleted.

1 change: 0 additions & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ type Config struct {
// These config can be set either by .env or the database config table.
// database config always takes preference.
db.Config
NostrSecretKey string `envconfig:"NOSTR_PRIVKEY"`
CookieSecret string `envconfig:"COOKIE_SECRET"`
CookieDomain string `envconfig:"COOKIE_DOMAIN"`
ClientPubkey string `envconfig:"CLIENT_NOSTR_PUBKEY"`
Expand Down
13 changes: 4 additions & 9 deletions echo_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,8 @@ func (svc *Service) LogoutHandler(c echo.Context) error {
}

func (svc *Service) AppsListHandler(c echo.Context) error {
user, _ := c.Get("user").(*User)
userApps := user.Apps

apps, err := svc.ListApps(&userApps)
apps, err := svc.ListApps()

if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResponse{
Expand All @@ -102,9 +100,8 @@ func (svc *Service) AppsListHandler(c echo.Context) error {
}

func (svc *Service) AppsShowHandler(c echo.Context) error {
user, _ := c.Get("user").(*User)
app := App{}
findResult := svc.db.Where("user_id = ? AND nostr_pubkey = ?", user.ID, c.Param("pubkey")).First(&app)
findResult := svc.db.Where("nostr_pubkey = ?", c.Param("pubkey")).First(&app)

if findResult.RowsAffected == 0 {
return c.JSON(http.StatusNotFound, ErrorResponse{
Expand All @@ -118,15 +115,14 @@ func (svc *Service) AppsShowHandler(c echo.Context) error {
}

func (svc *Service) AppsDeleteHandler(c echo.Context) error {
user, _ := c.Get("user").(*User)
pubkey := c.Param("pubkey")
if pubkey == "" {
return c.JSON(http.StatusBadRequest, ErrorResponse{
Message: "Invalid pubkey parameter",
})
}
app := App{}
result := svc.db.Where("user_id = ? AND nostr_pubkey = ?", user.ID, pubkey).First(&app)
result := svc.db.Where("nostr_pubkey = ?", pubkey).First(&app)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return c.JSON(http.StatusNotFound, ErrorResponse{
Expand All @@ -147,15 +143,14 @@ func (svc *Service) AppsDeleteHandler(c echo.Context) error {
}

func (svc *Service) AppsCreateHandler(c echo.Context) error {
user, _ := c.Get("user").(*User)
var requestData api.CreateAppRequest
if err := c.Bind(&requestData); err != nil {
return c.JSON(http.StatusBadRequest, ErrorResponse{
Message: fmt.Sprintf("Bad request: %s", err.Error()),
})
}

responseBody, err := svc.CreateApp(user, &requestData)
responseBody, err := svc.CreateApp(&requestData)

if err != nil {
svc.Logger.Errorf("Failed to save app: %v", err)
Expand Down
6 changes: 1 addition & 5 deletions frontend/src/components/Navbar.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { Link, Outlet, useLocation } from "react-router-dom";

import { useUser } from "src/hooks/useUser";
import nwcLogo from "src/assets/images/nwc-logo.svg";

function Navbar() {
const { data: user } = useUser();
const location = useLocation();

const linkStyles =
Expand Down Expand Up @@ -35,9 +33,7 @@ function Navbar() {
</span>
</Link>

<div
className={`${user ? "hidden md:flex" : "flex"} space-x-4`}
>
<div className="flex space-x-4">
<Link
className={`${linkStyles} ${
location.pathname.startsWith("/apps") &&
Expand Down
8 changes: 0 additions & 8 deletions frontend/src/hooks/useUser.ts

This file was deleted.

2 changes: 1 addition & 1 deletion frontend/src/screens/apps/AppsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function AppsList() {
Connected apps
</h2>
<Link
className="inline-flex bg-purple-700 cursor-pointer dark:text-neutral-200 duration-150 focus-visible:ring-2 focus-visible:ring-offset-2 focus:outline-none font-medium items-center justify-center px-3 md:px-6 py-2 md:py-3 rounded-lg shadow text-white transition {{if not .User}}opacity-50{{else}}hover:bg-purple-900{{end}} text-sm md:text-base"
className="inline-flex bg-purple-700 cursor-pointer dark:text-neutral-200 duration-150 focus-visible:ring-2 focus-visible:ring-offset-2 focus:outline-none font-medium items-center justify-center px-3 md:px-6 py-2 md:py-3 rounded-lg shadow text-white transition hover:bg-purple-900 text-sm md:text-base"
to="/apps/new"
>
<PlusIcon className="mr-2 text-white w-6 h-6" />
Expand Down
15 changes: 0 additions & 15 deletions frontend/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,28 +40,13 @@ export const nip47MethodDescriptions: Record<RequestMethodType, string> = {
[NIP_47_PAY_INVOICE_METHOD]: "Send payments",
};

export interface User {
id: number;
albyIdentifier: string;
accessToken: string;
refreshToken: string;
email: string;
expiry: string;
lightningAddress: string;
apps: string;
createdAt: string;
updatedAt: string;
expiresAt: string;
}

export interface ErrorResponse {
message: string;
}

export interface App {
id: number;
userId: number;
user: User;
name: string;
description: string;
nostrPubkey: string;
Expand Down
2 changes: 0 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -196,11 +196,9 @@ require (
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect
github.com/glebarez/sqlite v1.5.0
github.com/gorilla/websocket v1.5.0 // indirect
github.com/jackc/pgx/v5 v5.4.3 // indirect
github.com/joho/godotenv v1.5.1
github.com/kelseyhightower/envconfig v1.4.0
github.com/lightningnetwork/lnd v0.15.5-beta.rc2
github.com/sirupsen/logrus v1.9.0
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 // indirect
gorm.io/driver/postgres v1.5.2
)
Loading

0 comments on commit 778c249

Please sign in to comment.