fix: refactor code to be testable #181
This commit was merged in pull request #212.
This commit is contained in:
397
service/auth.go
397
service/auth.go
@@ -10,9 +10,9 @@ import (
|
||||
"net/mail"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"me-fit/db"
|
||||
"me-fit/template"
|
||||
"me-fit/template/auth"
|
||||
tempMail "me-fit/template/mail"
|
||||
"me-fit/types"
|
||||
@@ -28,6 +28,7 @@ var (
|
||||
ErrInvalidPassword = errors.New("Password needs to be 8 characters long, contain at least one number, one special, one uppercase and one lowercase character")
|
||||
ErrInvalidEmail = errors.New("Invalid email")
|
||||
ErrAccountExists = errors.New("Account already exists")
|
||||
ErrSessionIdInvalid = errors.New("Session ID is invalid")
|
||||
)
|
||||
|
||||
type User struct {
|
||||
@@ -44,22 +45,41 @@ func NewUser(user *db.User) *User {
|
||||
}
|
||||
}
|
||||
|
||||
type ServiceAuth interface {
|
||||
SignIn(email string, password string) (*User, error)
|
||||
SignUp(email string, password string) (*User, error)
|
||||
SendVerificationMail(userId uuid.UUID, email string)
|
||||
type Session struct {
|
||||
Id string
|
||||
CreatedAt time.Time
|
||||
User *User
|
||||
}
|
||||
|
||||
type ServiceAuthImpl struct {
|
||||
dbAuth db.DbAuth
|
||||
randomGenerator RandomGenerator
|
||||
clock Clock
|
||||
func NewSession(session *db.Session, user *User) *Session {
|
||||
return &Session{
|
||||
Id: session.Id,
|
||||
CreatedAt: session.CreatedAt,
|
||||
User: user,
|
||||
}
|
||||
}
|
||||
|
||||
type AuthService interface {
|
||||
SignIn(email string, password string) (*Session, error)
|
||||
SignUp(email string, password string) (*User, error)
|
||||
SendVerificationMail(userId uuid.UUID, email string)
|
||||
SignOut(sessionId string) error
|
||||
DeleteAccount(user *User) error
|
||||
ChangePassword(user *User, currPass, newPass string) error
|
||||
|
||||
GetUserFromSessionId(sessionId string) (*User, error)
|
||||
}
|
||||
|
||||
type AuthServiceImpl struct {
|
||||
dbAuth db.AuthDb
|
||||
randomGenerator RandomService
|
||||
clock ClockService
|
||||
mailService MailService
|
||||
serverSettings *types.ServerSettings
|
||||
}
|
||||
|
||||
func NewServiceAuthImpl(dbAuth db.DbAuth, randomGenerator RandomGenerator, clock Clock, mailService MailService, serverSettings *types.ServerSettings) *ServiceAuthImpl {
|
||||
return &ServiceAuthImpl{
|
||||
func NewAuthServiceImpl(dbAuth db.AuthDb, randomGenerator RandomService, clock ClockService, mailService MailService, serverSettings *types.ServerSettings) *AuthServiceImpl {
|
||||
return &AuthServiceImpl{
|
||||
dbAuth: dbAuth,
|
||||
randomGenerator: randomGenerator,
|
||||
clock: clock,
|
||||
@@ -68,7 +88,7 @@ func NewServiceAuthImpl(dbAuth db.DbAuth, randomGenerator RandomGenerator, clock
|
||||
}
|
||||
}
|
||||
|
||||
func (service ServiceAuthImpl) SignIn(email string, password string) (*User, error) {
|
||||
func (service AuthServiceImpl) SignIn(email string, password string) (*Session, error) {
|
||||
user, err := service.dbAuth.GetUser(email)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrUserNotFound) {
|
||||
@@ -84,10 +104,36 @@ func (service ServiceAuthImpl) SignIn(email string, password string) (*User, err
|
||||
return nil, ErrInvaidCredentials
|
||||
}
|
||||
|
||||
return NewUser(user), nil
|
||||
session, err := service.createSession(user.Id)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
}
|
||||
|
||||
return NewSession(session, NewUser(user)), nil
|
||||
}
|
||||
|
||||
func (service ServiceAuthImpl) SignUp(email string, password string) (*User, error) {
|
||||
func (service AuthServiceImpl) createSession(userId uuid.UUID) (*db.Session, error) {
|
||||
sessionId, err := service.randomGenerator.String(32)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
}
|
||||
|
||||
err = service.dbAuth.DeleteOldSessions(userId)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
}
|
||||
|
||||
session := db.NewSession(sessionId, userId, service.clock.Now())
|
||||
|
||||
err = service.dbAuth.InsertSession(session)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
}
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (service AuthServiceImpl) SignUp(email string, password string) (*User, error) {
|
||||
_, err := mail.ParseAddress(email)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidEmail
|
||||
@@ -123,7 +169,7 @@ func (service ServiceAuthImpl) SignUp(email string, password string) (*User, err
|
||||
return NewUser(dbUser), nil
|
||||
}
|
||||
|
||||
func (service ServiceAuthImpl) SendVerificationMail(userId uuid.UUID, email string) {
|
||||
func (service AuthServiceImpl) SendVerificationMail(userId uuid.UUID, email string) {
|
||||
var token string
|
||||
|
||||
token, err := service.dbAuth.GetEmailVerificationToken(userId)
|
||||
@@ -153,45 +199,35 @@ func (service ServiceAuthImpl) SendVerificationMail(userId uuid.UUID, email stri
|
||||
service.mailService.SendMail(email, "Welcome to ME-FIT", w.String())
|
||||
}
|
||||
|
||||
func (service AuthServiceImpl) SignOut(sessionId string) error {
|
||||
|
||||
return service.dbAuth.DeleteSession(sessionId)
|
||||
}
|
||||
|
||||
func (service AuthServiceImpl) GetUserFromSessionId(sessionId string) (*User, error) {
|
||||
if sessionId == "" {
|
||||
return nil, ErrSessionIdInvalid
|
||||
}
|
||||
|
||||
session, err := service.dbAuth.GetSession(sessionId)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
}
|
||||
|
||||
user, err := service.dbAuth.GetUserById(session.UserId)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
}
|
||||
|
||||
if session.CreatedAt.Add(time.Duration(8 * time.Hour)).Before(service.clock.Now()) {
|
||||
return nil, nil
|
||||
} else {
|
||||
return NewUser(user), nil
|
||||
}
|
||||
}
|
||||
|
||||
// TODO
|
||||
|
||||
func HandleSignUpVerifyPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := utils.GetUserFromSession(db, r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
} else if user.EmailVerified {
|
||||
utils.DoRedirect(w, r, "/")
|
||||
} else {
|
||||
userComp := UserInfoComp(user)
|
||||
signIn := auth.VerifyComp()
|
||||
err := template.Layout(signIn, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||
if err != nil {
|
||||
utils.LogError("Failed to render verify page", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func HandleDeleteAccountPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// An unverified email should be able to delete their account
|
||||
user := utils.GetUserFromSession(db, r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
} else {
|
||||
userComp := UserInfoComp(user)
|
||||
comp := auth.DeleteAccountComp()
|
||||
err := template.Layout(comp, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||
if err != nil {
|
||||
utils.LogError("Failed to render delete account page", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func HandleSignUpVerifyResponsePage(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -234,45 +270,7 @@ func HandleSignUpVerifyResponsePage(db *sql.DB) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func HandleChangePasswordPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
isPasswordReset := r.URL.Query().Has("token")
|
||||
|
||||
user := utils.GetUserFromSession(db, r)
|
||||
if user == nil && !isPasswordReset {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
} else {
|
||||
userComp := UserInfoComp(user)
|
||||
comp := auth.ChangePasswordComp(isPasswordReset)
|
||||
err := template.Layout(comp, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||
if err != nil {
|
||||
utils.LogError("Failed to render change password page", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func HandleResetPasswordPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
user := utils.GetUserFromSession(db, r)
|
||||
if user != nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
} else {
|
||||
userComp := UserInfoComp(nil)
|
||||
comp := auth.ResetPasswordComp()
|
||||
err := template.Layout(comp, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||
if err != nil {
|
||||
utils.LogError("Failed to render change password page", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func UserInfoComp(user *types.User) templ.Component {
|
||||
func UserInfoComp(user *User) templ.Component {
|
||||
|
||||
if user != nil {
|
||||
return auth.UserComp(user.Email)
|
||||
@@ -281,168 +279,46 @@ func UserInfoComp(user *types.User) templ.Component {
|
||||
}
|
||||
}
|
||||
|
||||
func HandleSignOutComp(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := utils.GetUserFromSession(db, r)
|
||||
func (service AuthServiceImpl) DeleteAccount(user *User) error {
|
||||
|
||||
if user != nil {
|
||||
_, err := db.Exec("DELETE FROM session WHERE session_id = ?", user.SessionId)
|
||||
if err != nil {
|
||||
utils.LogError("Could not delete session", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c := http.Cookie{
|
||||
Name: "id",
|
||||
Value: "",
|
||||
MaxAge: -1,
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
}
|
||||
|
||||
http.SetCookie(w, &c)
|
||||
utils.DoRedirect(w, r, "/")
|
||||
err := service.dbAuth.DeleteUser(user.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
go service.mailService.SendMail(user.Email, "Account deleted", "Your account has been deleted")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func HandleDeleteAccountComp(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||
mailService := NewMailServiceImpl(serverSettings)
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := utils.GetUserFromSession(db, r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
func (service AuthServiceImpl) ChangePassword(user *User, currPass, newPass string) error {
|
||||
|
||||
password := r.FormValue("password")
|
||||
if password == "" {
|
||||
utils.TriggerToast(w, r, "error", "Password is required")
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
storedHash []byte
|
||||
salt []byte
|
||||
)
|
||||
|
||||
err := db.QueryRow("SELECT password, salt FROM user WHERE user_uuid = ?", user.Id).Scan(&storedHash, &salt)
|
||||
if err != nil {
|
||||
utils.LogError("Could not get password", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
return
|
||||
}
|
||||
|
||||
currHash := GetHashPassword(password, salt)
|
||||
if subtle.ConstantTimeCompare(currHash, storedHash) == 0 {
|
||||
utils.TriggerToast(w, r, "error", "Password is not correct")
|
||||
return
|
||||
}
|
||||
|
||||
_, err = db.Exec("DELETE FROM workout WHERE user_id = ?", user.Id)
|
||||
if err != nil {
|
||||
utils.LogError("Could not delete workouts", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
return
|
||||
}
|
||||
|
||||
_, err = db.Exec("DELETE FROM user_token WHERE user_uuid = ?", user.Id)
|
||||
if err != nil {
|
||||
utils.LogError("Could not delete user tokens", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
return
|
||||
}
|
||||
|
||||
_, err = db.Exec("DELETE FROM session WHERE user_uuid = ?", user.Id)
|
||||
if err != nil {
|
||||
utils.LogError("Could not delete sessions", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
return
|
||||
}
|
||||
|
||||
_, err = db.Exec("DELETE FROM user WHERE user_uuid = ?", user.Id)
|
||||
if err != nil {
|
||||
utils.LogError("Could not delete user", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
return
|
||||
}
|
||||
|
||||
go mailService.SendMail(user.Email, "Account deleted", "Your account has been deleted")
|
||||
|
||||
utils.DoRedirect(w, r, "/")
|
||||
if !isPasswordValid(newPass) {
|
||||
return ErrInvalidPassword
|
||||
}
|
||||
}
|
||||
|
||||
func HandleVerifyResendComp(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := utils.GetUserFromSession(db, r)
|
||||
if user == nil || user.EmailVerified {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
// TODO
|
||||
// go sendVerificationEmail(db, user.Id.String(), user.Email, serverSettings)
|
||||
|
||||
w.Write([]byte("<p class=\"mt-8\">Verification email sent</p>"))
|
||||
if currPass == newPass {
|
||||
return ErrInvalidPassword
|
||||
}
|
||||
}
|
||||
|
||||
func HandleChangePasswordComp(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
user := utils.GetUserFromSession(db, r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
currPass := r.FormValue("current-password")
|
||||
newPass := r.FormValue("new-password")
|
||||
|
||||
if !isPasswordValid(newPass) {
|
||||
utils.TriggerToast(w, r, "error", ErrInvalidPassword.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if currPass == newPass {
|
||||
utils.TriggerToast(w, r, "error", "Please use a new password")
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
storedHash []byte
|
||||
salt []byte
|
||||
)
|
||||
|
||||
err := db.QueryRow("SELECT password, salt FROM user WHERE user_uuid = ?", user.Id).Scan(&storedHash, &salt)
|
||||
if err != nil {
|
||||
utils.LogError("Could not get password", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
return
|
||||
}
|
||||
|
||||
currHash := GetHashPassword(currPass, salt)
|
||||
if subtle.ConstantTimeCompare(currHash, storedHash) == 0 {
|
||||
utils.TriggerToast(w, r, "error", "Current Password is not correct")
|
||||
return
|
||||
}
|
||||
|
||||
newHash := GetHashPassword(newPass, salt)
|
||||
|
||||
_, err = db.Exec("UPDATE user SET password = ? WHERE user_uuid = ?", newHash, user.Id)
|
||||
if err != nil {
|
||||
utils.LogError("Could not update password", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
return
|
||||
}
|
||||
|
||||
utils.TriggerToast(w, r, "success", "Password changed")
|
||||
_, err := service.SignIn(user.Email, currPass)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
userDb, err := service.dbAuth.GetUserById(user.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
newHash := GetHashPassword(newPass, userDb.Salt)
|
||||
|
||||
err = service.dbAuth.UpdateUserPassword(user.Id, newHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func HandleActualResetPasswordComp(db *sql.DB) http.HandlerFunc {
|
||||
@@ -517,7 +393,7 @@ func HandleResetPasswordComp(db *sql.DB, serverSettings *types.ServerSettings) h
|
||||
return
|
||||
}
|
||||
|
||||
token, err := NewRandomGeneratorImpl().String(32)
|
||||
token, err := NewRandomServiceImpl().String(32)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -556,39 +432,6 @@ func HandleResetPasswordComp(db *sql.DB, serverSettings *types.ServerSettings) h
|
||||
}
|
||||
}
|
||||
|
||||
func TryCreateSessionAndSetCookie(r *http.Request, w http.ResponseWriter, db *sql.DB, user_uuid uuid.UUID) error {
|
||||
sessionId, err := NewRandomGeneratorImpl().String(32)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
}
|
||||
|
||||
// Delete old inactive sessions
|
||||
_, err = db.Exec("DELETE FROM session WHERE created_at < datetime('now','-8 hours') AND user_uuid = ?", user_uuid)
|
||||
if err != nil {
|
||||
utils.LogError("Could not delete old sessions", err)
|
||||
return types.ErrInternal
|
||||
}
|
||||
|
||||
_, err = db.Exec("INSERT INTO session (session_id, user_uuid, created_at) VALUES (?, ?, datetime())", sessionId, user_uuid)
|
||||
if err != nil {
|
||||
utils.LogError("Could not insert session", err)
|
||||
return types.ErrInternal
|
||||
}
|
||||
|
||||
cookie := http.Cookie{
|
||||
Name: "id",
|
||||
Value: sessionId,
|
||||
MaxAge: 60 * 60 * 8, // 8 hours
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
}
|
||||
http.SetCookie(w, &cookie)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetHashPassword(password string, salt []byte) []byte {
|
||||
return argon2.IDKey([]byte(password), salt, 1, 64*1024, 1, 16)
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"me-fit/db"
|
||||
"me-fit/mocks"
|
||||
"me-fit/types"
|
||||
"strings"
|
||||
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -33,24 +33,25 @@ func TestSignIn(t *testing.T) {
|
||||
time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
)
|
||||
|
||||
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||
mockDbAuth.EXPECT().GetUser("test@test.de").Return(user, nil)
|
||||
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
dbSession := db.NewSession("sessionId", user.Id, time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC))
|
||||
|
||||
mockAuthDb := mocks.NewMockAuthDb(t)
|
||||
mockAuthDb.EXPECT().GetUser("test@test.de").Return(user, nil)
|
||||
mockAuthDb.EXPECT().DeleteOldSessions(user.Id).Return(nil)
|
||||
mockAuthDb.EXPECT().InsertSession(dbSession).Return(nil)
|
||||
mockRandom := mocks.NewMockRandomService(t)
|
||||
mockRandom.EXPECT().String(32).Return("sessionId", nil)
|
||||
mockClock := mocks.NewMockClockService(t)
|
||||
mockClock.EXPECT().Now().Return(time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC))
|
||||
mockMail := mocks.NewMockMailService(t)
|
||||
|
||||
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
underTest := NewAuthServiceImpl(mockAuthDb, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
|
||||
actualUser, err := underTest.SignIn(user.Email, "password")
|
||||
actualSession, err := underTest.SignIn(user.Email, "password")
|
||||
assert.Nil(t, err)
|
||||
|
||||
expectedUser := User{
|
||||
Id: user.Id,
|
||||
Email: user.Email,
|
||||
EmailVerified: user.EmailVerified,
|
||||
}
|
||||
|
||||
assert.Equal(t, expectedUser, *actualUser)
|
||||
expectedSession := NewSession(dbSession, NewUser(user))
|
||||
assert.Equal(t, expectedSession, actualSession)
|
||||
})
|
||||
|
||||
t.Run("should return ErrInvalidCretentials if password is not correct", func(t *testing.T) {
|
||||
@@ -69,13 +70,13 @@ func TestSignIn(t *testing.T) {
|
||||
time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
)
|
||||
|
||||
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||
mockDbAuth.EXPECT().GetUser(user.Email).Return(user, nil)
|
||||
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockAuthDb := mocks.NewMockAuthDb(t)
|
||||
mockAuthDb.EXPECT().GetUser(user.Email).Return(user, nil)
|
||||
mockRandom := mocks.NewMockRandomService(t)
|
||||
mockClock := mocks.NewMockClockService(t)
|
||||
mockMail := mocks.NewMockMailService(t)
|
||||
|
||||
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
underTest := NewAuthServiceImpl(mockAuthDb, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
|
||||
_, err := underTest.SignIn("test@test.de", "wrong password")
|
||||
|
||||
@@ -84,13 +85,13 @@ func TestSignIn(t *testing.T) {
|
||||
t.Run("should return ErrInvalidCretentials if user has not been found", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||
mockDbAuth.EXPECT().GetUser("test").Return(nil, db.ErrUserNotFound)
|
||||
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockAuthDb := mocks.NewMockAuthDb(t)
|
||||
mockAuthDb.EXPECT().GetUser("test").Return(nil, db.ErrUserNotFound)
|
||||
mockRandom := mocks.NewMockRandomService(t)
|
||||
mockClock := mocks.NewMockClockService(t)
|
||||
mockMail := mocks.NewMockMailService(t)
|
||||
|
||||
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
underTest := NewAuthServiceImpl(mockAuthDb, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
|
||||
_, err := underTest.SignIn("test", "test")
|
||||
assert.Equal(t, ErrInvaidCredentials, err)
|
||||
@@ -98,13 +99,13 @@ func TestSignIn(t *testing.T) {
|
||||
t.Run("should forward ErrInternal on any other error", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||
mockDbAuth.EXPECT().GetUser("test").Return(nil, errors.New("Some undefined error"))
|
||||
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockAuthDb := mocks.NewMockAuthDb(t)
|
||||
mockAuthDb.EXPECT().GetUser("test").Return(nil, errors.New("Some undefined error"))
|
||||
mockRandom := mocks.NewMockRandomService(t)
|
||||
mockClock := mocks.NewMockClockService(t)
|
||||
mockMail := mocks.NewMockMailService(t)
|
||||
|
||||
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
underTest := NewAuthServiceImpl(mockAuthDb, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
|
||||
_, err := underTest.SignIn("test", "test")
|
||||
|
||||
@@ -117,12 +118,12 @@ func TestSignUp(t *testing.T) {
|
||||
t.Run("should check for correct email address", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockAuthDb := mocks.NewMockAuthDb(t)
|
||||
mockRandom := mocks.NewMockRandomService(t)
|
||||
mockClock := mocks.NewMockClockService(t)
|
||||
mockMail := mocks.NewMockMailService(t)
|
||||
|
||||
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
underTest := NewAuthServiceImpl(mockAuthDb, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
|
||||
_, err := underTest.SignUp("invalid email address", "SomeStrongPassword123!")
|
||||
|
||||
@@ -131,12 +132,12 @@ func TestSignUp(t *testing.T) {
|
||||
t.Run("should check for password complexity", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockAuthDb := mocks.NewMockAuthDb(t)
|
||||
mockRandom := mocks.NewMockRandomService(t)
|
||||
mockClock := mocks.NewMockClockService(t)
|
||||
mockMail := mocks.NewMockMailService(t)
|
||||
|
||||
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
underTest := NewAuthServiceImpl(mockAuthDb, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
|
||||
weakPasswords := []string{
|
||||
"123!ab", // too short
|
||||
@@ -153,9 +154,9 @@ func TestSignUp(t *testing.T) {
|
||||
t.Run("should signup correctly", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockAuthDb := mocks.NewMockAuthDb(t)
|
||||
mockRandom := mocks.NewMockRandomService(t)
|
||||
mockClock := mocks.NewMockClockService(t)
|
||||
mockMail := mocks.NewMockMailService(t)
|
||||
|
||||
expected := User{
|
||||
@@ -164,7 +165,7 @@ func TestSignUp(t *testing.T) {
|
||||
EmailVerified: false,
|
||||
}
|
||||
|
||||
random := NewRandomGeneratorImpl()
|
||||
random := NewRandomServiceImpl()
|
||||
salt, err := random.Bytes(16)
|
||||
assert.Nil(t, err)
|
||||
password := "SomeStrongPassword123!"
|
||||
@@ -176,9 +177,9 @@ func TestSignUp(t *testing.T) {
|
||||
|
||||
mockClock.EXPECT().Now().Return(createTime)
|
||||
|
||||
mockDbAuth.EXPECT().InsertUser(db.NewUser(expected.Id, expected.Email, false, nil, false, GetHashPassword(password, salt), salt, createTime)).Return(nil)
|
||||
mockAuthDb.EXPECT().InsertUser(db.NewUser(expected.Id, expected.Email, false, nil, false, GetHashPassword(password, salt), salt, createTime)).Return(nil)
|
||||
|
||||
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
underTest := NewAuthServiceImpl(mockAuthDb, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
|
||||
actual, err := underTest.SignUp(expected.Email, password)
|
||||
|
||||
@@ -189,9 +190,9 @@ func TestSignUp(t *testing.T) {
|
||||
t.Run("should return ErrAccountExists", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockAuthDb := mocks.NewMockAuthDb(t)
|
||||
mockRandom := mocks.NewMockRandomService(t)
|
||||
mockClock := mocks.NewMockClockService(t)
|
||||
mockMail := mocks.NewMockMailService(t)
|
||||
|
||||
user := User{
|
||||
@@ -199,7 +200,7 @@ func TestSignUp(t *testing.T) {
|
||||
Email: "some@valid.email",
|
||||
}
|
||||
|
||||
random := NewRandomGeneratorImpl()
|
||||
random := NewRandomServiceImpl()
|
||||
salt, err := random.Bytes(16)
|
||||
assert.Nil(t, err)
|
||||
password := "SomeStrongPassword123!"
|
||||
@@ -211,9 +212,9 @@ func TestSignUp(t *testing.T) {
|
||||
|
||||
mockClock.EXPECT().Now().Return(createTime)
|
||||
|
||||
mockDbAuth.EXPECT().InsertUser(db.NewUser(user.Id, user.Email, false, nil, false, GetHashPassword(password, salt), salt, createTime)).Return(db.ErrUserExists)
|
||||
mockAuthDb.EXPECT().InsertUser(db.NewUser(user.Id, user.Email, false, nil, false, GetHashPassword(password, salt), salt, createTime)).Return(db.ErrUserExists)
|
||||
|
||||
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
underTest := NewAuthServiceImpl(mockAuthDb, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
|
||||
_, err = underTest.SignUp(user.Email, password)
|
||||
assert.Equal(t, ErrAccountExists, err)
|
||||
@@ -230,16 +231,16 @@ func TestSendVerificationMail(t *testing.T) {
|
||||
email := "some@email.de"
|
||||
userId := uuid.New()
|
||||
|
||||
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockAuthDb := mocks.NewMockAuthDb(t)
|
||||
mockRandom := mocks.NewMockRandomService(t)
|
||||
mockClock := mocks.NewMockClockService(t)
|
||||
mockMail := mocks.NewMockMailService(t)
|
||||
|
||||
mockDbAuth.EXPECT().GetEmailVerificationToken(userId).Return(token, nil)
|
||||
mockAuthDb.EXPECT().GetEmailVerificationToken(userId).Return(token, nil)
|
||||
|
||||
mockMail.EXPECT().SendMail(email, "Welcome to ME-FIT", mock.MatchedBy(func(message string) bool { return strings.Contains(message, token) })).Return(nil)
|
||||
|
||||
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
underTest := NewAuthServiceImpl(mockAuthDb, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||
|
||||
underTest.SendVerificationMail(userId, email)
|
||||
})
|
||||
|
||||
@@ -2,16 +2,16 @@ package service
|
||||
|
||||
import "time"
|
||||
|
||||
type Clock interface {
|
||||
type ClockService interface {
|
||||
Now() time.Time
|
||||
}
|
||||
|
||||
type ClockImpl struct{}
|
||||
type ClockServiceImpl struct{}
|
||||
|
||||
func NewClockImpl() Clock {
|
||||
return &ClockImpl{}
|
||||
func NewClockServiceImpl() ClockService {
|
||||
return &ClockServiceImpl{}
|
||||
}
|
||||
|
||||
func (c *ClockImpl) Now() time.Time {
|
||||
func (c *ClockServiceImpl) Now() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"me-fit/template"
|
||||
"me-fit/types"
|
||||
"me-fit/utils"
|
||||
"net/http"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
)
|
||||
|
||||
func HandleIndexAnd404(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := utils.GetUserFromSession(db, r)
|
||||
|
||||
var comp templ.Component = nil
|
||||
userComp := UserInfoComp(user)
|
||||
|
||||
if r.URL.Path != "/" {
|
||||
comp = template.Layout(template.NotFound(), userComp, serverSettings.Environment)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
} else {
|
||||
comp = template.Layout(template.Index(), userComp, serverSettings.Environment)
|
||||
}
|
||||
|
||||
err := comp.Render(r.Context(), w)
|
||||
if err != nil {
|
||||
utils.LogError("Failed to render index", err)
|
||||
http.Error(w, "Failed to render index", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,20 +10,20 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type RandomGenerator interface {
|
||||
type RandomService interface {
|
||||
Bytes(size int) ([]byte, error)
|
||||
String(size int) (string, error)
|
||||
UUID() (uuid.UUID, error)
|
||||
}
|
||||
|
||||
type RandomGeneratorImpl struct {
|
||||
type RandomServiceImpl struct {
|
||||
}
|
||||
|
||||
func NewRandomGeneratorImpl() *RandomGeneratorImpl {
|
||||
return &RandomGeneratorImpl{}
|
||||
func NewRandomServiceImpl() *RandomServiceImpl {
|
||||
return &RandomServiceImpl{}
|
||||
}
|
||||
|
||||
func (r *RandomGeneratorImpl) Bytes(size int) ([]byte, error) {
|
||||
func (r *RandomServiceImpl) Bytes(size int) ([]byte, error) {
|
||||
b := make([]byte, 32)
|
||||
_, err := rand.Read(b)
|
||||
if err != nil {
|
||||
@@ -34,7 +34,7 @@ func (r *RandomGeneratorImpl) Bytes(size int) ([]byte, error) {
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (r *RandomGeneratorImpl) String(size int) (string, error) {
|
||||
func (r *RandomServiceImpl) String(size int) (string, error) {
|
||||
bytes, err := r.Bytes(size)
|
||||
if err != nil {
|
||||
return "", types.ErrInternal
|
||||
@@ -43,6 +43,6 @@ func (r *RandomGeneratorImpl) String(size int) (string, error) {
|
||||
return base64.StdEncoding.EncodeToString(bytes), nil
|
||||
}
|
||||
|
||||
func (r *RandomGeneratorImpl) UUID() (uuid.UUID, error) {
|
||||
func (r *RandomServiceImpl) UUID() (uuid.UUID, error) {
|
||||
return uuid.NewRandom()
|
||||
}
|
||||
|
||||
@@ -1,183 +1,128 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"me-fit/template"
|
||||
"me-fit/template/workout"
|
||||
"me-fit/db"
|
||||
"me-fit/types"
|
||||
"me-fit/utils"
|
||||
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"errors"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func HandleWorkoutPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := utils.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
type WorkoutService interface {
|
||||
AddWorkout(user *User, workoutDto *WorkoutDto) (*WorkoutDto, error)
|
||||
DeleteWorkout(user *User, rowId int) error
|
||||
GetWorkouts(user *User) ([]*WorkoutDto, error)
|
||||
}
|
||||
|
||||
currentDate := time.Now().Format("2006-01-02")
|
||||
inner := workout.WorkoutComp(currentDate)
|
||||
userComp := UserInfoComp(user)
|
||||
err := template.Layout(inner, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||
if err != nil {
|
||||
utils.LogError("Failed to render workout page", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
type WorkoutServiceImpl struct {
|
||||
dbWorkout db.WorkoutDb
|
||||
randomGenerator RandomService
|
||||
clock ClockService
|
||||
mailService MailService
|
||||
serverSettings *types.ServerSettings
|
||||
}
|
||||
|
||||
func NewWorkoutServiceImpl(dbWorkout db.WorkoutDb, randomGenerator RandomService, clock ClockService, mailService MailService, serverSettings *types.ServerSettings) WorkoutService {
|
||||
return WorkoutServiceImpl{
|
||||
dbWorkout: dbWorkout,
|
||||
randomGenerator: randomGenerator,
|
||||
clock: clock,
|
||||
mailService: mailService,
|
||||
serverSettings: serverSettings,
|
||||
}
|
||||
}
|
||||
|
||||
func HandleWorkoutNewComp(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := utils.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
type WorkoutDto struct {
|
||||
RowId string
|
||||
Date string
|
||||
Type string
|
||||
Sets string
|
||||
Reps string
|
||||
}
|
||||
|
||||
var dateStr = r.FormValue("date")
|
||||
var typeStr = r.FormValue("type")
|
||||
var setsStr = r.FormValue("sets")
|
||||
var repsStr = r.FormValue("reps")
|
||||
|
||||
if dateStr == "" || typeStr == "" || setsStr == "" || repsStr == "" {
|
||||
utils.TriggerToast(w, r, "error", "Missing required fields")
|
||||
http.Error(w, "Missing required fields", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
date, err := time.Parse("2006-01-02", dateStr)
|
||||
if err != nil {
|
||||
utils.TriggerToast(w, r, "error", "Invalid date")
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
sets, err := strconv.Atoi(setsStr)
|
||||
if err != nil {
|
||||
utils.TriggerToast(w, r, "error", "Invalid number")
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
reps, err := strconv.Atoi(repsStr)
|
||||
if err != nil {
|
||||
utils.TriggerToast(w, r, "error", "Invalid number")
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var rowId int
|
||||
err = db.QueryRow("INSERT INTO workout (user_id, date, type, sets, reps) VALUES (?, ?, ?, ?, ?) RETURNING rowid", user.Id, date, typeStr, sets, reps).Scan(&rowId)
|
||||
if err != nil {
|
||||
utils.LogError("Could not insert workout", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
wo := workout.Workout{
|
||||
Id: strconv.Itoa(rowId),
|
||||
Date: renderDate(date),
|
||||
Type: r.FormValue("type"),
|
||||
Sets: r.FormValue("sets"),
|
||||
Reps: r.FormValue("reps"),
|
||||
}
|
||||
|
||||
err = workout.WorkoutItemComp(wo, true).Render(r.Context(), w)
|
||||
if err != nil {
|
||||
utils.LogError("Could not render workoutitem", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
func NewWorkoutDtoFromDb(workout *db.Workout) *WorkoutDto {
|
||||
return &WorkoutDto{
|
||||
RowId: strconv.Itoa(workout.RowId),
|
||||
Date: renderDate(workout.Date),
|
||||
Type: workout.Type,
|
||||
Sets: strconv.Itoa(workout.Sets),
|
||||
Reps: strconv.Itoa(workout.Reps),
|
||||
}
|
||||
}
|
||||
func NewWorkoutDto(rowId string, date string, workoutType string, sets string, reps string) *WorkoutDto {
|
||||
return &WorkoutDto{
|
||||
RowId: rowId,
|
||||
Date: date,
|
||||
Type: workoutType,
|
||||
Sets: sets,
|
||||
Reps: reps,
|
||||
}
|
||||
}
|
||||
|
||||
func HandleWorkoutGetComp(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := utils.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
var (
|
||||
ErrInputValues = errors.New("Invalid input values")
|
||||
)
|
||||
|
||||
rows, err := db.Query("SELECT rowid, date, type, sets, reps FROM workout WHERE user_id = ? ORDER BY date desc", user.Id)
|
||||
if err != nil {
|
||||
utils.LogError("Could not get workouts", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
func (service WorkoutServiceImpl) AddWorkout(user *User, workoutDto *WorkoutDto) (*WorkoutDto, error) {
|
||||
|
||||
var workouts = make([]workout.Workout, 0)
|
||||
for rows.Next() {
|
||||
var workout workout.Workout
|
||||
|
||||
err = rows.Scan(&workout.Id, &workout.Date, &workout.Type, &workout.Sets, &workout.Reps)
|
||||
if err != nil {
|
||||
utils.LogError("Could not scan workout", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
workout.Date, err = renderDateStr(workout.Date)
|
||||
if err != nil {
|
||||
utils.LogError("Could not render date", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
workouts = append(workouts, workout)
|
||||
}
|
||||
|
||||
workout.WorkoutListComp(workouts).Render(r.Context(), w)
|
||||
if workoutDto.Date == "" || workoutDto.Type == "" || workoutDto.Sets == "" || workoutDto.Reps == "" {
|
||||
return nil, ErrInputValues
|
||||
}
|
||||
|
||||
date, err := time.Parse("2006-01-02", workoutDto.Date)
|
||||
if err != nil {
|
||||
return nil, ErrInputValues
|
||||
}
|
||||
|
||||
sets, err := strconv.Atoi(workoutDto.Sets)
|
||||
if err != nil {
|
||||
return nil, ErrInputValues
|
||||
}
|
||||
|
||||
reps, err := strconv.Atoi(workoutDto.Reps)
|
||||
if err != nil {
|
||||
return nil, ErrInputValues
|
||||
}
|
||||
|
||||
workoutInsert := db.NewWorkoutInsert(date, workoutDto.Type, sets, reps)
|
||||
|
||||
workout, err := service.dbWorkout.InsertWorkout(user.Id, workoutInsert)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewWorkoutDtoFromDb(workout), nil
|
||||
}
|
||||
|
||||
func HandleWorkoutDeleteComp(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := utils.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
rowId := r.PathValue("id")
|
||||
if rowId == "" {
|
||||
http.Error(w, "Missing required fields", http.StatusBadRequest)
|
||||
slog.Warn("Missing required fields for workout delete")
|
||||
utils.TriggerToast(w, r, "error", "Missing ID field")
|
||||
return
|
||||
}
|
||||
|
||||
res, err := db.Exec("DELETE FROM workout WHERE user_id = ? AND rowid = ?", user.Id, rowId)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
utils.LogError("Could not delete workout", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
return
|
||||
}
|
||||
|
||||
rows, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
utils.LogError("Could not get rows affected", err)
|
||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||
return
|
||||
}
|
||||
|
||||
if rows == 0 {
|
||||
http.Error(w, "Not found", http.StatusNotFound)
|
||||
slog.Warn("Could not find workout to delete")
|
||||
utils.TriggerToast(w, r, "error", "Not found. Refresh the page.")
|
||||
return
|
||||
}
|
||||
func (service WorkoutServiceImpl) DeleteWorkout(user *User, rowId int) error {
|
||||
if user == nil {
|
||||
return types.ErrInternal
|
||||
}
|
||||
|
||||
return service.dbWorkout.DeleteWorkout(user.Id, rowId)
|
||||
}
|
||||
|
||||
func (service WorkoutServiceImpl) GetWorkouts(user *User) ([]*WorkoutDto, error) {
|
||||
if user == nil {
|
||||
return nil, types.ErrInternal
|
||||
}
|
||||
|
||||
workouts, err := service.dbWorkout.GetWorkouts(user.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// for _, workout := range workouts {
|
||||
// workout.Date = renderDate(workout.Date)
|
||||
// }
|
||||
|
||||
workoutsDto := make([]*WorkoutDto, len(workouts))
|
||||
for i, workout := range workouts {
|
||||
workoutsDto[i] = NewWorkoutDtoFromDb(&workout)
|
||||
}
|
||||
|
||||
return workoutsDto, nil
|
||||
}
|
||||
|
||||
func renderDateStr(date string) (string, error) {
|
||||
|
||||
Reference in New Issue
Block a user