Skip to content

Commit

Permalink
chore: split user from info endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
rolznz committed Dec 27, 2023
1 parent d5c7f0d commit 5279211
Show file tree
Hide file tree
Showing 7 changed files with 40 additions and 73 deletions.
38 changes: 15 additions & 23 deletions echo_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@ package main
import (
"embed"
"encoding/hex"
"errors"
"fmt"
"html/template"
"io"
"io/fs"
"net/http"
"net/url"
Expand All @@ -31,20 +28,6 @@ import (
//go:embed frontend/dist/*

Check failure on line 28 in echo_handlers.go

View workflow job for this annotation

GitHub Actions / build

pattern frontend/dist/*: no matching files found

Check failure on line 28 in echo_handlers.go

View workflow job for this annotation

GitHub Actions / build

pattern frontend/dist/*: no matching files found
var embeddedAssets embed.FS

type TemplateRegistry struct {
templates map[string]*template.Template
}

// Implement e.Renderer interface
func (t *TemplateRegistry) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
tmpl, ok := t.templates[name]
if !ok {
err := errors.New("Template not found -> " + name)
return err
}
return tmpl.ExecuteTemplate(w, "layout.html", data)
}

func (svc *Service) RegisterSharedRoutes(e *echo.Echo) {
e.HideBanner = true
e.Use(echologrus.Middleware())
Expand All @@ -64,6 +47,7 @@ func (svc *Service) RegisterSharedRoutes(e *echo.Echo) {
e.GET("/api/apps/:pubkey", svc.AppsShowHandler)
e.POST("/api/apps", svc.AppsCreateHandler)
e.DELETE("/api/apps/:pubkey", svc.AppsDeleteHandler)
e.GET("/api/user/me", svc.UserMeHandler)
e.GET("/api/info", svc.InfoHandler)
e.POST("/api/logout", svc.LogoutHandler)
frontend.RegisterHandlers(e)
Expand Down Expand Up @@ -328,6 +312,7 @@ func (svc *Service) AppsCreateHandler(c echo.Context) error {

func (svc *Service) AppsDeleteHandler(c echo.Context) error {
user, err := svc.GetUser(c)
// TODO: error handling
if err != nil {
return err
}
Expand All @@ -351,16 +336,23 @@ func (svc *Service) LogoutHandler(c echo.Context) error {
}

func (svc *Service) InfoHandler(c echo.Context) error {
responseBody := &api.InfoResponse{}
responseBody.BackendType = svc.cfg.LNBackendType
return c.JSON(http.StatusOK, responseBody)
}

func (svc *Service) UserMeHandler(c echo.Context) error {
user, err := svc.GetUser(c)
if err != nil {
// TODO: error handling
return err
}
responseBody := &api.InfoResponse{}
responseBody.BackendType = svc.cfg.LNBackendType
if user != nil {
responseBody.User = &api.User{
Email: user.Email,
}
if user == nil {
return c.NoContent(http.StatusNotFound)
}

responseBody := api.User{
Email: user.Email,
}
return c.JSON(http.StatusOK, responseBody)
}
28 changes: 13 additions & 15 deletions frontend/src/components/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import React from "react";
import { LogoutIcon } from "./icons/LogoutIcon";
import { handleFetchError, validateFetchResponse } from "../utils/fetch";
import { useCSRF } from "../hooks/useCSRF";
import { useUser } from "../hooks/useUser";

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

const linkStyles =
Expand Down Expand Up @@ -41,9 +43,7 @@ function Navbar() {
</a>

<div
className={`${
info?.user ? "hidden md:flex" : "flex"
} space-x-4`}
className={`${user ? "hidden md:flex" : "flex"} space-x-4`}
>
<a
className={`${linkStyles} ${
Expand Down Expand Up @@ -79,11 +79,11 @@ function Navbar() {

function ProfileDropdown() {
useLogin();
const { data: info } = useInfo();
const { data: csrf } = useCSRF();
const { data: user } = useUser();
const [isOpen, setOpen] = React.useState(false);

if (!info?.user) {
if (!user) {
return null;
}

Expand Down Expand Up @@ -112,7 +112,7 @@ function ProfileDropdown() {
className="text-gray-400 text-xs font-medium sm:text-base cursor-pointer select-none "
onClick={() => setOpen((current) => !current)}
>
<span>{info.user.email}</span>
<span>{user.email}</span>
<img
id="caret"
className={`inline cursor-pointer w-4 ml-2 ${
Expand All @@ -139,15 +139,13 @@ function ProfileDropdown() {
<p className="font-normal">About</p>
</a>

{info?.user && (
<div
className="flex items-center justify-left py-2 text-red-500"
onClick={logout}
>
<LogoutIcon className="inline cursor-pointer w-4 mr-3" />
<p className="font-normal">Logout</p>
</div>
)}
<div
className="flex items-center justify-left py-2 text-red-500"
onClick={logout}
>
<LogoutIcon className="inline cursor-pointer w-4 mr-3" />
<p className="font-normal">Logout</p>
</div>
</div>
)}
</div>
Expand Down
10 changes: 5 additions & 5 deletions frontend/src/hooks/useLogin.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
import { useLocation, useNavigate } from "react-router-dom";
import { useInfo } from "./useInfo";
import React from "react";
import { useUser } from "./useUser";

const RETURN_TO_KEY = "returnTo";

export function useLogin() {
const { data: info, isLoading } = useInfo();
const { data: user, isLoading } = useUser();
const location = useLocation();
const navigate = useNavigate();

React.useEffect(() => {
if (!isLoading) {
if (info?.user) {
if (user) {
const returnTo = window.localStorage.getItem(RETURN_TO_KEY);
if (returnTo) {
window.localStorage.removeItem(RETURN_TO_KEY);
navigate(returnTo);
}
}
if (!info?.user && ["/login", "/about"].indexOf(location.pathname) < 0) {
if (!user && ["/login", "/about"].indexOf(location.pathname) < 0) {
const returnTo = location.pathname + location.search;
window.localStorage.setItem(RETURN_TO_KEY, returnTo);

navigate("/login");
}
}
}, [info?.user, isLoading, location.pathname, location.search, navigate]);
}, [user, isLoading, location.pathname, location.search, navigate]);

return null;
}
7 changes: 7 additions & 0 deletions frontend/src/hooks/useUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import useSWR from "swr";
import { swrFetcher } from "../swr";
import { User } from "../types";

export function useUser() {
return useSWR<User>("/api/user/me", swrFetcher);
}
12 changes: 0 additions & 12 deletions frontend/src/screens/Login.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,7 @@
import { useNavigate } from "react-router-dom";
import { useInfo } from "../hooks/useInfo";
import { useEffect } from "react";
import nwcLogo from "../assets/images/nwc-logo.svg";
import albyHead from "../assets/images/alby-head.svg";

function Login() {
const { data: info } = useInfo();
const navigate = useNavigate();

useEffect(() => {
if (info?.user) {
navigate("/");
}
}, [navigate, info?.user]);

return (
<div className="text-center pt-4">
<img
Expand Down
5 changes: 0 additions & 5 deletions frontend/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,8 @@ export interface NostrEvent {
updatedAt: string;
}

export interface UserInfo {
user: User | null;
}

export interface InfoResponse {
backendType: BackendType;
user: User | null; // TODO: remove
}

export interface CreateAppResponse {
Expand Down
13 changes: 0 additions & 13 deletions models/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,6 @@ type App struct {
BudgetRenewal string `json:"budgetRenewal"`
}

// type AppPermission struct {
// ID uint `json:"id"`
// AppId uint `json:"appId" validate:"required"`
// App App `json:"app"`
// RequestMethod string `json:"requestMethod" validate:"required"`
// MaxAmount int `json:"maxAmount"`
// BudgetRenewal string `json:"budgetRenewal"`
// ExpiresAt time.Time `json:"expiresAt"`
// CreatedAt time.Time `json:"createdAt"`
// UpdatedAt time.Time `json:"updatedAt"`
// }

type ListAppsResponse struct {
Apps []App `json:"apps"`
}
Expand All @@ -47,6 +35,5 @@ type User struct {
}

type InfoResponse struct {
User *User `json:"user"`
BackendType string `json:"backendType"`
}

0 comments on commit 5279211

Please sign in to comment.