fix: migrate sigin to testable code #181 #202
@@ -2,6 +2,11 @@ with-expecter: True
|
|||||||
dir: mocks/
|
dir: mocks/
|
||||||
outpkg: mocks
|
outpkg: mocks
|
||||||
packages:
|
packages:
|
||||||
|
me-fit/service:
|
||||||
|
interfaces:
|
||||||
|
RandomGenerator:
|
||||||
|
Clock:
|
||||||
|
MailService:
|
||||||
me-fit/db:
|
me-fit/db:
|
||||||
interfaces:
|
interfaces:
|
||||||
DbAuth:
|
DbAuth:
|
||||||
|
|||||||
52
db/auth.go
52
db/auth.go
@@ -6,6 +6,7 @@ import (
|
|||||||
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
@@ -13,6 +14,7 @@ import (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
ErrUserNotFound = errors.New("User not found")
|
ErrUserNotFound = errors.New("User not found")
|
||||||
|
ErrUserExists = errors.New("User already exists")
|
||||||
)
|
)
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
@@ -41,6 +43,10 @@ func NewUser(id uuid.UUID, email string, emailVerified bool, emailVerifiedAt *ti
|
|||||||
|
|
||||||
type DbAuth interface {
|
type DbAuth interface {
|
||||||
GetUser(email string) (*User, error)
|
GetUser(email string) (*User, error)
|
||||||
|
InsertUser(user *User) error
|
||||||
|
|
||||||
|
GetEmailVerificationToken(userId uuid.UUID) (string, error)
|
||||||
|
InsertEmailVerificationToken(userId uuid.UUID, token string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type DbAuthSqlite struct {
|
type DbAuthSqlite struct {
|
||||||
@@ -77,3 +83,49 @@ func (db DbAuthSqlite) GetUser(email string) (*User, error) {
|
|||||||
|
|
||||||
return NewUser(userId, email, emailVerified, emailVerifiedAt, isAdmin, password, salt, createdAt), nil
|
return NewUser(userId, email, emailVerified, emailVerifiedAt, isAdmin, password, salt, createdAt), nil
|
||||||
}
|
}
|
||||||
|
func (db DbAuthSqlite) InsertUser(user *User) error {
|
||||||
|
_, err := db.db.Exec(`
|
||||||
|
INSERT INTO user (user_uuid, email, email_verified, email_verified_at, is_admin, password, salt, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
user.Id, user.Email, user.EmailVerified, user.EmailVerifiedAt, user.IsAdmin, user.Password, user.Salt, user.CreateAt)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
if strings.Contains(err.Error(), "email") {
|
||||||
|
return ErrUserExists
|
||||||
|
}
|
||||||
|
|
||||||
|
utils.LogError("SQL error InsertUser", err)
|
||||||
|
return types.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db DbAuthSqlite) GetEmailVerificationToken(userId uuid.UUID) (string, error) {
|
||||||
|
var token string
|
||||||
|
|
||||||
|
err := db.db.QueryRow(`
|
||||||
|
SELECT token
|
||||||
|
FROM user_token
|
||||||
|
WHERE user_uuid = ?
|
||||||
|
AND type = 'email_verify'`, userId).Scan(&token)
|
||||||
|
|
||||||
|
if err != nil && err != sql.ErrNoRows {
|
||||||
|
utils.LogError("Could not get token", err)
|
||||||
|
return "", types.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
func (db DbAuthSqlite) InsertEmailVerificationToken(userId uuid.UUID, token string) error {
|
||||||
|
_, err := db.db.Exec(`
|
||||||
|
INSERT INTO user_token (user_uuid, type, token, created_at)
|
||||||
|
VALUES (?, 'email_verify', ?, datetime())`, userId, token)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
utils.LogError("Could not insert token", err)
|
||||||
|
return types.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,11 +4,11 @@ import (
|
|||||||
"me-fit/utils"
|
"me-fit/utils"
|
||||||
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func setupDb(t *testing.T) *sql.DB {
|
func setupDb(t *testing.T) *sql.DB {
|
||||||
@@ -16,6 +16,9 @@ func setupDb(t *testing.T) *sql.DB {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Error opening database: %v", err)
|
t.Fatalf("Error opening database: %v", err)
|
||||||
}
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
db.Close()
|
||||||
|
})
|
||||||
|
|
||||||
err = utils.RunMigrations(db, "../")
|
err = utils.RunMigrations(db, "../")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -25,26 +28,41 @@ func setupDb(t *testing.T) *sql.DB {
|
|||||||
return db
|
return db
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetUser(t *testing.T) {
|
func TestUser(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
t.Run("should return UserNotFound", func(t *testing.T) {
|
t.Run("should return UserNotFound", func(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
db := setupDb(t)
|
db := setupDb(t)
|
||||||
defer db.Close()
|
|
||||||
|
|
||||||
underTest := DbAuthSqlite{db: db}
|
underTest := DbAuthSqlite{db: db}
|
||||||
|
|
||||||
_, err := underTest.GetUser("someNonExistentEmail")
|
_, err := underTest.GetUser("someNonExistentEmail")
|
||||||
if err != ErrUserNotFound {
|
assert.Equal(t, ErrUserNotFound, err)
|
||||||
t.Errorf("Expected UserNotFound, got %v", err)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("should find user in database", func(t *testing.T) {
|
t.Run("should insert and get user", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
db := setupDb(t)
|
||||||
|
|
||||||
|
underTest := DbAuthSqlite{db: db}
|
||||||
|
|
||||||
|
verifiedAt := time.Date(2020, 1, 5, 13, 0, 0, 0, time.UTC)
|
||||||
|
createAt := time.Date(2020, 1, 5, 12, 0, 0, 0, time.UTC)
|
||||||
|
expected := NewUser(uuid.New(), "some@email.de", true, &verifiedAt, false, []byte("somePass"), []byte("someSalt"), createAt)
|
||||||
|
|
||||||
|
err := underTest.InsertUser(expected)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
actual, err := underTest.GetUser(expected.Email)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
assert.Equal(t, expected, actual)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("should throw error if user already exists", func(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
db := setupDb(t)
|
db := setupDb(t)
|
||||||
defer db.Close()
|
|
||||||
|
|
||||||
underTest := DbAuthSqlite{db: db}
|
underTest := DbAuthSqlite{db: db}
|
||||||
|
|
||||||
@@ -52,22 +70,43 @@ func TestGetUser(t *testing.T) {
|
|||||||
createAt := time.Date(2020, 1, 5, 12, 0, 0, 0, time.UTC)
|
createAt := time.Date(2020, 1, 5, 12, 0, 0, 0, time.UTC)
|
||||||
user := NewUser(uuid.New(), "some@email.de", true, &verifiedAt, false, []byte("somePass"), []byte("someSalt"), createAt)
|
user := NewUser(uuid.New(), "some@email.de", true, &verifiedAt, false, []byte("somePass"), []byte("someSalt"), createAt)
|
||||||
|
|
||||||
_, err := db.Exec(`
|
err := underTest.InsertUser(user)
|
||||||
INSERT INTO user (user_uuid, email, email_verified, email_verified_at, is_admin, password, salt, created_at)
|
assert.Nil(t, err)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
||||||
`, user.Id, user.Email, user.EmailVerified, user.EmailVerifiedAt, user.IsAdmin, user.Password, user.Salt, user.CreateAt)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Error inserting user: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
actual, err := underTest.GetUser(user.Email)
|
err = underTest.InsertUser(user)
|
||||||
if err != nil {
|
assert.Equal(t, ErrUserExists, err)
|
||||||
t.Fatalf("Error getting user: %v", err)
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if !reflect.DeepEqual(user, actual) {
|
func TestEmailVerification(t *testing.T) {
|
||||||
t.Errorf("Expected %v, got %v", user, actual)
|
t.Parallel()
|
||||||
}
|
|
||||||
|
t.Run("should return empty string if no token is safed", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
db := setupDb(t)
|
||||||
|
|
||||||
|
underTest := DbAuthSqlite{db: db}
|
||||||
|
|
||||||
|
token, err := underTest.GetEmailVerificationToken(uuid.New())
|
||||||
|
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, "", token)
|
||||||
|
})
|
||||||
|
t.Run("should insert and return token", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
db := setupDb(t)
|
||||||
|
|
||||||
|
underTest := DbAuthSqlite{db: db}
|
||||||
|
|
||||||
|
userId := uuid.New()
|
||||||
|
expectedToken := "someToken"
|
||||||
|
|
||||||
|
err := underTest.InsertEmailVerificationToken(userId, expectedToken)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
actualToken, err := underTest.GetEmailVerificationToken(userId)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
assert.Equal(t, expectedToken, actualToken)
|
||||||
})
|
})
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"me-fit/utils"
|
"me-fit/utils"
|
||||||
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -33,13 +34,13 @@ func NewHandlerAuth(db *sql.DB, service service.ServiceAuth, serverSettings *typ
|
|||||||
func (handler HandlerAuthImpl) handle(router *http.ServeMux) {
|
func (handler HandlerAuthImpl) handle(router *http.ServeMux) {
|
||||||
// Don't use auth middleware for these routes, as it makes redirecting very difficult, if the mail is not yet verified
|
// Don't use auth middleware for these routes, as it makes redirecting very difficult, if the mail is not yet verified
|
||||||
router.Handle("/auth/signin", handler.handleSignInPage())
|
router.Handle("/auth/signin", handler.handleSignInPage())
|
||||||
router.Handle("/auth/signup", service.HandleSignUpPage(handler.db, handler.serverSettings))
|
router.Handle("/auth/signup", handler.handleSignUpPage())
|
||||||
router.Handle("/auth/verify", service.HandleSignUpVerifyPage(handler.db, handler.serverSettings)) // Hint for the user to verify their email
|
router.Handle("/auth/verify", service.HandleSignUpVerifyPage(handler.db, handler.serverSettings)) // Hint for the user to verify their email
|
||||||
router.Handle("/auth/delete-account", service.HandleDeleteAccountPage(handler.db, handler.serverSettings))
|
router.Handle("/auth/delete-account", service.HandleDeleteAccountPage(handler.db, handler.serverSettings))
|
||||||
router.Handle("/auth/verify-email", service.HandleSignUpVerifyResponsePage(handler.db)) // The link contained in the email
|
router.Handle("/auth/verify-email", service.HandleSignUpVerifyResponsePage(handler.db)) // The link contained in the email
|
||||||
router.Handle("/auth/change-password", service.HandleChangePasswordPage(handler.db, handler.serverSettings))
|
router.Handle("/auth/change-password", service.HandleChangePasswordPage(handler.db, handler.serverSettings))
|
||||||
router.Handle("/auth/reset-password", service.HandleResetPasswordPage(handler.db, handler.serverSettings))
|
router.Handle("/auth/reset-password", service.HandleResetPasswordPage(handler.db, handler.serverSettings))
|
||||||
router.Handle("/api/auth/signup", service.HandleSignUpComp(handler.db, handler.serverSettings))
|
router.Handle("/api/auth/signup", handler.handleSignUp())
|
||||||
router.Handle("/api/auth/signin", handler.handleSignIn())
|
router.Handle("/api/auth/signin", handler.handleSignIn())
|
||||||
router.Handle("/api/auth/signout", service.HandleSignOutComp(handler.db))
|
router.Handle("/api/auth/signout", service.HandleSignOutComp(handler.db))
|
||||||
router.Handle("/api/auth/delete-account", service.HandleDeleteAccountComp(handler.db, handler.serverSettings))
|
router.Handle("/api/auth/delete-account", service.HandleDeleteAccountComp(handler.db, handler.serverSettings))
|
||||||
@@ -74,7 +75,6 @@ func (handler HandlerAuthImpl) handleSignInPage() http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (handler HandlerAuthImpl) handleSignIn() http.HandlerFunc {
|
func (handler HandlerAuthImpl) handleSignIn() http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user, err := utils.WaitMinimumTime(securityWaitDuration, func() (*service.User, error) {
|
user, err := utils.WaitMinimumTime(securityWaitDuration, func() (*service.User, error) {
|
||||||
@@ -112,3 +112,54 @@ func (handler HandlerAuthImpl) handleSignIn() http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (handler HandlerAuthImpl) handleSignUpPage() http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := utils.GetUserFromSession(handler.db, r)
|
||||||
|
|
||||||
|
if user == nil {
|
||||||
|
userComp := service.UserInfoComp(nil)
|
||||||
|
signUpComp := auth.SignInOrUpComp(false)
|
||||||
|
err := template.Layout(signUpComp, userComp, handler.serverSettings.Environment).Render(r.Context(), w)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
utils.LogError("Failed to render sign up page", err)
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if !user.EmailVerified {
|
||||||
|
utils.DoRedirect(w, r, "/auth/verify")
|
||||||
|
} else {
|
||||||
|
utils.DoRedirect(w, r, "/")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (handler HandlerAuthImpl) handleSignUp() http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var email = r.FormValue("email")
|
||||||
|
var password = r.FormValue("password")
|
||||||
|
|
||||||
|
_, err := utils.WaitMinimumTime(securityWaitDuration, func() (interface{}, error) {
|
||||||
|
user, err := handler.service.SignUp(email, password)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
go handler.service.SendVerificationMail(user.Id, user.Email)
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, types.ErrInternal) {
|
||||||
|
utils.TriggerToast(w, r, "error", "An error occurred")
|
||||||
|
return
|
||||||
|
} else if errors.Is(err, service.ErrInvalidEmail) {
|
||||||
|
utils.TriggerToast(w, r, "error", "The email provided is invalid")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// If the "service.ErrAccountExists", then just continue
|
||||||
|
}
|
||||||
|
|
||||||
|
utils.TriggerToast(w, r, "success", "A link to activate your account has been emailed to the address provided.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -15,7 +15,12 @@ func GetHandler(d *sql.DB, serverSettings *types.ServerSettings) http.Handler {
|
|||||||
|
|
||||||
router.HandleFunc("/", service.HandleIndexAnd404(d, serverSettings))
|
router.HandleFunc("/", service.HandleIndexAnd404(d, serverSettings))
|
||||||
|
|
||||||
handlerAuth := NewHandlerAuth(d, service.NewServiceAuthImpl(db.NewDbAuthSqlite(d)), serverSettings)
|
randomGenerator := service.NewRandomGeneratorImpl()
|
||||||
|
clock := service.NewClockImpl()
|
||||||
|
dbAuth := db.NewDbAuthSqlite(d)
|
||||||
|
mailService := service.NewMailServiceImpl(serverSettings)
|
||||||
|
serviceAuth := service.NewServiceAuthImpl(dbAuth, randomGenerator, clock, mailService, serverSettings)
|
||||||
|
handlerAuth := NewHandlerAuth(d, serviceAuth, serverSettings)
|
||||||
|
|
||||||
// Serve static files (CSS, JS and images)
|
// Serve static files (CSS, JS and images)
|
||||||
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
|
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
|
||||||
|
|||||||
222
service/auth.go
222
service/auth.go
@@ -2,7 +2,6 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/rand"
|
|
||||||
"crypto/subtle"
|
"crypto/subtle"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
@@ -26,7 +25,9 @@ import (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
ErrInvaidCredentials = errors.New("Invalid email or password")
|
ErrInvaidCredentials = errors.New("Invalid email or password")
|
||||||
ErrPasswordComplexity = errors.New("Password needs to be 8 characters long, contain at least one number, one special, one uppercase and one lowercase character")
|
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")
|
||||||
)
|
)
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
@@ -45,20 +46,29 @@ func NewUser(user *db.User) *User {
|
|||||||
|
|
||||||
type ServiceAuth interface {
|
type ServiceAuth interface {
|
||||||
SignIn(email string, password string) (*User, error)
|
SignIn(email string, password string) (*User, error)
|
||||||
|
SignUp(email string, password string) (*User, error)
|
||||||
|
SendVerificationMail(userId uuid.UUID, email string)
|
||||||
}
|
}
|
||||||
|
|
||||||
type ServiceAuthImpl struct {
|
type ServiceAuthImpl struct {
|
||||||
dbAuth db.DbAuth
|
dbAuth db.DbAuth
|
||||||
|
randomGenerator RandomGenerator
|
||||||
|
clock Clock
|
||||||
|
mailService MailService
|
||||||
|
serverSettings *types.ServerSettings
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewServiceAuthImpl(dbAuth db.DbAuth) *ServiceAuthImpl {
|
func NewServiceAuthImpl(dbAuth db.DbAuth, randomGenerator RandomGenerator, clock Clock, mailService MailService, serverSettings *types.ServerSettings) *ServiceAuthImpl {
|
||||||
return &ServiceAuthImpl{
|
return &ServiceAuthImpl{
|
||||||
dbAuth: dbAuth,
|
dbAuth: dbAuth,
|
||||||
|
randomGenerator: randomGenerator,
|
||||||
|
clock: clock,
|
||||||
|
mailService: mailService,
|
||||||
|
serverSettings: serverSettings,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (service ServiceAuthImpl) SignIn(email string, password string) (*User, error) {
|
func (service ServiceAuthImpl) SignIn(email string, password string) (*User, error) {
|
||||||
|
|
||||||
user, err := service.dbAuth.GetUser(email)
|
user, err := service.dbAuth.GetUser(email)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, db.ErrUserNotFound) {
|
if errors.Is(err, db.ErrUserNotFound) {
|
||||||
@@ -77,30 +87,74 @@ func (service ServiceAuthImpl) SignIn(email string, password string) (*User, err
|
|||||||
return NewUser(user), nil
|
return NewUser(user), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO
|
func (service ServiceAuthImpl) SignUp(email string, password string) (*User, error) {
|
||||||
|
_, err := mail.ParseAddress(email)
|
||||||
func HandleSignUpPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
user := utils.GetUserFromSession(db, r)
|
|
||||||
|
|
||||||
if user == nil {
|
|
||||||
userComp := UserInfoComp(nil)
|
|
||||||
signUpComp := auth.SignInOrUpComp(false)
|
|
||||||
err := template.Layout(signUpComp, userComp, serverSettings.Environment).Render(r.Context(), w)
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Failed to render sign up page", err)
|
return nil, ErrInvalidEmail
|
||||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if !user.EmailVerified {
|
if !isPasswordValid(password) {
|
||||||
utils.DoRedirect(w, r, "/auth/verify")
|
return nil, ErrInvalidPassword
|
||||||
|
}
|
||||||
|
|
||||||
|
userId, err := service.randomGenerator.UUID()
|
||||||
|
if err != nil {
|
||||||
|
return nil, types.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
salt, err := service.randomGenerator.Bytes(16)
|
||||||
|
if err != nil {
|
||||||
|
return nil, types.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
hash := GetHashPassword(password, salt)
|
||||||
|
|
||||||
|
dbUser := db.NewUser(userId, email, false, nil, false, hash, salt, service.clock.Now())
|
||||||
|
|
||||||
|
err = service.dbAuth.InsertUser(dbUser)
|
||||||
|
if err != nil {
|
||||||
|
if err == db.ErrUserExists {
|
||||||
|
return nil, ErrAccountExists
|
||||||
} else {
|
} else {
|
||||||
utils.DoRedirect(w, r, "/")
|
return nil, types.ErrInternal
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return NewUser(dbUser), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (service ServiceAuthImpl) SendVerificationMail(userId uuid.UUID, email string) {
|
||||||
|
var token string
|
||||||
|
|
||||||
|
token, err := service.dbAuth.GetEmailVerificationToken(userId)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if token == "" {
|
||||||
|
token, err := service.randomGenerator.String(32)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = service.dbAuth.InsertEmailVerificationToken(userId, token)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var w strings.Builder
|
||||||
|
err = tempMail.Register(service.serverSettings.BaseUrl, token).Render(context.Background(), &w)
|
||||||
|
if err != nil {
|
||||||
|
utils.LogError("Could not render welcome email", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
service.mailService.SendMail(email, "Welcome to ME-FIT", w.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO
|
||||||
|
|
||||||
func HandleSignUpVerifyPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
func HandleSignUpVerifyPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
@@ -227,69 +281,6 @@ func UserInfoComp(user *types.User) templ.Component {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleSignUpComp(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var email = r.FormValue("email")
|
|
||||||
var password = r.FormValue("password")
|
|
||||||
|
|
||||||
_, err := mail.ParseAddress(email)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Invalid email", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err = checkPassword(password)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
userId, err := uuid.NewRandom()
|
|
||||||
if err != nil {
|
|
||||||
utils.LogError("Could not generate UUID", err)
|
|
||||||
auth.Error("Internal Server Error").Render(r.Context(), w)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
salt := make([]byte, 16)
|
|
||||||
_, err = rand.Read(salt)
|
|
||||||
if err != nil {
|
|
||||||
utils.LogError("Could not generate salt", err)
|
|
||||||
auth.Error("Internal Server Error").Render(r.Context(), w)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
hash := GetHashPassword(password, salt)
|
|
||||||
|
|
||||||
_, err = db.Exec("INSERT INTO user (user_uuid, email, email_verified, is_admin, password, salt, created_at) VALUES (?, ?, FALSE, FALSE, ?, ?, datetime())", userId, email, hash, salt)
|
|
||||||
if err != nil {
|
|
||||||
// This does leak information about the email being in use, though not specifically stated
|
|
||||||
// It needs to be refacoteres to "If the email is not already in use, an email has been send to your address", or something
|
|
||||||
// The happy path, currently a redirect, needs to send the same message!
|
|
||||||
// Then it is also important to have the same compute time in both paths
|
|
||||||
// Otherwise an attacker could guess emails when comparing the response time
|
|
||||||
if strings.Contains(err.Error(), "email") {
|
|
||||||
auth.Error("Bad Request").Render(r.Context(), w)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
utils.LogError("Could not insert user", err)
|
|
||||||
auth.Error("Internal Server Error").Render(r.Context(), w)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err = TryCreateSessionAndSetCookie(r, w, db, userId)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send verification email as a goroutine
|
|
||||||
go sendVerificationEmail(db, userId.String(), email, serverSettings)
|
|
||||||
|
|
||||||
utils.DoRedirect(w, r, "/auth/verify")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func HandleSignOutComp(db *sql.DB) http.HandlerFunc {
|
func HandleSignOutComp(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
@@ -320,7 +311,7 @@ func HandleSignOutComp(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func HandleDeleteAccountComp(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
func HandleDeleteAccountComp(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
mailService := NewMailService(serverSettings)
|
mailService := NewMailServiceImpl(serverSettings)
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
@@ -394,7 +385,8 @@ func HandleVerifyResendComp(db *sql.DB, serverSettings *types.ServerSettings) ht
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
go sendVerificationEmail(db, user.Id.String(), user.Email, serverSettings)
|
// TODO
|
||||||
|
// go sendVerificationEmail(db, user.Id.String(), user.Email, serverSettings)
|
||||||
|
|
||||||
w.Write([]byte("<p class=\"mt-8\">Verification email sent</p>"))
|
w.Write([]byte("<p class=\"mt-8\">Verification email sent</p>"))
|
||||||
}
|
}
|
||||||
@@ -412,9 +404,8 @@ func HandleChangePasswordComp(db *sql.DB) http.HandlerFunc {
|
|||||||
currPass := r.FormValue("current-password")
|
currPass := r.FormValue("current-password")
|
||||||
newPass := r.FormValue("new-password")
|
newPass := r.FormValue("new-password")
|
||||||
|
|
||||||
err := checkPassword(newPass)
|
if !isPasswordValid(newPass) {
|
||||||
if err != nil {
|
utils.TriggerToast(w, r, "error", ErrInvalidPassword.Error())
|
||||||
utils.TriggerToast(w, r, "error", err.Error())
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -428,7 +419,7 @@ func HandleChangePasswordComp(db *sql.DB) http.HandlerFunc {
|
|||||||
salt []byte
|
salt []byte
|
||||||
)
|
)
|
||||||
|
|
||||||
err = db.QueryRow("SELECT password, salt FROM user WHERE user_uuid = ?", user.Id).Scan(&storedHash, &salt)
|
err := db.QueryRow("SELECT password, salt FROM user WHERE user_uuid = ?", user.Id).Scan(&storedHash, &salt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Could not get password", err)
|
utils.LogError("Could not get password", err)
|
||||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||||
@@ -472,9 +463,8 @@ func HandleActualResetPasswordComp(db *sql.DB) http.HandlerFunc {
|
|||||||
|
|
||||||
newPass := r.FormValue("new-password")
|
newPass := r.FormValue("new-password")
|
||||||
|
|
||||||
err = checkPassword(newPass)
|
if !isPasswordValid(newPass) {
|
||||||
if err != nil {
|
utils.TriggerToast(w, r, "error", ErrInvalidPassword.Error())
|
||||||
utils.TriggerToast(w, r, "error", err.Error())
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -516,8 +506,9 @@ func HandleActualResetPasswordComp(db *sql.DB) http.HandlerFunc {
|
|||||||
utils.TriggerToast(w, r, "success", "Password changed")
|
utils.TriggerToast(w, r, "success", "Password changed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleResetPasswordComp(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
func HandleResetPasswordComp(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
mailService := NewMailService(serverSettings)
|
mailService := NewMailServiceImpl(serverSettings)
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
email := r.FormValue("email")
|
email := r.FormValue("email")
|
||||||
@@ -526,9 +517,8 @@ func HandleResetPasswordComp(db *sql.DB, serverSettings *types.ServerSettings) h
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
token, err := utils.RandomToken()
|
token, err := NewRandomGeneratorImpl().String(32)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Could not generate token", err)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -566,43 +556,9 @@ func HandleResetPasswordComp(db *sql.DB, serverSettings *types.ServerSettings) h
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func sendVerificationEmail(db *sql.DB, userId string, email string, serverSettings *types.ServerSettings) {
|
|
||||||
|
|
||||||
var token string
|
|
||||||
err := db.QueryRow("SELECT token FROM user_token WHERE user_uuid = ? AND type = 'email_verify'", userId).Scan(&token)
|
|
||||||
if err != nil && err != sql.ErrNoRows {
|
|
||||||
utils.LogError("Could not get token", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if token == "" {
|
|
||||||
token, err := utils.RandomToken()
|
|
||||||
if err != nil {
|
|
||||||
utils.LogError("Could not generate token", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = db.Exec("INSERT INTO user_token (user_uuid, type, token, created_at) VALUES (?, 'email_verify', ?, datetime())", userId, token)
|
|
||||||
if err != nil {
|
|
||||||
utils.LogError("Could not insert token", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var w strings.Builder
|
|
||||||
err = tempMail.Register(serverSettings.BaseUrl, token).Render(context.Background(), &w)
|
|
||||||
if err != nil {
|
|
||||||
utils.LogError("Could not render welcome email", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mailService := NewMailService(serverSettings)
|
|
||||||
mailService.SendMail(email, "Welcome to ME-FIT", w.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
func TryCreateSessionAndSetCookie(r *http.Request, w http.ResponseWriter, db *sql.DB, user_uuid uuid.UUID) error {
|
func TryCreateSessionAndSetCookie(r *http.Request, w http.ResponseWriter, db *sql.DB, user_uuid uuid.UUID) error {
|
||||||
sessionId, err := utils.RandomToken()
|
sessionId, err := NewRandomGeneratorImpl().String(32)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Could not generate session ID", err)
|
|
||||||
return types.ErrInternal
|
return types.ErrInternal
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -637,15 +593,15 @@ func GetHashPassword(password string, salt []byte) []byte {
|
|||||||
return argon2.IDKey([]byte(password), salt, 1, 64*1024, 1, 16)
|
return argon2.IDKey([]byte(password), salt, 1, 64*1024, 1, 16)
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkPassword(password string) error {
|
func isPasswordValid(password string) bool {
|
||||||
|
|
||||||
if len(password) < 8 ||
|
if len(password) < 8 ||
|
||||||
!strings.ContainsAny(password, "0123456789") ||
|
!strings.ContainsAny(password, "0123456789") ||
|
||||||
!strings.ContainsAny(password, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") ||
|
!strings.ContainsAny(password, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") ||
|
||||||
!strings.ContainsAny(password, "abcdefghijklmnopqrstuvwxyz") ||
|
!strings.ContainsAny(password, "abcdefghijklmnopqrstuvwxyz") ||
|
||||||
!strings.ContainsAny(password, "!@#$%^&*()_+-=[]{}\\|;:'\",.<>/?") {
|
!strings.ContainsAny(password, "!@#$%^&*()_+-=[]{}\\|;:'\",.<>/?") {
|
||||||
return ErrPasswordComplexity
|
return false
|
||||||
} else {
|
} else {
|
||||||
return nil
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,23 +2,26 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"me-fit/db"
|
"me-fit/db"
|
||||||
m "me-fit/mocks"
|
"me-fit/mocks"
|
||||||
"me-fit/types"
|
"me-fit/types"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"errors"
|
"errors"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/mock"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSignIn(t *testing.T) {
|
func TestSignIn(t *testing.T) {
|
||||||
|
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
t.Run("should return user if password is correct", func(t *testing.T) {
|
t.Run("should return user if password is correct", func(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
salt := []byte("salt")
|
salt := []byte("salt")
|
||||||
verifiedAt := time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC)
|
verifiedAt := time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
user := db.NewUser(
|
user := db.NewUser(
|
||||||
uuid.New(),
|
uuid.New(),
|
||||||
"test@test.de",
|
"test@test.de",
|
||||||
@@ -30,30 +33,31 @@ func TestSignIn(t *testing.T) {
|
|||||||
time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
|
time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||||
)
|
)
|
||||||
|
|
||||||
mockDbAuth := m.NewMockDbAuth(t)
|
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||||
mockDbAuth.EXPECT().GetUser("test@test.de").Return(user, nil)
|
mockDbAuth.EXPECT().GetUser("test@test.de").Return(user, nil)
|
||||||
|
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||||
|
mockClock := mocks.NewMockClock(t)
|
||||||
|
mockMail := mocks.NewMockMailService(t)
|
||||||
|
|
||||||
underTest := NewServiceAuthImpl(mockDbAuth)
|
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||||
|
|
||||||
actualUser, err := underTest.SignIn(user.Email, "password")
|
actualUser, err := underTest.SignIn(user.Email, "password")
|
||||||
if err != nil {
|
assert.Nil(t, err)
|
||||||
t.Errorf("Expected nil, got %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
expectedUser := User{
|
expectedUser := User{
|
||||||
Id: user.Id,
|
Id: user.Id,
|
||||||
Email: user.Email,
|
Email: user.Email,
|
||||||
EmailVerified: user.EmailVerified,
|
EmailVerified: user.EmailVerified,
|
||||||
}
|
}
|
||||||
if *actualUser != expectedUser {
|
|
||||||
t.Errorf("Expected %v, got %v", expectedUser, actualUser)
|
assert.Equal(t, expectedUser, *actualUser)
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("should return ErrInvalidCretentials if password is not correct", func(t *testing.T) {
|
t.Run("should return ErrInvalidCretentials if password is not correct", func(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
salt := []byte("salt")
|
salt := []byte("salt")
|
||||||
verifiedAt := time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC)
|
verifiedAt := time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
user := db.NewUser(
|
user := db.NewUser(
|
||||||
uuid.New(),
|
uuid.New(),
|
||||||
"test@test.de",
|
"test@test.de",
|
||||||
@@ -65,38 +69,178 @@ func TestSignIn(t *testing.T) {
|
|||||||
time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
|
time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||||
)
|
)
|
||||||
|
|
||||||
mockDbAuth := m.NewMockDbAuth(t)
|
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||||
mockDbAuth.EXPECT().GetUser(user.Email).Return(user, nil)
|
mockDbAuth.EXPECT().GetUser(user.Email).Return(user, nil)
|
||||||
|
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||||
|
mockClock := mocks.NewMockClock(t)
|
||||||
|
mockMail := mocks.NewMockMailService(t)
|
||||||
|
|
||||||
underTest := NewServiceAuthImpl(mockDbAuth)
|
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||||
|
|
||||||
_, err := underTest.SignIn("test@test.de", "wrong password")
|
_, err := underTest.SignIn("test@test.de", "wrong password")
|
||||||
if err != ErrInvaidCredentials {
|
|
||||||
t.Errorf("Expected %v, got %v", ErrInvaidCredentials, err)
|
assert.Equal(t, ErrInvaidCredentials, err)
|
||||||
}
|
|
||||||
})
|
})
|
||||||
t.Run("should return ErrInvalidCretentials if user has not been found", func(t *testing.T) {
|
t.Run("should return ErrInvalidCretentials if user has not been found", func(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
mockDbAuth := m.NewMockDbAuth(t)
|
|
||||||
mockDbAuth.EXPECT().GetUser("test").Return(nil, db.ErrUserNotFound)
|
|
||||||
|
|
||||||
underTest := NewServiceAuthImpl(mockDbAuth)
|
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||||
|
mockDbAuth.EXPECT().GetUser("test").Return(nil, db.ErrUserNotFound)
|
||||||
|
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||||
|
mockClock := mocks.NewMockClock(t)
|
||||||
|
mockMail := mocks.NewMockMailService(t)
|
||||||
|
|
||||||
|
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||||
|
|
||||||
_, err := underTest.SignIn("test", "test")
|
_, err := underTest.SignIn("test", "test")
|
||||||
if err != ErrInvaidCredentials {
|
assert.Equal(t, ErrInvaidCredentials, err)
|
||||||
t.Errorf("Expected %v, got %v", ErrInvaidCredentials, err)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
t.Run("should forward ErrInternal on any other error", func(t *testing.T) {
|
t.Run("should forward ErrInternal on any other error", func(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
mockDbAuth := m.NewMockDbAuth(t)
|
|
||||||
mockDbAuth.EXPECT().GetUser("test").Return(nil, errors.New("Some error"))
|
|
||||||
|
|
||||||
underTest := NewServiceAuthImpl(mockDbAuth)
|
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||||
|
mockDbAuth.EXPECT().GetUser("test").Return(nil, errors.New("Some undefined error"))
|
||||||
|
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||||
|
mockClock := mocks.NewMockClock(t)
|
||||||
|
mockMail := mocks.NewMockMailService(t)
|
||||||
|
|
||||||
|
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||||
|
|
||||||
_, err := underTest.SignIn("test", "test")
|
_, err := underTest.SignIn("test", "test")
|
||||||
if err != types.ErrInternal {
|
|
||||||
t.Errorf("Expected %v, got %v", types.ErrInternal, err)
|
assert.Equal(t, types.ErrInternal, err)
|
||||||
}
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSignUp(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
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)
|
||||||
|
mockMail := mocks.NewMockMailService(t)
|
||||||
|
|
||||||
|
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||||
|
|
||||||
|
_, err := underTest.SignUp("invalid email address", "SomeStrongPassword123!")
|
||||||
|
|
||||||
|
assert.Equal(t, ErrInvalidEmail, err)
|
||||||
|
})
|
||||||
|
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)
|
||||||
|
mockMail := mocks.NewMockMailService(t)
|
||||||
|
|
||||||
|
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||||
|
|
||||||
|
weakPasswords := []string{
|
||||||
|
"123!ab", // too short
|
||||||
|
"no_upper_case_123",
|
||||||
|
"NO_LOWER_CASE_123",
|
||||||
|
"noSpecialChar123",
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, password := range weakPasswords {
|
||||||
|
_, err := underTest.SignUp("some@valid.email", password)
|
||||||
|
assert.Equal(t, ErrInvalidPassword, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("should signup correctly", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||||
|
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||||
|
mockClock := mocks.NewMockClock(t)
|
||||||
|
mockMail := mocks.NewMockMailService(t)
|
||||||
|
|
||||||
|
expected := User{
|
||||||
|
Id: uuid.New(),
|
||||||
|
Email: "some@valid.email",
|
||||||
|
EmailVerified: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
random := NewRandomGeneratorImpl()
|
||||||
|
salt, err := random.Bytes(16)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
password := "SomeStrongPassword123!"
|
||||||
|
|
||||||
|
mockRandom.EXPECT().UUID().Return(expected.Id, nil)
|
||||||
|
mockRandom.EXPECT().Bytes(16).Return(salt, nil)
|
||||||
|
|
||||||
|
createTime := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
mockClock.EXPECT().Now().Return(createTime)
|
||||||
|
|
||||||
|
mockDbAuth.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{})
|
||||||
|
|
||||||
|
actual, err := underTest.SignUp(expected.Email, password)
|
||||||
|
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
assert.Equal(t, expected, *actual)
|
||||||
|
})
|
||||||
|
t.Run("should return ErrAccountExists", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||||
|
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||||
|
mockClock := mocks.NewMockClock(t)
|
||||||
|
mockMail := mocks.NewMockMailService(t)
|
||||||
|
|
||||||
|
user := User{
|
||||||
|
Id: uuid.New(),
|
||||||
|
Email: "some@valid.email",
|
||||||
|
}
|
||||||
|
|
||||||
|
random := NewRandomGeneratorImpl()
|
||||||
|
salt, err := random.Bytes(16)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
password := "SomeStrongPassword123!"
|
||||||
|
|
||||||
|
mockRandom.EXPECT().UUID().Return(user.Id, nil)
|
||||||
|
mockRandom.EXPECT().Bytes(16).Return(salt, nil)
|
||||||
|
|
||||||
|
createTime := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
underTest := NewServiceAuthImpl(mockDbAuth, mockRandom, mockClock, mockMail, &types.ServerSettings{})
|
||||||
|
|
||||||
|
_, err = underTest.SignUp(user.Email, password)
|
||||||
|
assert.Equal(t, ErrAccountExists, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSendVerificationMail(t *testing.T) {
|
||||||
|
|
||||||
|
t.Parallel()
|
||||||
|
t.Run("should use stored token and send mail", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
token := "someRandomTokenToUse"
|
||||||
|
email := "some@email.de"
|
||||||
|
userId := uuid.New()
|
||||||
|
|
||||||
|
mockDbAuth := mocks.NewMockDbAuth(t)
|
||||||
|
mockRandom := mocks.NewMockRandomGenerator(t)
|
||||||
|
mockClock := mocks.NewMockClock(t)
|
||||||
|
mockMail := mocks.NewMockMailService(t)
|
||||||
|
|
||||||
|
mockDbAuth.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.SendVerificationMail(userId, email)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
17
service/clock.go
Normal file
17
service/clock.go
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type Clock interface {
|
||||||
|
Now() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type ClockImpl struct{}
|
||||||
|
|
||||||
|
func NewClockImpl() Clock {
|
||||||
|
return &ClockImpl{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ClockImpl) Now() time.Time {
|
||||||
|
return time.Now()
|
||||||
|
}
|
||||||
@@ -6,15 +6,19 @@ import (
|
|||||||
"net/smtp"
|
"net/smtp"
|
||||||
)
|
)
|
||||||
|
|
||||||
type MailService struct {
|
type MailService interface {
|
||||||
|
SendMail(to string, subject string, message string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type MailServiceImpl struct {
|
||||||
serverSettings *types.ServerSettings
|
serverSettings *types.ServerSettings
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMailService(serverSettings *types.ServerSettings) MailService {
|
func NewMailServiceImpl(serverSettings *types.ServerSettings) MailServiceImpl {
|
||||||
return MailService{serverSettings: serverSettings}
|
return MailServiceImpl{serverSettings: serverSettings}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m MailService) SendMail(to string, subject string, message string) error {
|
func (m MailServiceImpl) SendMail(to string, subject string, message string) error {
|
||||||
if m.serverSettings.Smtp == nil {
|
if m.serverSettings.Smtp == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
48
service/random_generator.go
Normal file
48
service/random_generator.go
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"me-fit/types"
|
||||||
|
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/base64"
|
||||||
|
"log/slog"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RandomGenerator interface {
|
||||||
|
Bytes(size int) ([]byte, error)
|
||||||
|
String(size int) (string, error)
|
||||||
|
UUID() (uuid.UUID, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type RandomGeneratorImpl struct {
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRandomGeneratorImpl() *RandomGeneratorImpl {
|
||||||
|
return &RandomGeneratorImpl{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RandomGeneratorImpl) Bytes(size int) ([]byte, error) {
|
||||||
|
b := make([]byte, 32)
|
||||||
|
_, err := rand.Read(b)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Error generating random bytes: " + err.Error())
|
||||||
|
return []byte{}, types.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
return b, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RandomGeneratorImpl) String(size int) (string, error) {
|
||||||
|
bytes, err := r.Bytes(size)
|
||||||
|
if err != nil {
|
||||||
|
return "", types.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
return base64.StdEncoding.EncodeToString(bytes), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RandomGeneratorImpl) UUID() (uuid.UUID, error) {
|
||||||
|
return uuid.NewRandom()
|
||||||
|
}
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"encoding/base64"
|
|
||||||
)
|
|
||||||
|
|
||||||
func RandomToken() (string, error) {
|
|
||||||
b := make([]byte, 32)
|
|
||||||
_, err := rand.Read(b)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return base64.StdEncoding.EncodeToString(b), nil
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user