shiori/internal/domains/accounts.go
Felipe Martin cc7c75116d
refactor: migrate bookmark static pages to new http server (#775)
* migrate bookmark content route to new http server

* new archive page

* remove unused go generate comment

* database mock

* utils cleanup

* unused var

* domains refactor and tests

* fixed secret key type

* redirect to login on ui errors

* fixed archive folder with storage domain

* webroot documentation

* some bookmark route tests

* fixed error in bookmark domain for non existant bookmarks

* centralice errors

* add coverage data to unittests

* added tests, refactor storage to use afero

* removed mock to avoid increasing complexity

* using deps to copy files around

* remove config usage (to deps)

* remove handler-ui file
2023-12-28 18:18:32 +01:00

84 lines
2.1 KiB
Go

package domains
import (
"context"
"fmt"
"time"
"github.com/go-shiori/shiori/internal/dependencies"
"github.com/go-shiori/shiori/internal/model"
"github.com/golang-jwt/jwt/v5"
"github.com/pkg/errors"
"golang.org/x/crypto/bcrypt"
)
type AccountsDomain struct {
deps *dependencies.Dependencies
}
type JWTClaim struct {
jwt.RegisteredClaims
Account *model.Account
}
func (d *AccountsDomain) CheckToken(ctx context.Context, userJWT string) (*model.Account, error) {
token, err := jwt.ParseWithClaims(userJWT, &JWTClaim{}, func(token *jwt.Token) (interface{}, error) {
// Validate algorithm
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return d.deps.Config.Http.SecretKey, nil
})
if err != nil {
return nil, errors.Wrap(err, "error parsing token")
}
if claims, ok := token.Claims.(*JWTClaim); ok && token.Valid {
if claims.Account.ID > 0 {
return claims.Account, nil
}
if err != nil {
return nil, err
}
return claims.Account, nil
}
return nil, fmt.Errorf("error obtaining user from JWT claims")
}
func (d *AccountsDomain) GetAccountFromCredentials(ctx context.Context, username, password string) (*model.Account, error) {
account, _, err := d.deps.Database.GetAccount(ctx, username)
if err != nil {
return nil, fmt.Errorf("username and password do not match")
}
if err := bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(password)); err != nil {
return nil, fmt.Errorf("username and password do not match")
}
return &account, nil
}
func (d *AccountsDomain) CreateTokenForAccount(account *model.Account, expiration time.Time) (string, error) {
claims := jwt.MapClaims{
"account": account.ToDTO(),
"exp": expiration.UTC().Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
t, err := token.SignedString(d.deps.Config.Http.SecretKey)
if err != nil {
d.deps.Log.WithError(err).Error("error signing token")
}
return t, err
}
func NewAccountsDomain(deps *dependencies.Dependencies) *AccountsDomain {
return &AccountsDomain{
deps: deps,
}
}