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,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,