refactor auth and addinvoice

This commit is contained in:
kiwiidb
2022-01-19 15:25:07 +01:00
parent b8fb826ea5
commit 55fda4d3f4
4 changed files with 70 additions and 67 deletions

View File

@@ -1,11 +1,9 @@
package controllers
import (
"context"
"math/rand"
"net/http"
"github.com/getAlby/lndhub.go/db/models"
"github.com/getAlby/lndhub.go/lib"
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/random"
@@ -43,33 +41,20 @@ func (controller *AddInvoiceController) AddInvoice(c echo.Context) error {
})
}
invoice := models.Invoice{
Type: "",
UserID: userID,
TransactionEntryID: 0,
Amount: body.Amt,
Memo: body.Memo,
DescriptionHash: body.DescriptionHash,
PaymentRequest: "",
RHash: "",
State: "",
}
// TODO: move this to a service layer and call a method
_, err := controller.svc.DB.NewInsert().Model(&invoice).Exec(context.TODO())
invoice, err := controller.svc.AddInvoice(userID, body.Amt, body.Memo, body.DescriptionHash)
if err != nil {
c.Logger().Errorf("error saving an invoice: %v", err)
// TODO: better error handling, possibly panic and catch in an error handler
return c.JSON(http.StatusInternalServerError, nil)
}
var responseBody struct {
RHash string `json:"r_hash"`
PaymentRequest string `json:"payment_request"`
PayReq string `json:"pay_req"`
}
//TODO
responseBody.PayReq = makePreimageHex()
responseBody.PaymentRequest = invoice.PaymentRequest
return c.JSON(http.StatusOK, &responseBody)
}

View File

@@ -1,14 +1,10 @@
package controllers
import (
"context"
"net/http"
"github.com/getAlby/lndhub.go/db/models"
"github.com/getAlby/lndhub.go/lib"
"github.com/getAlby/lndhub.go/lib/tokens"
"github.com/labstack/echo/v4"
"golang.org/x/crypto/bcrypt"
)
// AuthController : AuthController struct
@@ -48,56 +44,15 @@ func (controller *AuthController) Auth(c echo.Context) error {
})
}
var user models.User
switch {
case body.Login != "" || body.Password != "":
{
if err := controller.svc.DB.NewSelect().Model(&user).Where("login = ?", body.Login).Scan(context.TODO()); err != nil {
return c.JSON(http.StatusNotFound, echo.Map{
"error": true,
"code": 1,
"message": "bad auth",
})
}
if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(body.Password)) != nil {
return c.JSON(http.StatusNotFound, echo.Map{
"error": true,
"code": 1,
"message": "bad auth",
})
}
}
case body.RefreshToken != "":
{
// TODO: currently not supported
// I'd love to remove this from the auth handler, as the refresh token
// is usually a part of the JWT middleware: https://webdevstation.com/posts/user-authentication-with-go-using-jwt-token/
// if the current client depends on that - we can incorporate the refresh JWT code into here
return c.JSON(http.StatusNotFound, echo.Map{
"error": true,
"code": 1,
"message": "bad auth",
})
}
default:
accessToken, refreshToken, err := controller.svc.GenerateToken(body.Login, body.Password, body.RefreshToken)
if err != nil {
return c.JSON(http.StatusBadRequest, echo.Map{
"error": true,
"code": 8,
"message": "login and password or refresh token is required",
"message": err.Error(),
})
}
accessToken, err := tokens.GenerateAccessToken(controller.JWTSecret, controller.JWTExpiry, &user)
if err != nil {
return err
}
refreshToken, err := tokens.GenerateRefreshToken(controller.JWTSecret, controller.JWTExpiry, &user)
if err != nil {
return err
}
return c.JSON(http.StatusOK, echo.Map{
"refresh_token": refreshToken,
"access_token": accessToken,

View File

@@ -19,7 +19,7 @@ func Logger(logFilePath string) *lecho.Logger {
if logFilePath != "" {
file, err := GetLoggingFile(logFilePath)
if err != nil {
logger.Error("failed to create logging file: %v", err)
logger.Errorf("failed to create logging file: %v", err)
}
logger.SetOutput(file)
}

View File

@@ -2,10 +2,13 @@ package lib
import (
"context"
"fmt"
"github.com/getAlby/lndhub.go/db/models"
"github.com/getAlby/lndhub.go/lib/tokens"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/uptrace/bun"
"golang.org/x/crypto/bcrypt"
)
type LndhubService struct {
@@ -40,3 +43,63 @@ func (svc *LndhubService) AccountFor(ctx context.Context, accountType string, us
err := svc.DB.NewSelect().Model(&account).Where("user_id = ? AND type= ?", userId, accountType).Limit(1).Scan(ctx)
return account, err
}
func (svc *LndhubService) AddInvoice(userID int64, amount uint, memo, descriptionHash string) (*models.Invoice, error) {
invoice := &models.Invoice{
Type: "",
UserID: userID,
TransactionEntryID: 0,
Amount: amount,
Memo: memo,
DescriptionHash: descriptionHash,
PaymentRequest: "",
RHash: "",
State: "",
}
// TODO: move this to a service layer and call a method
_, err := svc.DB.NewInsert().Model(invoice).Exec(context.TODO())
if err != nil {
return nil, err
}
return invoice, nil
}
func (svc *LndhubService) GenerateToken(login, password, inRefreshToken string) (accessToken, refreshToken string, err error) {
var user models.User
switch {
case login != "" || password != "":
{
if err := svc.DB.NewSelect().Model(&user).Where("login = ?", login).Scan(context.TODO()); err != nil {
return "", "", fmt.Errorf("bad auth")
}
if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) != nil {
return "", "", fmt.Errorf("bad auth")
}
}
case inRefreshToken != "":
{
// TODO: currently not supported
// I'd love to remove this from the auth handler, as the refresh token
// is usually a part of the JWT middleware: https://webdevstation.com/posts/user-authentication-with-go-using-jwt-token/
// if the current client depends on that - we can incorporate the refresh JWT code into here
return "", "", fmt.Errorf("bad auth")
}
default:
{
return "", "", fmt.Errorf("login and password or refresh token is required")
}
}
accessToken, err = tokens.GenerateAccessToken(svc.Config.JWTSecret, svc.Config.JWTExpiry, &user)
if err != nil {
return "", "", err
}
refreshToken, err = tokens.GenerateRefreshToken(svc.Config.JWTSecret, svc.Config.JWTExpiry, &user)
if err != nil {
return "", "", err
}
return accessToken, refreshToken, nil
}