Skip to content
This repository has been archived by the owner on Sep 2, 2024. It is now read-only.

Commit

Permalink
feat: oauth before login
Browse files Browse the repository at this point in the history
  • Loading branch information
im-adithya committed Jun 11, 2024
1 parent 2f5bbf4 commit 55d9b1c
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 21 deletions.
37 changes: 36 additions & 1 deletion alby/alby_http_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"net/http"

"github.com/getAlby/nostr-wallet-connect/config"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"
)
Expand All @@ -15,6 +17,11 @@ type AlbyHttpService struct {
appConfig *config.AppConfig
}

const (
sessionCookieName = "session"
sessionCookieOAuthKey = "oauthenticated"
)

func NewAlbyHttpService(albyOAuthSvc AlbyOAuthService, logger *logrus.Logger, appConfig *config.AppConfig) *AlbyHttpService {
return &AlbyHttpService{
albyOAuthSvc: albyOAuthSvc,
Expand All @@ -24,13 +31,33 @@ func NewAlbyHttpService(albyOAuthSvc AlbyOAuthService, logger *logrus.Logger, ap
}

func (albyHttpSvc *AlbyHttpService) RegisterSharedRoutes(e *echo.Echo, authMiddleware func(next echo.HandlerFunc) echo.HandlerFunc) {
e.GET("/api/alby/callback", albyHttpSvc.albyCallbackHandler, authMiddleware)
e.GET("/api/alby/callback", albyHttpSvc.albyCallbackHandler)
e.GET("/api/alby/me", albyHttpSvc.albyMeHandler, authMiddleware)
e.GET("/api/alby/balance", albyHttpSvc.albyBalanceHandler, authMiddleware)
e.POST("/api/alby/pay", albyHttpSvc.albyPayHandler, authMiddleware)
e.POST("/api/alby/link-account", albyHttpSvc.albyLinkAccountHandler, authMiddleware)
}

func (albyHttpSvc *AlbyHttpService) IsAlbyConnected(c echo.Context) bool {
sess, _ := session.Get(sessionCookieName, c)
return sess.Values[sessionCookieOAuthKey] == true
}

func (albyHttpSvc *AlbyHttpService) saveSessionCookie(c echo.Context) error {
sess, _ := session.Get("session", c)
sess.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 7,
HttpOnly: true,
}
sess.Values[sessionCookieOAuthKey] = true
err := sess.Save(c.Request(), c.Response())
if err != nil {
albyHttpSvc.logger.WithError(err).Error("Failed to save session")
}
return err
}

func (albyHttpSvc *AlbyHttpService) albyCallbackHandler(c echo.Context) error {
code := c.QueryParam("code")

Expand All @@ -42,6 +69,14 @@ func (albyHttpSvc *AlbyHttpService) albyCallbackHandler(c echo.Context) error {
})
}

err = albyHttpSvc.saveSessionCookie(c)

if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResponse{
Message: fmt.Sprintf("Failed to save session: %s", err.Error()),
})
}

if albyHttpSvc.appConfig.IsDefaultClientId() {
// do not redirect if using default OAuth client
// redirect will be handled by the frontend instead
Expand Down
23 changes: 13 additions & 10 deletions alby/alby_oauth_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,24 +72,27 @@ func (svc *albyOAuthService) CallbackHandler(ctx context.Context, code string) e
}
svc.saveToken(token)

me, err := svc.GetMe(ctx)
if err != nil {
svc.logger.WithError(err).Error("Failed to fetch user me")
// remove token so user can retry
svc.config.SetUpdate(accessTokenKey, me.Identifier, "")
return err
}

existingUserIdentifier, err := svc.GetUserIdentifier()
if err != nil {
svc.logger.WithError(err).Error("Failed to get alby user identifier")
return err
}

// setup Alby account on first time login
// save the user's alby account ID on first time login
if existingUserIdentifier == "" {
// fetch and save the user's alby account ID. This cannot be changed.
me, err := svc.GetMe(ctx)
if err != nil {
svc.logger.WithError(err).Error("Failed to fetch user me")
// remove token so user can retry
svc.config.SetUpdate(accessTokenKey, me.Identifier, "")
return err
}

svc.config.SetUpdate(userIdentifierKey, me.Identifier, "")
} else {
if existingUserIdentifier != me.Identifier {
return errors.New("alby identifier does not match")
}
}

return nil
Expand Down
1 change: 0 additions & 1 deletion api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,6 @@ func (api *api) GetInfo(ctx context.Context) (*InfoResponse, error) {
return nil, err
}
info.AlbyUserIdentifier = albyUserIdentifier
info.AlbyAccountConnected = api.svc.GetAlbyOAuthSvc().IsConnected(ctx)
if api.svc.GetLNClient() != nil {
nodeInfo, err := api.svc.GetLNClient().GetInfo(ctx)
if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/components/redirects/HomeRedirect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export function HomeRedirect() {
}
let to: string | undefined;
if (info.setupCompleted && info.running) {
if (info.unlocked) {
if (info.albyAccountConnected) {
if (info.albyAccountConnected) {
if (info.unlocked) {
const returnTo = window.localStorage.getItem(
localStorageKeys.returnTo
);
Expand All @@ -27,10 +27,10 @@ export function HomeRedirect() {
}, 100);
to = returnTo || "/wallet";
} else {
to = "/alby/auth";
to = "/unlock";
}
} else {
to = "/unlock";
to = "/alby/auth";
}
} else if (info.setupCompleted && !info.running) {
to = "/start";
Expand Down
6 changes: 1 addition & 5 deletions http/http_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ func (httpSvc *HttpService) infoHandler(c echo.Context) error {
Message: err.Error(),
})
}
responseBody.AlbyAccountConnected = httpSvc.albyHttpSvc.IsAlbyConnected(c)
responseBody.Unlocked = httpSvc.isUnlocked(c)
return c.JSON(http.StatusOK, responseBody)
}
Expand Down Expand Up @@ -250,11 +251,6 @@ func (httpSvc *HttpService) isUnlocked(c echo.Context) bool {

func (httpSvc *HttpService) saveSessionCookie(c echo.Context) error {
sess, _ := session.Get("session", c)
sess.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 7,
HttpOnly: true,
}
sess.Values[sessionCookieAuthKey] = true
err := sess.Save(c.Request(), c.Response())
if err != nil {
Expand Down

0 comments on commit 55d9b1c

Please sign in to comment.