From b7e5db5228061173225d6215d2b0effbcc05ef61 Mon Sep 17 00:00:00 2001 From: Rob Archibald Date: Fri, 20 Jan 2017 10:01:38 -0800 Subject: [PATCH] Numerous renames to fix exports --- auth.go | 71 -------------- authStore.go | 30 +++--- authStore_test.go | 78 ++++++++-------- auth_test.go | 149 ------------------------------ backend.go | 102 ++++++++++----------- backendDbUser.go | 16 ++-- backendLDAPLogin.go | 14 +-- backendLDAPLogin_test.go | 2 +- backendMemory.go | 68 +++++++------- backendMemory_test.go | 66 ++++++------- backendRedisSession.go | 56 ++++++------ backendRedisSession_test.go | 16 ++-- backend_test.go | 126 ++++++++++++------------- cookieStore.go | 178 ++++++++++++++++++------------------ cookieStore_test.go | 6 +- loginStore.go | 16 ++-- loginStore_test.go | 30 +++--- mailer.go | 6 +- mailer_test.go | 2 +- nginxauth.go | 78 ++++++++++++++-- nginxauth_test.go | 144 +++++++++++++++++++++++++++++ sessionStore.go | 22 ++--- sessionStore_test.go | 38 ++++---- 23 files changed, 651 insertions(+), 663 deletions(-) delete mode 100644 auth.go delete mode 100644 auth_test.go diff --git a/auth.go b/auth.go deleted file mode 100644 index b60aad1..0000000 --- a/auth.go +++ /dev/null @@ -1,71 +0,0 @@ -package main - -import ( - "fmt" - "net/http" -) - -// move together with nginxauth.go -func auth(authStore AuthStorer, w http.ResponseWriter, r *http.Request) { - session, err := authStore.GetSession() - if err != nil { - http.Error(w, "Authentication required: "+err.Error(), http.StatusUnauthorized) - if a, ok := err.(*AuthError); ok { - fmt.Println(a.Trace()) - } - } else { - addUserHeader(session, w) - } -} - -func authBasic(authStore AuthStorer, w http.ResponseWriter, r *http.Request) { - session, err := authStore.GetBasicAuth() - if err != nil { - w.Header().Set("WWW-Authenticate", "Basic realm='Endfirst.com'") - http.Error(w, "Authentication required: "+err.Error(), http.StatusUnauthorized) - } else { - addUserHeader(session, w) - } -} - -func login(authStore AuthStorer, w http.ResponseWriter, r *http.Request) { - run(authStore.Login, w) -} - -func register(authStore AuthStorer, w http.ResponseWriter, r *http.Request) { - run(authStore.Register, w) -} - -func createProfile(authStore AuthStorer, w http.ResponseWriter, r *http.Request) { - run(authStore.CreateProfile, w) -} - -func updateEmail(authStore AuthStorer, w http.ResponseWriter, r *http.Request) { - run(authStore.UpdateEmail, w) -} - -func updatePassword(authStore AuthStorer, w http.ResponseWriter, r *http.Request) { - run(authStore.UpdatePassword, w) -} - -func verifyEmail(authStore AuthStorer, w http.ResponseWriter, r *http.Request) { - run(authStore.VerifyEmail, w) -} - -func run(method func() error, w http.ResponseWriter) { - err := method() - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - if a, ok := err.(*AuthError); ok { - fmt.Println(a.Trace()) - } - } else { - w.Header().Add("Access-Control-Allow-Origin", "*") - w.Header().Add("Content-Type", "application/javascript") - fmt.Fprint(w, "{ \"result\": \"Success\" }") - } -} - -func addUserHeader(session *UserLoginSession, w http.ResponseWriter) { - w.Header().Add("X-User", session.Email) -} diff --git a/authStore.go b/authStore.go index fda7cf8..e2ec66f 100644 --- a/authStore.go +++ b/authStore.go @@ -13,9 +13,9 @@ import ( "time" ) -type AuthStorer interface { - GetSession() (*UserLoginSession, error) - GetBasicAuth() (*UserLoginSession, error) +type authStorer interface { + GetSession() (*loginSession, error) + GetBasicAuth() (*loginSession, error) Login() error Register() error CreateProfile() error @@ -30,27 +30,27 @@ type emailCookie struct { } type authStore struct { - backend Backender - sessionStore SessionStorer - loginStore LoginStorer - mailer Mailer - cookieStore CookieStorer + backend backender + sessionStore sessionStorer + loginStore loginStorer + mailer mailer + cookieStore cookieStorer r *http.Request } var emailRegex = regexp.MustCompile(`^(?i)[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$`) -func NewAuthStore(b Backender, mailer Mailer, w http.ResponseWriter, r *http.Request, customPrefix string, cookieKey []byte, secureOnlyCookie bool) AuthStorer { - sessionStore := NewSessionStore(b, w, r, customPrefix, cookieKey, secureOnlyCookie) - loginStore := NewLoginStore(b, mailer) - return &authStore{b, sessionStore, loginStore, mailer, NewCookieStore(w, r, cookieKey, secureOnlyCookie), r} +func newAuthStore(b backender, mailer mailer, w http.ResponseWriter, r *http.Request, customPrefix string, cookieKey []byte, secureOnlyCookie bool) authStorer { + sessionStore := newSessionStore(b, w, r, customPrefix, cookieKey, secureOnlyCookie) + loginStore := newLoginStore(b, mailer) + return &authStore{b, sessionStore, loginStore, mailer, newCookieStore(w, r, cookieKey, secureOnlyCookie), r} } -func (s *authStore) GetSession() (*UserLoginSession, error) { +func (s *authStore) GetSession() (*loginSession, error) { return s.sessionStore.GetSession() } -func (s *authStore) GetBasicAuth() (*UserLoginSession, error) { +func (s *authStore) GetBasicAuth() (*loginSession, error) { session, err := s.GetSession() if err == nil { return session, nil @@ -75,7 +75,7 @@ func (s *authStore) Login() error { return err } -func (s *authStore) login(email, password string, rememberMe bool) (*UserLoginSession, error) { +func (s *authStore) login(email, password string, rememberMe bool) (*loginSession, error) { _, err := s.loginStore.Login(email, password, rememberMe) if err != nil { return nil, err diff --git a/authStore_test.go b/authStore_test.go index 59aa00d..79c0dbe 100644 --- a/authStore_test.go +++ b/authStore_test.go @@ -17,27 +17,27 @@ import ( var futureTime = time.Now().Add(5 * time.Minute) var pastTime = time.Now().Add(-5 * time.Minute) -func getAuthStore(sessionReturn *SessionReturn, loginReturn *LoginReturn, emailCookieToReturn *emailCookie, hasCookieGetError, hasCookiePutError bool, mailErr error, backend *MockBackend) *authStore { +func getAuthStore(sessionReturn *SessionReturn, loginReturn *LoginReturn, emailCookieToReturn *emailCookie, hasCookieGetError, hasCookiePutError bool, mailErr error, backend *mockBackend) *authStore { r := &http.Request{} cookieStore := NewMockCookieStore(map[string]interface{}{emailCookieName: emailCookieToReturn}, hasCookieGetError, hasCookiePutError) - sessionStore := MockSessionStore{SessionReturn: sessionReturn} - loginStore := MockLoginStore{LoginReturn: loginReturn} + sessionStore := mockSessionStore{SessionReturn: sessionReturn} + loginStore := mockLoginStore{LoginReturn: loginReturn} return &authStore{backend, &sessionStore, &loginStore, &TextMailer{Err: mailErr}, cookieStore, r} } func TestNewAuthStore(t *testing.T) { w := httptest.NewRecorder() r := &http.Request{} - b := &MockBackend{} + b := &mockBackend{} m := &TextMailer{} - actual := NewAuthStore(b, m, w, r, "prefix", cookieKey, false).(*authStore) + actual := newAuthStore(b, m, w, r, "prefix", cookieKey, false).(*authStore) if actual.backend != b || actual.cookieStore.(*cookieStore).w != w || actual.cookieStore.(*cookieStore).r != r { t.Fatal("expected correct init") } } func TestAuthGetSession(t *testing.T) { - store := getAuthStore(sessionErr(), nil, nil, false, false, nil, &MockBackend{}) + store := getAuthStore(sessionErr(), nil, nil, false, false, nil, &mockBackend{}) if _, err := store.GetSession(); err == nil { t.Error("expected error") } @@ -45,19 +45,19 @@ func TestAuthGetSession(t *testing.T) { func TestAuthGetBasicAuth(t *testing.T) { // loginStore.LoginBasic error - store := getAuthStore(sessionErr(), loginErr(), nil, false, false, nil, &MockBackend{}) + store := getAuthStore(sessionErr(), loginErr(), nil, false, false, nil, &mockBackend{}) if _, err := store.GetBasicAuth(); err == nil { t.Error("expected error") } // createSession error - store = getAuthStore(sessionErr(), loginSuccess(), nil, false, false, nil, &MockBackend{}) + store = getAuthStore(sessionErr(), loginSuccess(), nil, false, false, nil, &mockBackend{}) if _, err := store.GetBasicAuth(); err == nil { t.Error("expected error") } // found session - store = getAuthStore(sessionSuccess(futureTime, futureTime), nil, nil, false, false, nil, &MockBackend{}) + store = getAuthStore(sessionSuccess(futureTime, futureTime), nil, nil, false, false, nil, &mockBackend{}) if _, err := store.GetBasicAuth(); err != nil { t.Error("expected success") } @@ -66,9 +66,9 @@ func TestAuthGetBasicAuth(t *testing.T) { func TestAuthStoreEndToEnd(t *testing.T) { w := httptest.NewRecorder() r := &http.Request{Header: http.Header{}} - b := NewBackendMemory().(*backendMemory) + b := newBackendMemory().(*backendMemory) m := &TextMailer{} - s := NewAuthStore(b, m, w, r, "prefix", cookieKey, false).(*authStore) + s := newAuthStore(b, m, w, r, "prefix", cookieKey, false).(*authStore) // register new user // adds to users, logins and sessions @@ -167,10 +167,10 @@ var registerTests = []struct { func TestAuthRegister(t *testing.T) { for i, test := range registerTests { - backend := &MockBackend{ErrReturn: test.CreateEmailSessionReturn, GetUserReturn: test.GetUserReturn} + backend := &mockBackend{ErrReturn: test.CreateEmailSessionReturn, GetUserReturn: test.GetUserReturn} store := getAuthStore(nil, nil, nil, false, false, nil, backend) err := store.register(test.Email) - methods := store.backend.(*MockBackend).MethodsCalled + methods := store.backend.(*mockBackend).MethodsCalled if (err == nil && test.ExpectedErr != "" || err != nil && test.ExpectedErr != err.Error()) || !collectionEqual(test.MethodsCalled, methods) { t.Errorf("Scenario[%d] failed: %s\nexpected err:%v\tactual err:%v\nexpected methods: %s\tactual methods: %s", i, test.Scenario, test.ExpectedErr, err, test.MethodsCalled, methods) @@ -182,7 +182,7 @@ var createProfileTests = []struct { Scenario string HasCookieGetError bool HasCookiePutError bool - GetEmailSessionReturn *GetEmailSessionReturn + getEmailSessionReturn *getEmailSessionReturn EmailCookie *emailCookie LoginReturn *LoginReturn UpdateUserReturn error @@ -203,14 +203,14 @@ var createProfileTests = []struct { { Scenario: "Can't get EmailSession", EmailCookie: &emailCookie{EmailVerificationCode: "nfwRDzfxxJj2_HY-_mLz6jWyWU7bF0zUlIUUVkQgbZ0=", ExpireTimeUTC: time.Now()}, - GetEmailSessionReturn: getEmailSessionErr(), + getEmailSessionReturn: getEmailSessionErr(), MethodsCalled: []string{"GetEmailSession"}, ExpectedErr: "Invalid email verification", }, { Scenario: "Error Updating user", EmailCookie: &emailCookie{EmailVerificationCode: "nfwRDzfxxJj2_HY-_mLz6jWyWU7bF0zUlIUUVkQgbZ0=", ExpireTimeUTC: time.Now()}, - GetEmailSessionReturn: getEmailSessionSuccess(), + getEmailSessionReturn: getEmailSessionSuccess(), UpdateUserReturn: errors.New("failed"), LoginReturn: loginErr(), MethodsCalled: []string{"GetEmailSession", "UpdateUser"}, @@ -219,7 +219,7 @@ var createProfileTests = []struct { { Scenario: "Error Creating login", EmailCookie: &emailCookie{EmailVerificationCode: "nfwRDzfxxJj2_HY-_mLz6jWyWU7bF0zUlIUUVkQgbZ0=", ExpireTimeUTC: time.Now()}, - GetEmailSessionReturn: getEmailSessionSuccess(), + getEmailSessionReturn: getEmailSessionSuccess(), LoginReturn: loginErr(), MethodsCalled: []string{"GetEmailSession", "UpdateUser", "DeleteEmailSession"}, ExpectedErr: "Unable to create login", @@ -227,7 +227,7 @@ var createProfileTests = []struct { { Scenario: "Error creating session", EmailCookie: &emailCookie{EmailVerificationCode: "nfwRDzfxxJj2_HY-_mLz6jWyWU7bF0zUlIUUVkQgbZ0=", ExpireTimeUTC: time.Now()}, - GetEmailSessionReturn: getEmailSessionSuccess(), + getEmailSessionReturn: getEmailSessionSuccess(), LoginReturn: loginSuccess(), CreateSessionReturn: sessionErr(), MethodsCalled: []string{"GetEmailSession", "UpdateUser", "DeleteEmailSession"}, @@ -236,7 +236,7 @@ var createProfileTests = []struct { { Scenario: "Success", EmailCookie: &emailCookie{EmailVerificationCode: "nfwRDzfxxJj2_HY-_mLz6jWyWU7bF0zUlIUUVkQgbZ0=", ExpireTimeUTC: time.Now()}, - GetEmailSessionReturn: getEmailSessionSuccess(), + getEmailSessionReturn: getEmailSessionSuccess(), LoginReturn: loginSuccess(), CreateSessionReturn: sessionSuccess(futureTime, futureTime), MethodsCalled: []string{"GetEmailSession", "UpdateUser", "DeleteEmailSession"}, @@ -245,10 +245,10 @@ var createProfileTests = []struct { func TestAuthCreateProfile(t *testing.T) { for i, test := range createProfileTests { - backend := &MockBackend{ErrReturn: test.UpdateUserReturn, GetEmailSessionReturn: test.GetEmailSessionReturn} + backend := &mockBackend{ErrReturn: test.UpdateUserReturn, getEmailSessionReturn: test.getEmailSessionReturn} store := getAuthStore(test.CreateSessionReturn, test.LoginReturn, test.EmailCookie, test.HasCookieGetError, test.HasCookiePutError, nil, backend) err := store.createProfile("name", "organization", "password", "path", 1, 1) - methods := store.backend.(*MockBackend).MethodsCalled + methods := store.backend.(*mockBackend).MethodsCalled if (err == nil && test.ExpectedErr != "" || err != nil && test.ExpectedErr != err.Error()) || !collectionEqual(test.MethodsCalled, methods) { t.Errorf("Scenario[%d] failed: %s\nexpected err:%v\tactual err:%v\nexpected methods: %s\tactual methods: %s", i, test.Scenario, test.ExpectedErr, err, test.MethodsCalled, methods) @@ -260,7 +260,7 @@ var verifyEmailTests = []struct { Scenario string EmailVerificationCode string HasCookiePutError bool - GetEmailSessionReturn *GetEmailSessionReturn + getEmailSessionReturn *getEmailSessionReturn MailErr error MethodsCalled []string ExpectedErr string @@ -268,20 +268,20 @@ var verifyEmailTests = []struct { { Scenario: "Decode error", EmailVerificationCode: "code", - GetEmailSessionReturn: getEmailSessionErr(), + getEmailSessionReturn: getEmailSessionErr(), ExpectedErr: "Invalid verification code", }, { Scenario: "Verify Email Error", EmailVerificationCode: "nfwRDzfxxJj2_HY-_mLz6jWyWU7bF0zUlIUUVkQgbZ0", - GetEmailSessionReturn: getEmailSessionErr(), + getEmailSessionReturn: getEmailSessionErr(), MethodsCalled: []string{"GetEmailSession"}, ExpectedErr: "Failed to verify email", }, { Scenario: "Cookie Save Error", EmailVerificationCode: "nfwRDzfxxJj2_HY-_mLz6jWyWU7bF0zUlIUUVkQgbZ0", - GetEmailSessionReturn: getEmailSessionSuccess(), + getEmailSessionReturn: getEmailSessionSuccess(), HasCookiePutError: true, MethodsCalled: []string{"GetEmailSession", "AddUser"}, ExpectedErr: "Failed to save email cookie", @@ -289,7 +289,7 @@ var verifyEmailTests = []struct { { Scenario: "Mail Error", EmailVerificationCode: "nfwRDzfxxJj2_HY-_mLz6jWyWU7bF0zUlIUUVkQgbZ0", - GetEmailSessionReturn: getEmailSessionSuccess(), + getEmailSessionReturn: getEmailSessionSuccess(), MethodsCalled: []string{"GetEmailSession", "AddUser"}, MailErr: errors.New("test"), ExpectedErr: "Failed to send welcome email", @@ -297,17 +297,17 @@ var verifyEmailTests = []struct { { Scenario: "Email sent", EmailVerificationCode: "nfwRDzfxxJj2_HY-_mLz6jWyWU7bF0zUlIUUVkQgbZ0", - GetEmailSessionReturn: getEmailSessionSuccess(), + getEmailSessionReturn: getEmailSessionSuccess(), MethodsCalled: []string{"GetEmailSession", "AddUser"}, }, } func TestAuthVerifyEmail(t *testing.T) { for i, test := range verifyEmailTests { - backend := &MockBackend{GetEmailSessionReturn: test.GetEmailSessionReturn} + backend := &mockBackend{getEmailSessionReturn: test.getEmailSessionReturn} store := getAuthStore(nil, nil, nil, false, test.HasCookiePutError, test.MailErr, backend) err := store.verifyEmail(test.EmailVerificationCode) - methods := store.backend.(*MockBackend).MethodsCalled + methods := store.backend.(*mockBackend).MethodsCalled if (err == nil && test.ExpectedErr != "" || err != nil && test.ExpectedErr != err.Error()) || !collectionEqual(test.MethodsCalled, methods) { t.Errorf("Scenario[%d] failed: %s\nexpected err:%v\tactual err:%v\nexpected methods: %s\tactual methods: %s", i, test.Scenario, test.ExpectedErr, err, test.MethodsCalled, methods) @@ -329,7 +329,7 @@ func TestRegisterPub(t *testing.T) { var buf bytes.Buffer buf.WriteString(`{"Email":"bogus"}`) r := &http.Request{Body: ioutil.NopCloser(&buf)} - backend := &MockBackend{} + backend := &mockBackend{} store := getAuthStore(nil, nil, nil, true, false, nil, backend) store.r = r err := store.Register() @@ -358,7 +358,7 @@ func TestVerifyEmailPub(t *testing.T) { var buf bytes.Buffer buf.WriteString(`{"EmailVerificationCode":"nfwRDzfxxJj2_HY-_mLz6jWyWU7bF0zUlIUUVkQgbZ0"}`) // random valid base64 encoded data r := &http.Request{Body: ioutil.NopCloser(&buf)} - backend := &MockBackend{GetEmailSessionReturn: getEmailSessionErr()} + backend := &mockBackend{getEmailSessionReturn: getEmailSessionErr()} store := getAuthStore(nil, nil, nil, true, false, nil, backend) store.r = r err := store.VerifyEmail() @@ -387,7 +387,7 @@ func TestLoginJson(t *testing.T) { var buf bytes.Buffer buf.WriteString(`{"Email":"email", "Password":"password", "RememberMe":true}`) r := &http.Request{Body: ioutil.NopCloser(&buf)} - backend := &MockBackend{} + backend := &mockBackend{} store := getAuthStore(nil, loginErr(), nil, true, false, nil, backend) store.r = r err := store.Login() @@ -438,7 +438,7 @@ func TestCreateProfilePub(t *testing.T) { r, _ := http.NewRequest("PUT", "url", &buf) r.Header.Add("Content-Type", w.FormDataContentType()) - backend := &MockBackend{} + backend := &mockBackend{} store := getAuthStore(nil, nil, nil, true, false, nil, backend) store.r = r err := store.CreateProfile() @@ -483,19 +483,19 @@ func collectionEqual(expected, actual []string) bool { } /****************************************************************************/ -type MockAuthStore struct { +type mockAuthStore struct { } -func NewMockAuthStore() *MockAuthStore { - return &MockAuthStore{} +func newMockAuthStore() *mockAuthStore { + return &mockAuthStore{} } -func (s *MockAuthStore) Get() (*UserLoginSession, error) { +func (s *mockAuthStore) Get() (*loginSession, error) { return nil, nil } -func (s *MockAuthStore) GetRememberMe() (*UserLoginRememberMe, error) { +func (s *mockAuthStore) GetRememberMe() (*rememberMeSession, error) { return nil, nil } -func (s *MockAuthStore) Login(email, password, returnURL string) (*UserLoginSession, error) { +func (s *mockAuthStore) Login(email, password, returnURL string) (*loginSession, error) { return nil, nil } diff --git a/auth_test.go b/auth_test.go deleted file mode 100644 index 0c93fe4..0000000 --- a/auth_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package main - -import ( - "errors" - "net/http/httptest" - "testing" -) - -func TestAuth(t *testing.T) { - w := httptest.NewRecorder() - storer := &MockAuthStorer{ErrReturn: errors.New("failed")} - auth(storer, w, nil) - if w.Body.String() != "Authentication required: failed\n" || storer.LastRun != "GetSession" { - t.Error("expected auth to fail", w.Body.String(), storer.LastRun) - } - - w = httptest.NewRecorder() - storer = &MockAuthStorer{SessionReturn: &UserLoginSession{Email: "test@test.com"}} - auth(storer, w, nil) - if w.Header().Get("X-User") != "test@test.com" || storer.LastRun != "GetSession" { - t.Error("expected User header to be set", w.Header().Get("X-User"), storer.LastRun) - } -} - -func TestAuthBasic(t *testing.T) { - w := httptest.NewRecorder() - storer := &MockAuthStorer{ErrReturn: errors.New("failed")} - authBasic(storer, w, nil) - if w.Body.String() != "Authentication required: failed\n" || storer.LastRun != "GetBasicAuth" { - t.Error("expected auth to fail", w.Body.String(), storer.LastRun) - } - - w = httptest.NewRecorder() - storer = &MockAuthStorer{SessionReturn: &UserLoginSession{Email: "test@test.com"}} - authBasic(storer, w, nil) - if w.Header().Get("X-User") != "test@test.com" || storer.LastRun != "GetBasicAuth" { - t.Error("expected User header to be set", w.Header().Get("X-User"), storer.LastRun) - } -} - -func TestLogin(t *testing.T) { - w := httptest.NewRecorder() - storer := &MockAuthStorer{ErrReturn: errors.New("failed")} - login(storer, w, nil) - if w.Body.String() != "failed\n" || storer.LastRun != "Login" { - t.Error("expected to fail", w.Body.String(), storer.LastRun) - } - - w = httptest.NewRecorder() - storer = &MockAuthStorer{SessionReturn: &UserLoginSession{}} - login(storer, w, nil) - if w.Body.String() != `{ "result": "Success" }` || storer.LastRun != "Login" { - t.Error("expected success", w.Body.String(), storer.LastRun) - } -} - -func TestRegister(t *testing.T) { - w := httptest.NewRecorder() - storer := &MockAuthStorer{ErrReturn: errors.New("failed")} - register(storer, w, nil) - if w.Body.String() != "failed\n" || storer.LastRun != "Register" { - t.Error("expected to fail", w.Body.String(), storer.LastRun) - } -} - -func TestCreateProfile(t *testing.T) { - w := httptest.NewRecorder() - storer := &MockAuthStorer{ErrReturn: errors.New("failed")} - createProfile(storer, w, nil) - if w.Body.String() != "failed\n" || storer.LastRun != "CreateProfile" { - t.Error("expected to fail", w.Body.String(), storer.LastRun) - } -} - -func TestUpdateEmail(t *testing.T) { - w := httptest.NewRecorder() - storer := &MockAuthStorer{ErrReturn: errors.New("failed")} - updateEmail(storer, w, nil) - if w.Body.String() != "failed\n" || storer.LastRun != "UpdateEmail" { - t.Error("expected to fail", w.Body.String(), storer.LastRun) - } -} - -func TestUpdatePassword(t *testing.T) { - w := httptest.NewRecorder() - storer := &MockAuthStorer{ErrReturn: errors.New("failed")} - updatePassword(storer, w, nil) - if w.Body.String() != "failed\n" || storer.LastRun != "UpdatePassword" { - t.Error("expected to fail", w.Body.String(), storer.LastRun) - } -} - -func TestVerifyEmail(t *testing.T) { - w := httptest.NewRecorder() - storer := &MockAuthStorer{ErrReturn: errors.New("failed")} - verifyEmail(storer, w, nil) - if w.Body.String() != "failed\n" || storer.LastRun != "VerifyEmail" { - t.Error("expected to fail", w.Body.String(), storer.LastRun) - } -} - -func TestAddUserHeader(t *testing.T) { - w := httptest.NewRecorder() - addUserHeader(&UserLoginSession{Email: "test@test.com"}, w) - if w.Header().Get("X-User") != "test@test.com" { - t.Error("expected halfauth header", w.Header()) - } -} - -/*******************************************************/ -type MockAuthStorer struct { - SessionReturn *UserLoginSession - ErrReturn error - LastRun string -} - -func (s *MockAuthStorer) GetSession() (*UserLoginSession, error) { - s.LastRun = "GetSession" - return s.SessionReturn, s.ErrReturn -} - -func (s *MockAuthStorer) GetBasicAuth() (*UserLoginSession, error) { - s.LastRun = "GetBasicAuth" - return s.SessionReturn, s.ErrReturn -} -func (s *MockAuthStorer) Login() error { - s.LastRun = "Login" - return s.ErrReturn -} -func (s *MockAuthStorer) Register() error { - s.LastRun = "Register" - return s.ErrReturn -} -func (s *MockAuthStorer) CreateProfile() error { - s.LastRun = "CreateProfile" - return s.ErrReturn -} -func (s *MockAuthStorer) VerifyEmail() error { - s.LastRun = "VerifyEmail" - return s.ErrReturn -} -func (s *MockAuthStorer) UpdateEmail() error { - s.LastRun = "UpdateEmail" - return s.ErrReturn -} -func (s *MockAuthStorer) UpdatePassword() error { - s.LastRun = "UpdatePassword" - return s.ErrReturn -} diff --git a/backend.go b/backend.go index e419554..cf5ddbe 100644 --- a/backend.go +++ b/backend.go @@ -5,55 +5,55 @@ import ( "time" ) -type Backender interface { +type backender interface { // UserBackender. Write out since it contains duplicate BackendCloser AddUser(email string) error - GetUser(email string) (*User, error) + GetUser(email string) (*user, error) UpdateUser(email, fullname string, company string, pictureURL string) error // LoginBackender. Write out since it contains duplicate BackendCloser - CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*UserLogin, error) - GetLogin(email, loginProvider string) (*UserLogin, error) - UpdateEmail(email string, password string, newEmail string) (*UserLoginSession, error) - UpdatePassword(email string, oldPassword string, newPassword string) (*UserLoginSession, error) + CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*userLogin, error) + GetLogin(email, loginProvider string) (*userLogin, error) + UpdateEmail(email string, password string, newEmail string) (*loginSession, error) + UpdatePassword(email string, oldPassword string, newPassword string) (*loginSession, error) - SessionBackender + sessionBackender } -type BackendCloser interface { +type backendCloser interface { Close() error } -type UserBackender interface { +type userBackender interface { AddUser(email string) error - GetUser(email string) (*User, error) + GetUser(email string) (*user, error) UpdateUser(email, fullname string, company string, pictureURL string) error - BackendCloser + backendCloser } -type LoginBackender interface { - CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*UserLogin, error) - GetLogin(email, loginProvider string) (*UserLogin, error) - UpdateEmail(email string, password string, newEmail string) (*UserLoginSession, error) - UpdatePassword(email string, oldPassword string, newPassword string) (*UserLoginSession, error) - BackendCloser +type loginBackender interface { + CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*userLogin, error) + GetLogin(email, loginProvider string) (*userLogin, error) + UpdateEmail(email string, password string, newEmail string) (*loginSession, error) + UpdatePassword(email string, oldPassword string, newPassword string) (*loginSession, error) + backendCloser } -type SessionBackender interface { +type sessionBackender interface { CreateEmailSession(email, emailVerifyHash string) error GetEmailSession(verifyHash string) (*emailSession, error) DeleteEmailSession(verifyHash string) error - CreateSession(email string, sessionHash string, sessionRenewTimeUTC, sessionExpireTimeUTC time.Time, rememberMe bool, rememberMeSelector, rememberMeTokenHash string, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC time.Time) (*UserLoginSession, *UserLoginRememberMe, error) - GetSession(sessionHash string) (*UserLoginSession, error) - RenewSession(sessionHash string, renewTimeUTC time.Time) (*UserLoginSession, error) + CreateSession(email string, sessionHash string, sessionRenewTimeUTC, sessionExpireTimeUTC time.Time, rememberMe bool, rememberMeSelector, rememberMeTokenHash string, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC time.Time) (*loginSession, *rememberMeSession, error) + GetSession(sessionHash string) (*loginSession, error) + RenewSession(sessionHash string, renewTimeUTC time.Time) (*loginSession, error) InvalidateSession(sessionHash string) error InvalidateSessions(email string) error - GetRememberMe(selector string) (*UserLoginRememberMe, error) - RenewRememberMe(selector string, renewTimeUTC time.Time) (*UserLoginRememberMe, error) + GetRememberMe(selector string) (*rememberMeSession, error) + RenewRememberMe(selector string, renewTimeUTC time.Time) (*rememberMeSession, error) InvalidateRememberMe(selector string) error - BackendCloser + backendCloser } var errEmailVerifyHashExists = errors.New("DB: Email verify hash already exists") @@ -75,27 +75,27 @@ type emailSession struct { EmailVerifyHash string } -type User struct { +type user struct { FullName string PrimaryEmail string LockoutEndTimeUTC *time.Time AccessFailedCount int } -type UserLogin struct { +type userLogin struct { Email string LoginProviderID int ProviderKey string } -type UserLoginSession struct { +type loginSession struct { Email string SessionHash string RenewTimeUTC time.Time ExpireTimeUTC time.Time } -type UserLoginRememberMe struct { +type rememberMeSession struct { Email string Selector string TokenHash string @@ -103,7 +103,7 @@ type UserLoginRememberMe struct { ExpireTimeUTC time.Time } -type UserLoginProvider struct { +type loginProvider struct { LoginProviderID int Name string OAuthClientID string @@ -111,32 +111,32 @@ type UserLoginProvider struct { OAuthURL string } -type AuthError struct { +type authError struct { message string innerError error shouldLog bool error } -func newLoggedError(message string, innerError error) *AuthError { - return &AuthError{message: message, innerError: innerError, shouldLog: true} +func newLoggedError(message string, innerError error) *authError { + return &authError{message: message, innerError: innerError, shouldLog: true} } -func newAuthError(message string, innerError error) *AuthError { - return &AuthError{message: message, innerError: innerError} +func newAuthError(message string, innerError error) *authError { + return &authError{message: message, innerError: innerError} } -func (a *AuthError) Error() string { +func (a *authError) Error() string { return a.message } -func (a *AuthError) Trace() string { +func (a *authError) Trace() string { trace := a.message + "\n" indent := " " inner := a.innerError for inner != nil { trace += indent + inner.Error() + "\n" - e, ok := inner.(*AuthError) + e, ok := inner.(*authError) if !ok { break } @@ -147,33 +147,33 @@ func (a *AuthError) Trace() string { } type backend struct { - u UserBackender - l LoginBackender - s SessionBackender - BackendCloser + u userBackender + l loginBackender + s sessionBackender + backendCloser } -func (b *backend) GetLogin(email, loginProvider string) (*UserLogin, error) { +func (b *backend) GetLogin(email, loginProvider string) (*userLogin, error) { return b.l.GetLogin(email, loginProvider) } -func (b *backend) CreateSession(email, sessionHash string, sessionRenewTimeUTC, sessionExpireTimeUTC time.Time, rememberMe bool, rememberMeSelector, rememberMeTokenHash string, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC time.Time) (*UserLoginSession, *UserLoginRememberMe, error) { +func (b *backend) CreateSession(email, sessionHash string, sessionRenewTimeUTC, sessionExpireTimeUTC time.Time, rememberMe bool, rememberMeSelector, rememberMeTokenHash string, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC time.Time) (*loginSession, *rememberMeSession, error) { return b.s.CreateSession(email, sessionHash, sessionRenewTimeUTC, sessionExpireTimeUTC, rememberMe, rememberMeSelector, rememberMeTokenHash, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC) } -func (b *backend) GetSession(sessionHash string) (*UserLoginSession, error) { +func (b *backend) GetSession(sessionHash string) (*loginSession, error) { return b.s.GetSession(sessionHash) } -func (b *backend) RenewSession(sessionHash string, renewTimeUTC time.Time) (*UserLoginSession, error) { +func (b *backend) RenewSession(sessionHash string, renewTimeUTC time.Time) (*loginSession, error) { return b.s.RenewSession(sessionHash, renewTimeUTC) } -func (b *backend) GetRememberMe(selector string) (*UserLoginRememberMe, error) { +func (b *backend) GetRememberMe(selector string) (*rememberMeSession, error) { return b.s.GetRememberMe(selector) } -func (b *backend) RenewRememberMe(selector string, renewTimeUTC time.Time) (*UserLoginRememberMe, error) { +func (b *backend) RenewRememberMe(selector string, renewTimeUTC time.Time) (*rememberMeSession, error) { return b.s.RenewRememberMe(selector, renewTimeUTC) } @@ -193,7 +193,7 @@ func (b *backend) AddUser(email string) error { return b.u.AddUser(email) } -func (b *backend) GetUser(email string) (*User, error) { +func (b *backend) GetUser(email string) (*user, error) { return b.u.GetUser(email) } @@ -201,15 +201,15 @@ func (b *backend) UpdateUser(email, fullname string, company string, pictureURL return b.u.UpdateUser(email, fullname, company, pictureURL) } -func (b *backend) CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*UserLogin, error) { +func (b *backend) CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*userLogin, error) { return b.l.CreateLogin(email, passwordHash, fullName, homeDirectory, uidNumber, gidNumber, mailQuota, fileQuota) } -func (b *backend) UpdateEmail(email string, password string, newEmail string) (*UserLoginSession, error) { +func (b *backend) UpdateEmail(email string, password string, newEmail string) (*loginSession, error) { return b.l.UpdateEmail(email, password, newEmail) } -func (b *backend) UpdatePassword(email string, oldPassword string, newPassword string) (*UserLoginSession, error) { +func (b *backend) UpdatePassword(email string, oldPassword string, newPassword string) (*loginSession, error) { return b.l.UpdatePassword(email, oldPassword, newPassword) } diff --git a/backendDbUser.go b/backendDbUser.go index cfa8870..330acf7 100644 --- a/backendDbUser.go +++ b/backendDbUser.go @@ -15,7 +15,7 @@ type backendDbUser struct { CreateLoginQuery string } -func newBackendDbUser(server string, port int, username, password, database string, getUserLoginQuery, addUserQuery, verifyEmailQuery, updateUserQuery string) (UserBackender, error) { +func newBackendDbUser(server string, port int, username, password, database string, getUserLoginQuery, addUserQuery, verifyEmailQuery, updateUserQuery string) (userBackender, error) { db, err := onedb.NewPgx(server, uint16(port), username, password, database) if err != nil { return nil, err @@ -27,8 +27,8 @@ func newBackendDbUser(server string, port int, username, password, database stri UpdateUserQuery: updateUserQuery}, nil } -func (u *backendDbUser) GetLogin(email, loginProvider string) (*UserLogin, error) { - var login *UserLogin +func (u *backendDbUser) GetLogin(email, loginProvider string) (*userLogin, error) { + var login *userLogin return login, u.Db.QueryStruct(onedb.NewSqlQuery(u.GetUserLoginQuery, email, loginProvider), login) } @@ -36,13 +36,13 @@ func (u *backendDbUser) AddUser(email string) error { return u.Db.Execute(onedb.NewSqlQuery(u.AddUserQuery, email)) } -func (u *backendDbUser) GetUser(email string) (*User, error) { - var user *User - err := u.Db.QueryStructRow(onedb.NewSqlQuery(u.VerifyEmailQuery, email), user) - if err != nil || user == nil { +func (u *backendDbUser) GetUser(email string) (*user, error) { + var r *user + err := u.Db.QueryStructRow(onedb.NewSqlQuery(u.VerifyEmailQuery, email), r) + if err != nil || r == nil { return nil, errors.New("Unable to get user: " + err.Error()) } - return user, err + return r, err } func (u *backendDbUser) UpdateUser(email, fullname string, company string, pictureURL string) error { diff --git a/backendLDAPLogin.go b/backendLDAPLogin.go index fc5fa8e..51ddd28 100644 --- a/backendLDAPLogin.go +++ b/backendLDAPLogin.go @@ -13,7 +13,7 @@ type backendLDAPLogin struct { userLoginFilter string } -func NewBackendLDAPLogin(server string, port int, bindDn, password, baseDn, userLoginFilter string) (LoginBackender, error) { +func newBackendLDAPLogin(server string, port int, bindDn, password, baseDn, userLoginFilter string) (loginBackender, error) { db, err := onedb.NewLdap(server, port, bindDn, password) if err != nil { return nil, err @@ -29,7 +29,7 @@ type ldapData struct { HomeDirectory []string } -func (l *backendLDAPLogin) GetLogin(email, loginProvider string) (*UserLogin, error) { +func (l *backendLDAPLogin) GetLogin(email, loginProvider string) (*userLogin, error) { req := ldap.NewSearchRequest(l.baseDn, ldap.ScopeSingleLevel, ldap.NeverDerefAliases, 0, 0, false, fmt.Sprintf(l.userLoginFilter, email), []string{"uid", "userPassword", "uidNumber", "gidNumber", "homeDirectory"}, nil) data := &ldapData{} err := l.db.QueryStructRow(req, data) @@ -40,11 +40,11 @@ func (l *backendLDAPLogin) GetLogin(email, loginProvider string) (*UserLogin, er if len(data.UserPassword) != 0 { password = data.UserPassword[0] } - return &UserLogin{ProviderKey: password}, nil + return &userLogin{ProviderKey: password}, nil } /**************** TODO: create different type of user if not using file and mail quotas **********************/ -func (l *backendLDAPLogin) CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*UserLogin, error) { +func (l *backendLDAPLogin) CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*userLogin, error) { req := ldap.NewAddRequest("uid=" + email + ",ou=Users,dc=endfirst,dc=com") req.Attribute("objectClass", []string{"posixAccount", "account", "ownCloud", "systemQuotas"}) req.Attribute("uid", []string{email}) @@ -56,14 +56,14 @@ func (l *backendLDAPLogin) CreateLogin(email, passwordHash, fullName, homeDirect req.Attribute("quota", []string{mailQuota}) req.Attribute("ownCloudQuota", []string{fileQuota}) err := l.db.Execute(req) - return &UserLogin{}, err + return &userLogin{}, err } -func (l *backendLDAPLogin) UpdateEmail(email string, password string, newEmail string) (*UserLoginSession, error) { +func (l *backendLDAPLogin) UpdateEmail(email string, password string, newEmail string) (*loginSession, error) { return nil, nil } -func (l *backendLDAPLogin) UpdatePassword(email string, oldPassword string, newPassword string) (*UserLoginSession, error) { +func (l *backendLDAPLogin) UpdatePassword(email string, oldPassword string, newPassword string) (*loginSession, error) { return nil, nil } diff --git a/backendLDAPLogin_test.go b/backendLDAPLogin_test.go index 8efa852..df377ee 100644 --- a/backendLDAPLogin_test.go +++ b/backendLDAPLogin_test.go @@ -18,7 +18,7 @@ func TestNewBackendLDAPLogin(t *testing.T) { t.Fatal("unable to load config file", err) } - l, err := NewBackendLDAPLogin(config.LdapServer, config.LdapPort, config.LdapBindDn, config.LdapPassword, config.LdapBaseDn, config.LdapUserFilter) + l, err := newBackendLDAPLogin(config.LdapServer, config.LdapPort, config.LdapBindDn, config.LdapPassword, config.LdapBaseDn, config.LdapUserFilter) if err != nil { t.Fatal("unable to login", err) } diff --git a/backendMemory.go b/backendMemory.go index e996f9a..f40c1d3 100644 --- a/backendMemory.go +++ b/backendMemory.go @@ -7,24 +7,24 @@ import ( ) type backendMemory struct { - Backender + backender EmailSessions []*emailSession - Users []*User - Logins []*UserLogin - Sessions []*UserLoginSession - RememberMes []*UserLoginRememberMe - LoginProviders []*UserLoginProvider + Users []*user + Logins []*userLogin + Sessions []*loginSession + RememberMes []*rememberMeSession + LoginProviders []*loginProvider LastUserID int LastLoginID int } const loginProviderDefaultName string = "Default" -func NewBackendMemory() Backender { - return &backendMemory{LoginProviders: []*UserLoginProvider{&UserLoginProvider{LoginProviderID: 1, Name: loginProviderDefaultName}}} +func newBackendMemory() backender { + return &backendMemory{LoginProviders: []*loginProvider{&loginProvider{LoginProviderID: 1, Name: loginProviderDefaultName}}} } -func (m *backendMemory) GetLogin(email, loginProvider string) (*UserLogin, error) { +func (m *backendMemory) GetLogin(email, loginProvider string) (*userLogin, error) { login := m.getLoginByEmail(email) if login == nil { return nil, errLoginNotFound @@ -32,28 +32,28 @@ func (m *backendMemory) GetLogin(email, loginProvider string) (*UserLogin, error return login, nil } -func (m *backendMemory) CreateSession(email, sessionHash string, sessionRenewTimeUTC, sessionExpireTimeUTC time.Time, rememberMe bool, rememberMeSelector, rememberMeTokenHash string, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC time.Time) (*UserLoginSession, *UserLoginRememberMe, error) { +func (m *backendMemory) CreateSession(email, sessionHash string, sessionRenewTimeUTC, sessionExpireTimeUTC time.Time, rememberMe bool, rememberMeSelector, rememberMeTokenHash string, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC time.Time) (*loginSession, *rememberMeSession, error) { session := m.getSessionByHash(sessionHash) if session != nil { return nil, nil, errSessionAlreadyExists } - session = &UserLoginSession{email, sessionHash, sessionRenewTimeUTC, sessionExpireTimeUTC} + session = &loginSession{email, sessionHash, sessionRenewTimeUTC, sessionExpireTimeUTC} m.Sessions = append(m.Sessions, session) - var rememberItem *UserLoginRememberMe + var rememberItem *rememberMeSession if rememberMe { rememberItem = m.getRememberMe(rememberMeSelector) if rememberItem != nil { return nil, nil, errRememberMeSelectorExists } - rememberItem = &UserLoginRememberMe{email, rememberMeSelector, rememberMeTokenHash, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC} + rememberItem = &rememberMeSession{email, rememberMeSelector, rememberMeTokenHash, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC} m.RememberMes = append(m.RememberMes, rememberItem) } return session, rememberItem, nil } -func (m *backendMemory) GetSession(sessionHash string) (*UserLoginSession, error) { +func (m *backendMemory) GetSession(sessionHash string) (*loginSession, error) { session := m.getSessionByHash(sessionHash) if session == nil { return nil, errSessionNotFound @@ -61,7 +61,7 @@ func (m *backendMemory) GetSession(sessionHash string) (*UserLoginSession, error return session, nil } -func (m *backendMemory) RenewSession(sessionHash string, renewTimeUTC time.Time) (*UserLoginSession, error) { +func (m *backendMemory) RenewSession(sessionHash string, renewTimeUTC time.Time) (*loginSession, error) { session := m.getSessionByHash(sessionHash) if session == nil { return nil, errSessionNotFound @@ -70,7 +70,7 @@ func (m *backendMemory) RenewSession(sessionHash string, renewTimeUTC time.Time) return session, nil } -func (m *backendMemory) GetRememberMe(selector string) (*UserLoginRememberMe, error) { +func (m *backendMemory) GetRememberMe(selector string) (*rememberMeSession, error) { rememberMe := m.getRememberMe(selector) if rememberMe == nil { return nil, errRememberMeNotFound @@ -78,7 +78,7 @@ func (m *backendMemory) GetRememberMe(selector string) (*UserLoginRememberMe, er return rememberMe, nil } -func (m *backendMemory) RenewRememberMe(selector string, renewTimeUTC time.Time) (*UserLoginRememberMe, error) { +func (m *backendMemory) RenewRememberMe(selector string, renewTimeUTC time.Time) (*rememberMeSession, error) { rememberMe := m.getRememberMe(selector) if rememberMe == nil { return nil, errRememberMeNotFound @@ -120,20 +120,20 @@ func (m *backendMemory) DeleteEmailSession(emailVerifyHash string) error { } func (m *backendMemory) AddUser(email string) error { - user := m.getUserByEmail(email) - if user != nil { + u := m.getUserByEmail(email) + if u != nil { return errUserAlreadyExists } - m.Users = append(m.Users, &User{"", email, nil, 0}) + m.Users = append(m.Users, &user{"", email, nil, 0}) return nil } -func (m *backendMemory) GetUser(email string) (*User, error) { - user := m.getUserByEmail(email) - if user == nil { +func (m *backendMemory) GetUser(email string) (*user, error) { + u := m.getUserByEmail(email) + if u == nil { return nil, errUserNotFound } - return user, nil + return u, nil } func (m *backendMemory) UpdateUser(email, fullname string, company string, pictureURL string) error { @@ -147,18 +147,18 @@ func (m *backendMemory) UpdateUser(email, fullname string, company string, pictu } // This method needs to be fixed to work with the new data model using LDAP -func (m *backendMemory) CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*UserLogin, error) { - login := UserLogin{email, 1, passwordHash} +func (m *backendMemory) CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*userLogin, error) { + login := userLogin{email, 1, passwordHash} m.Logins = append(m.Logins, &login) return &login, nil } -func (m *backendMemory) UpdateEmail(email string, password string, newEmail string) (*UserLoginSession, error) { +func (m *backendMemory) UpdateEmail(email string, password string, newEmail string) (*loginSession, error) { return nil, nil } -func (m *backendMemory) UpdatePassword(email string, oldPassword string, newPassword string) (*UserLoginSession, error) { +func (m *backendMemory) UpdatePassword(email string, oldPassword string, newPassword string) (*loginSession, error) { return nil, nil } @@ -231,7 +231,7 @@ func (m *backendMemory) removeSession(sessionHash string) { } } -func (m *backendMemory) getLoginProvider(name string) *UserLoginProvider { +func (m *backendMemory) getLoginProvider(name string) *loginProvider { for _, provider := range m.LoginProviders { if provider.Name == name { return provider @@ -240,7 +240,7 @@ func (m *backendMemory) getLoginProvider(name string) *UserLoginProvider { return nil } -func (m *backendMemory) getLoginByUser(email, loginProvider string) *UserLogin { +func (m *backendMemory) getLoginByUser(email, loginProvider string) *userLogin { provider := m.getLoginProvider(loginProvider) if provider == nil { return nil @@ -253,7 +253,7 @@ func (m *backendMemory) getLoginByUser(email, loginProvider string) *UserLogin { return nil } -func (m *backendMemory) getLoginByEmail(email string) *UserLogin { +func (m *backendMemory) getLoginByEmail(email string) *userLogin { for _, login := range m.Logins { if login.Email == email { return login @@ -262,7 +262,7 @@ func (m *backendMemory) getLoginByEmail(email string) *UserLogin { return nil } -func (m *backendMemory) getUserByEmail(email string) *User { +func (m *backendMemory) getUserByEmail(email string) *user { for _, user := range m.Users { if user.PrimaryEmail == email { return user @@ -280,7 +280,7 @@ func (m *backendMemory) getEmailSessionByEmailVerifyHash(hash string) *emailSess return nil } -func (m *backendMemory) getSessionByHash(sessionHash string) *UserLoginSession { +func (m *backendMemory) getSessionByHash(sessionHash string) *loginSession { for _, session := range m.Sessions { if session.SessionHash == sessionHash { return session @@ -289,7 +289,7 @@ func (m *backendMemory) getSessionByHash(sessionHash string) *UserLoginSession { return nil } -func (m *backendMemory) getRememberMe(selector string) *UserLoginRememberMe { +func (m *backendMemory) getRememberMe(selector string) *rememberMeSession { for _, rememberMe := range m.RememberMes { if rememberMe.Selector == selector { return rememberMe diff --git a/backendMemory_test.go b/backendMemory_test.go index 4dd28d5..22a6c61 100644 --- a/backendMemory_test.go +++ b/backendMemory_test.go @@ -9,11 +9,11 @@ var in5Minutes = time.Now().UTC().Add(5 * time.Minute) var in1Hour = time.Now().UTC().Add(time.Hour) func TestMemoryGetLogin(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) if _, err := backend.GetLogin("email", loginProviderDefaultName); err != errLoginNotFound { t.Error("expected no login since login not added yet", err) } - expected := &UserLogin{Email: "email", LoginProviderID: 1} + expected := &userLogin{Email: "email", LoginProviderID: 1} backend.Logins = append(backend.Logins, expected) if actual, _ := backend.GetLogin("email", loginProviderDefaultName); expected != actual { t.Error("expected no login since login not added yet") @@ -21,7 +21,7 @@ func TestMemoryGetLogin(t *testing.T) { } func TestMemoryCreateSession(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) if session, _, _ := backend.CreateSession("test@test.com", "sessionHash", in5Minutes, in1Hour, false, "", "", time.Time{}, time.Time{}); session.SessionHash != "sessionHash" || session.Email != "test@test.com" { t.Error("expected matching session", session) } @@ -50,58 +50,58 @@ func TestMemoryCreateSession(t *testing.T) { } func TestMemoryGetSession(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) if _, err := backend.GetSession("sessionHash"); err != errSessionNotFound { t.Error("expected err", err) } // add session now and try again... should be returned - backend.Sessions = append(backend.Sessions, &UserLoginSession{SessionHash: "sessionHash"}) + backend.Sessions = append(backend.Sessions, &loginSession{SessionHash: "sessionHash"}) if session, _ := backend.GetSession("sessionHash"); session.SessionHash != "sessionHash" { t.Error("expected session to be returned", session) } } func TestMemoryRenewSession(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) renews := time.Now() if _, err := backend.RenewSession("sessionHash", renews); err != errSessionNotFound { t.Error("expected err", err) } // add session now and try again... should be renewed - backend.Sessions = append(backend.Sessions, &UserLoginSession{SessionHash: "sessionHash"}) + backend.Sessions = append(backend.Sessions, &loginSession{SessionHash: "sessionHash"}) if session, _ := backend.RenewSession("sessionHash", renews); session.SessionHash != "sessionHash" || session.RenewTimeUTC != renews { t.Error("expected session to be renewed", session) } } func TestMemoryGetRememberMe(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) if _, err := backend.GetRememberMe("selector"); err != errRememberMeNotFound { t.Error("expected err", err) } // add rememberMe now and try again... should be returned - backend.RememberMes = append(backend.RememberMes, &UserLoginRememberMe{Selector: "selector"}) + backend.RememberMes = append(backend.RememberMes, &rememberMeSession{Selector: "selector"}) if rememberMe, _ := backend.GetRememberMe("selector"); rememberMe.Selector != "selector" { t.Error("expected rememberMe to be found", rememberMe) } } func TestMemoryRenewRememberMe(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) renews := time.Now().UTC().Add(5 * time.Minute) if _, err := backend.RenewRememberMe("selector", renews); err != errRememberMeNotFound { t.Error("expected err", err) } - backend.RememberMes = append(backend.RememberMes, &UserLoginRememberMe{Selector: "expired", ExpireTimeUTC: time.Now().UTC().Add(-1 * time.Hour)}) + backend.RememberMes = append(backend.RememberMes, &rememberMeSession{Selector: "expired", ExpireTimeUTC: time.Now().UTC().Add(-1 * time.Hour)}) if _, err := backend.RenewRememberMe("expired", renews); err != errRememberMeExpired { t.Error("expected expired", err) } - backend.RememberMes = append(backend.RememberMes, &UserLoginRememberMe{Selector: "selector", ExpireTimeUTC: time.Now().UTC().Add(time.Hour)}) + backend.RememberMes = append(backend.RememberMes, &rememberMeSession{Selector: "selector", ExpireTimeUTC: time.Now().UTC().Add(time.Hour)}) if _, err := backend.RenewRememberMe("selector", time.Now().UTC().Add(2*time.Hour)); err != errInvalidRenewTimeUTC { t.Error("expected invalid renew time", err) } @@ -114,7 +114,7 @@ func TestMemoryRenewRememberMe(t *testing.T) { } func TestMemoryAddUser(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) if err := backend.AddUser("email"); err != nil || len(backend.Users) != 1 { t.Error("expected valid session", err, backend.Users) } @@ -125,7 +125,7 @@ func TestMemoryAddUser(t *testing.T) { } func TestMemoryGetEmailSession(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) if _, err := backend.GetEmailSession("verifyHash"); err != errInvalidEmailVerifyHash { t.Error("expected login not found err", err) } @@ -138,14 +138,14 @@ func TestMemoryGetEmailSession(t *testing.T) { } func TestMemoryUpdateUser(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) err := backend.UpdateUser("email", "fullname", "company", "pictureUrl") if err != errUserNotFound { t.Error("expected to be unable to update non-existant user") } - backend = NewBackendMemory().(*backendMemory) - backend.Users = append(backend.Users, &User{PrimaryEmail: "email"}) + backend = newBackendMemory().(*backendMemory) + backend.Users = append(backend.Users, &user{PrimaryEmail: "email"}) err = backend.UpdateUser("email", "fullname", "company", "pictureUrl") if err != nil { t.Error("expected success", err) @@ -153,25 +153,25 @@ func TestMemoryUpdateUser(t *testing.T) { } func TestMemoryCreateLogin(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) if login, err := backend.CreateLogin("email", "passwordHash", "fullName", "homeDirectory", 1, 1, "mailQuota", "fileQuota"); err != nil || login.Email != "email" { t.Error("expected valid login", login) } } func TestMemoryUpdateEmail(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) backend.UpdateEmail("email", "password", "newEmail") } func TestMemoryUpdatePassword(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) backend.UpdatePassword("email", "oldPassword", "newPassword") } func TestMemoryInvalidateSession(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) - backend.Sessions = append(backend.Sessions, &UserLoginSession{SessionHash: "hash"}) + backend := newBackendMemory().(*backendMemory) + backend.Sessions = append(backend.Sessions, &loginSession{SessionHash: "hash"}) backend.InvalidateSession("hash") if len(backend.Sessions) != 0 { t.Error("Expected to remove session") @@ -179,13 +179,13 @@ func TestMemoryInvalidateSession(t *testing.T) { } func TestMemoryInvalidateSessions(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) backend.InvalidateSessions("email") } func TestMemoryInvalidateRememberMe(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) - backend.RememberMes = append(backend.RememberMes, &UserLoginRememberMe{Selector: "selector"}) + backend := newBackendMemory().(*backendMemory) + backend.RememberMes = append(backend.RememberMes, &rememberMeSession{Selector: "selector"}) backend.InvalidateRememberMe("selector") if len(backend.RememberMes) != 0 { t.Error("Expected to remove remember me") @@ -193,16 +193,16 @@ func TestMemoryInvalidateRememberMe(t *testing.T) { } func TestMemoryClose(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) backend.Close() } func TestToString(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) - backend.Users = append(backend.Users, &User{}) - backend.Logins = append(backend.Logins, &UserLogin{}) - backend.Sessions = append(backend.Sessions, &UserLoginSession{}) - backend.RememberMes = append(backend.RememberMes, &UserLoginRememberMe{}) + backend := newBackendMemory().(*backendMemory) + backend.Users = append(backend.Users, &user{}) + backend.Logins = append(backend.Logins, &userLogin{}) + backend.Sessions = append(backend.Sessions, &loginSession{}) + backend.RememberMes = append(backend.RememberMes, &rememberMeSession{}) actual := backend.ToString() expected := "Users:\n { 0}\nLogins:\n { 0 }\nSessions:\n { 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC}\nRememberMe:\n { 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC}\n" @@ -212,14 +212,14 @@ func TestToString(t *testing.T) { } func TestGetLoginProvider(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) if backend.getLoginProvider("bogus") != nil { t.Error("expected no provider") } } func TestGetLoginByUser(t *testing.T) { - backend := NewBackendMemory().(*backendMemory) + backend := newBackendMemory().(*backendMemory) if backend.getLoginByUser("email", "bogus") != nil { t.Error("expected no login") } diff --git a/backendRedisSession.go b/backendRedisSession.go index 279d55c..aac04ff 100644 --- a/backendRedisSession.go +++ b/backendRedisSession.go @@ -12,7 +12,7 @@ type backendRedisSession struct { prefix string } -func NewBackendRedisSession(server string, port int, password string, maxIdle, maxConnections int, keyPrefix string) SessionBackender { +func newBackendRedisSession(server string, port int, password string, maxIdle, maxConnections int, keyPrefix string) sessionBackender { r := onedb.NewRedis(server, port, password, maxIdle, maxConnections) return &backendRedisSession{db: r, prefix: keyPrefix} } @@ -24,7 +24,7 @@ func (r *backendRedisSession) CreateEmailSession(email, emailVerifyHash string) func (r *backendRedisSession) GetEmailSession(emailVerifyHash string) (*emailSession, error) { session := &emailSession{} - return session, r.db.QueryStructRow(onedb.NewRedisGetCommand(r.getEmailSessionUrl(emailVerifyHash)), session) + return session, r.db.QueryStructRow(onedb.NewRedisGetCommand(r.getEmailSessionKey(emailVerifyHash)), session) } func (r *backendRedisSession) DeleteEmailSession(emailVerifyHash string) error { @@ -32,16 +32,16 @@ func (r *backendRedisSession) DeleteEmailSession(emailVerifyHash string) error { } func (r *backendRedisSession) CreateSession(email, sessionHash string, sessionRenewTimeUTC, sessionExpireTimeUTC time.Time, - includeRememberMe bool, rememberMeSelector, rememberMeTokenHash string, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC time.Time) (*UserLoginSession, *UserLoginRememberMe, error) { - session := UserLoginSession{Email: email, SessionHash: sessionHash, RenewTimeUTC: sessionRenewTimeUTC, ExpireTimeUTC: sessionExpireTimeUTC} + includeRememberMe bool, rememberMeSelector, rememberMeTokenHash string, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC time.Time) (*loginSession, *rememberMeSession, error) { + session := loginSession{Email: email, SessionHash: sessionHash, RenewTimeUTC: sessionRenewTimeUTC, ExpireTimeUTC: sessionExpireTimeUTC} err := r.saveSession(&session) if err != nil { return nil, nil, err } - var rememberMe UserLoginRememberMe + var rememberMe rememberMeSession if includeRememberMe { - rememberMe = UserLoginRememberMe{Email: email, Selector: rememberMeSelector, TokenHash: rememberMeTokenHash, RenewTimeUTC: rememberMeRenewTimeUTC, ExpireTimeUTC: rememberMeExpireTimeUTC} + rememberMe = rememberMeSession{Email: email, Selector: rememberMeSelector, TokenHash: rememberMeTokenHash, RenewTimeUTC: rememberMeRenewTimeUTC, ExpireTimeUTC: rememberMeExpireTimeUTC} err = r.saveRememberMe(&rememberMe) if err != nil { return nil, nil, err @@ -51,14 +51,14 @@ func (r *backendRedisSession) CreateSession(email, sessionHash string, sessionRe return &session, &rememberMe, nil } -func (r *backendRedisSession) GetSession(sessionHash string) (*UserLoginSession, error) { - session := &UserLoginSession{} - return session, r.db.QueryStructRow(onedb.NewRedisGetCommand(r.getSessionUrl(sessionHash)), session) +func (r *backendRedisSession) GetSession(sessionHash string) (*loginSession, error) { + session := &loginSession{} + return session, r.db.QueryStructRow(onedb.NewRedisGetCommand(r.getSessionKey(sessionHash)), session) } -func (r *backendRedisSession) RenewSession(sessionHash string, renewTimeUTC time.Time) (*UserLoginSession, error) { - session := &UserLoginSession{} - key := r.getSessionUrl(sessionHash) +func (r *backendRedisSession) RenewSession(sessionHash string, renewTimeUTC time.Time) (*loginSession, error) { + session := &loginSession{} + key := r.getSessionKey(sessionHash) err := r.db.QueryStructRow(onedb.NewRedisGetCommand(key), session) if err != nil { return nil, err @@ -68,21 +68,21 @@ func (r *backendRedisSession) RenewSession(sessionHash string, renewTimeUTC time } func (r *backendRedisSession) InvalidateSession(sessionHash string) error { - return r.db.Execute(onedb.NewRedisDelCommand(r.getSessionUrl(sessionHash))) + return r.db.Execute(onedb.NewRedisDelCommand(r.getSessionKey(sessionHash))) } func (r *backendRedisSession) InvalidateSessions(email string) error { return nil } -func (r *backendRedisSession) GetRememberMe(selector string) (*UserLoginRememberMe, error) { - rememberMe := &UserLoginRememberMe{} - return rememberMe, r.db.QueryStructRow(onedb.NewRedisGetCommand(r.getRememberMeUrl(selector)), rememberMe) +func (r *backendRedisSession) GetRememberMe(selector string) (*rememberMeSession, error) { + rememberMe := &rememberMeSession{} + return rememberMe, r.db.QueryStructRow(onedb.NewRedisGetCommand(r.getRememberMeKey(selector)), rememberMe) } -func (r *backendRedisSession) RenewRememberMe(selector string, renewTimeUTC time.Time) (*UserLoginRememberMe, error) { - rememberMe := &UserLoginRememberMe{} - err := r.db.QueryStructRow(onedb.NewRedisGetCommand(r.getRememberMeUrl(selector)), rememberMe) +func (r *backendRedisSession) RenewRememberMe(selector string, renewTimeUTC time.Time) (*rememberMeSession, error) { + rememberMe := &rememberMeSession{} + err := r.db.QueryStructRow(onedb.NewRedisGetCommand(r.getRememberMeKey(selector)), rememberMe) if err != nil { return nil, err } else if rememberMe.ExpireTimeUTC.Before(time.Now().UTC()) { @@ -95,7 +95,7 @@ func (r *backendRedisSession) RenewRememberMe(selector string, renewTimeUTC time } func (r *backendRedisSession) InvalidateRememberMe(selector string) error { - return r.db.Execute(onedb.NewRedisDelCommand(r.getRememberMeUrl(selector))) + return r.db.Execute(onedb.NewRedisDelCommand(r.getRememberMeKey(selector))) } func (r *backendRedisSession) Close() error { @@ -103,32 +103,32 @@ func (r *backendRedisSession) Close() error { } func (r *backendRedisSession) saveEmailSession(session *emailSession) error { - return r.save(r.getEmailSessionUrl(session.EmailVerifyHash), session, emailExpireMins*60) + return r.save(r.getEmailSessionKey(session.EmailVerifyHash), session, emailExpireMins*60) } -func (r *backendRedisSession) saveSession(session *UserLoginSession) error { +func (r *backendRedisSession) saveSession(session *loginSession) error { if time.Since(session.ExpireTimeUTC).Seconds() >= 0 { return errors.New("Unable to save expired session") } - return r.save(r.getSessionUrl(session.SessionHash), session, round(rememberMeExpireDuration.Seconds())) + return r.save(r.getSessionKey(session.SessionHash), session, round(rememberMeExpireDuration.Seconds())) } -func (r *backendRedisSession) saveRememberMe(rememberMe *UserLoginRememberMe) error { +func (r *backendRedisSession) saveRememberMe(rememberMe *rememberMeSession) error { if time.Since(rememberMe.ExpireTimeUTC).Seconds() >= 0 { return errors.New("Unable to save expired rememberMe") } - return r.save(r.getRememberMeUrl(rememberMe.Selector), rememberMe, round(rememberMeExpireDuration.Seconds())) + return r.save(r.getRememberMeKey(rememberMe.Selector), rememberMe, round(rememberMeExpireDuration.Seconds())) } -func (r *backendRedisSession) getEmailSessionUrl(emailVerifyHash string) string { +func (r *backendRedisSession) getEmailSessionKey(emailVerifyHash string) string { return r.prefix + "/email/" + emailVerifyHash } -func (r *backendRedisSession) getSessionUrl(sessionHash string) string { +func (r *backendRedisSession) getSessionKey(sessionHash string) string { return r.prefix + "/session/" + sessionHash } -func (r *backendRedisSession) getRememberMeUrl(selector string) string { +func (r *backendRedisSession) getRememberMeKey(selector string) string { return r.prefix + "/rememberMe/" + selector } diff --git a/backendRedisSession_test.go b/backendRedisSession_test.go index 59ffce1..7fe3591 100644 --- a/backendRedisSession_test.go +++ b/backendRedisSession_test.go @@ -38,7 +38,7 @@ func TestRedisCreateSession(t *testing.T) { } func TestRedisGetSession(t *testing.T) { - data := UserLoginSession{Email: "test@test.com", SessionHash: "hash"} + data := loginSession{Email: "test@test.com", SessionHash: "hash"} m := onedb.NewMock(nil, nil, data) r := backendRedisSession{db: m, prefix: "test"} s, err := r.GetSession("hash") @@ -49,7 +49,7 @@ func TestRedisGetSession(t *testing.T) { func TestRedisRenewSession(t *testing.T) { // success - data := UserLoginSession{Email: "test@test.com", SessionHash: "hash", ExpireTimeUTC: time.Now().AddDate(1, 0, 0)} + data := loginSession{Email: "test@test.com", SessionHash: "hash", ExpireTimeUTC: time.Now().AddDate(1, 0, 0)} m := onedb.NewMock(nil, nil, data) r := backendRedisSession{db: m, prefix: "test"} s, err := r.RenewSession("hash", time.Now().AddDate(1, 0, 0)) @@ -68,7 +68,7 @@ func TestRedisRenewSession(t *testing.T) { func TestRedisInvalidateSession(t *testing.T) { // success - data := UserLoginSession{Email: "test@test.com", SessionHash: "hash", ExpireTimeUTC: time.Now().AddDate(1, 0, 0)} + data := loginSession{Email: "test@test.com", SessionHash: "hash", ExpireTimeUTC: time.Now().AddDate(1, 0, 0)} m := onedb.NewMock(nil, nil, data) r := backendRedisSession{db: m, prefix: "test"} if err := r.InvalidateSession("hash"); err != nil { @@ -78,7 +78,7 @@ func TestRedisInvalidateSession(t *testing.T) { func TestRedisGetRememberMe(t *testing.T) { // success - data := UserLoginRememberMe{Selector: "selector"} + data := rememberMeSession{Selector: "selector"} m := onedb.NewMock(nil, nil, data) r := backendRedisSession{db: m, prefix: "test"} rememberMe, err := r.GetRememberMe("selector") @@ -89,7 +89,7 @@ func TestRedisGetRememberMe(t *testing.T) { func TestRedisRenewRememberMe(t *testing.T) { // success - data := UserLoginRememberMe{Selector: "selector", ExpireTimeUTC: time.Now().AddDate(1, 0, 0)} + data := rememberMeSession{Selector: "selector", ExpireTimeUTC: time.Now().AddDate(1, 0, 0)} m := onedb.NewMock(nil, nil, data) r := backendRedisSession{db: m, prefix: "test"} renew := time.Now().AddDate(0, 1, 0) @@ -107,7 +107,7 @@ func TestRedisRenewRememberMe(t *testing.T) { } // expired - data = UserLoginRememberMe{Selector: "selector", ExpireTimeUTC: time.Now().AddDate(0, 0, -1)} + data = rememberMeSession{Selector: "selector", ExpireTimeUTC: time.Now().AddDate(0, 0, -1)} m = onedb.NewMock(nil, nil, data) r = backendRedisSession{db: m, prefix: "test"} remember, err = r.RenewRememberMe("selector", time.Now()) @@ -116,7 +116,7 @@ func TestRedisRenewRememberMe(t *testing.T) { } // invalid renew time - data = UserLoginRememberMe{Selector: "selector", ExpireTimeUTC: time.Now().AddDate(0, 0, 1)} + data = rememberMeSession{Selector: "selector", ExpireTimeUTC: time.Now().AddDate(0, 0, 1)} m = onedb.NewMock(nil, nil, data) r = backendRedisSession{db: m, prefix: "test"} remember, err = r.RenewRememberMe("selector", time.Now().AddDate(0, 0, -1)) @@ -126,7 +126,7 @@ func TestRedisRenewRememberMe(t *testing.T) { } func TestRedisInvalidateRememberMe(t *testing.T) { - data := UserLoginRememberMe{Selector: "selector", ExpireTimeUTC: time.Now().AddDate(1, 0, 0)} + data := rememberMeSession{Selector: "selector", ExpireTimeUTC: time.Now().AddDate(1, 0, 0)} m := onedb.NewMock(nil, nil, data) r := backendRedisSession{db: m, prefix: "test"} if err := r.InvalidateRememberMe("selector"); err != nil { diff --git a/backend_test.go b/backend_test.go index 5cb69ea..47f7c63 100644 --- a/backend_test.go +++ b/backend_test.go @@ -19,7 +19,7 @@ func TestAuthError(t *testing.T) { } func TestGetLogin(t *testing.T) { - m := &MockBackend{GetUserLoginReturn: loginSuccess()} + m := &mockBackend{GetUserLoginReturn: loginSuccess()} b := backend{u: m, l: m, s: m} b.GetLogin("email", "provider") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "GetLogin" { @@ -28,7 +28,7 @@ func TestGetLogin(t *testing.T) { } func TestBackendCreateSession(t *testing.T) { - m := &MockBackend{CreateSessionReturn: sessionRemember(time.Now(), time.Now())} + m := &mockBackend{CreateSessionReturn: sessionRemember(time.Now(), time.Now())} b := backend{u: m, l: m, s: m} b.CreateSession("test@test.com", "hash", time.Now(), time.Now(), false, "", "", time.Now(), time.Now()) if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "CreateSession" { @@ -37,7 +37,7 @@ func TestBackendCreateSession(t *testing.T) { } func TestBackendGetSession(t *testing.T) { - m := &MockBackend{GetSessionReturn: sessionErr()} + m := &mockBackend{GetSessionReturn: sessionErr()} b := backend{u: m, l: m, s: m} b.GetSession("hash") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "GetSession" { @@ -46,7 +46,7 @@ func TestBackendGetSession(t *testing.T) { } func TestBackendRenewSession(t *testing.T) { - m := &MockBackend{RenewSessionReturn: sessionErr()} + m := &mockBackend{RenewSessionReturn: sessionErr()} b := backend{u: m, l: m, s: m} b.RenewSession("hash", time.Now()) if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "RenewSession" { @@ -55,7 +55,7 @@ func TestBackendRenewSession(t *testing.T) { } func TestBackendGetRememberMe(t *testing.T) { - m := &MockBackend{GetRememberMeReturn: rememberErr()} + m := &mockBackend{GetRememberMeReturn: rememberErr()} b := backend{u: m, l: m, s: m} b.GetRememberMe("selector") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "GetRememberMe" { @@ -64,7 +64,7 @@ func TestBackendGetRememberMe(t *testing.T) { } func TestBackendRenewRememberMe(t *testing.T) { - m := &MockBackend{RenewRememberMeReturn: rememberErr()} + m := &mockBackend{RenewRememberMeReturn: rememberErr()} b := backend{u: m, l: m, s: m} b.RenewRememberMe("selector", time.Now()) if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "RenewRememberMe" { @@ -73,7 +73,7 @@ func TestBackendRenewRememberMe(t *testing.T) { } func TestBackendAddUser(t *testing.T) { - m := &MockBackend{AddUserReturn: nil} + m := &mockBackend{AddUserReturn: nil} b := backend{u: m, l: m, s: m} b.AddUser("mail") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "AddUser" { @@ -82,7 +82,7 @@ func TestBackendAddUser(t *testing.T) { } func TestBackendGetEmailSession(t *testing.T) { - m := &MockBackend{GetEmailSessionReturn: getEmailSessionErr()} + m := &mockBackend{getEmailSessionReturn: getEmailSessionErr()} b := backend{u: m, l: m, s: m} b.GetEmailSession("hash") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "GetEmailSession" { @@ -91,7 +91,7 @@ func TestBackendGetEmailSession(t *testing.T) { } func TestBackendUpdateUser(t *testing.T) { - m := &MockBackend{} + m := &mockBackend{} b := backend{u: m, l: m, s: m} b.UpdateUser("hash", "name", "company", "url") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "UpdateUser" { @@ -100,7 +100,7 @@ func TestBackendUpdateUser(t *testing.T) { } func TestBackendCreateLogin(t *testing.T) { - m := &MockBackend{CreateLoginReturn: loginErr()} + m := &mockBackend{CreateLoginReturn: loginErr()} b := backend{u: m, l: m, s: m} b.CreateLogin("email", "hash", "name", "homeDir", 1, 1, "quota", "fileQuota") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "CreateLogin" { @@ -109,7 +109,7 @@ func TestBackendCreateLogin(t *testing.T) { } func TestBackendUpdateEmail(t *testing.T) { - m := &MockBackend{UpdateEmailReturn: sessionErr()} + m := &mockBackend{UpdateEmailReturn: sessionErr()} b := backend{u: m, l: m, s: m} b.UpdateEmail("email", "password", "newEmail") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "UpdateEmail" { @@ -118,7 +118,7 @@ func TestBackendUpdateEmail(t *testing.T) { } func TestBackendUpdatePassword(t *testing.T) { - m := &MockBackend{UpdatePasswordReturn: sessionErr()} + m := &mockBackend{UpdatePasswordReturn: sessionErr()} b := backend{u: m, l: m, s: m} b.UpdatePassword("email", "oldPassword", "newPassword") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "UpdatePassword" { @@ -127,7 +127,7 @@ func TestBackendUpdatePassword(t *testing.T) { } func TestBackendInvalidateSession(t *testing.T) { - m := &MockBackend{} + m := &mockBackend{} b := backend{u: m, l: m, s: m} b.InvalidateSession("hash") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "InvalidateSession" { @@ -136,7 +136,7 @@ func TestBackendInvalidateSession(t *testing.T) { } func TestBackendInvalidateSessions(t *testing.T) { - m := &MockBackend{} + m := &mockBackend{} b := backend{u: m, l: m, s: m} b.InvalidateSessions("email") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "InvalidateSessions" { @@ -145,7 +145,7 @@ func TestBackendInvalidateSessions(t *testing.T) { } func TestBackendInvalidateRememberMe(t *testing.T) { - m := &MockBackend{} + m := &mockBackend{} b := backend{u: m, l: m, s: m} b.InvalidateRememberMe("selector") if len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "InvalidateRememberMe" { @@ -155,7 +155,7 @@ func TestBackendInvalidateRememberMe(t *testing.T) { func TestBackendClose(t *testing.T) { // all succeed - m := &MockBackend{} + m := &mockBackend{} b := backend{u: m, l: m, s: m} b.Close() if len(m.MethodsCalled) != 3 || m.MethodsCalled[0] != "Close" || m.MethodsCalled[1] != "Close" || m.MethodsCalled[2] != "Close" { @@ -163,8 +163,8 @@ func TestBackendClose(t *testing.T) { } // error on session close - m = &MockBackend{} - e := &MockBackend{ErrReturn: errors.New("failed")} + m = &mockBackend{} + e := &mockBackend{ErrReturn: errors.New("failed")} b = backend{u: m, l: m, s: e} b.Close() if len(m.MethodsCalled) != 0 || len(e.MethodsCalled) != 1 || e.MethodsCalled[0] != "Close" { @@ -172,8 +172,8 @@ func TestBackendClose(t *testing.T) { } // error on user close - m = &MockBackend{} - e = &MockBackend{ErrReturn: errors.New("failed")} + m = &mockBackend{} + e = &mockBackend{ErrReturn: errors.New("failed")} b = backend{u: e, l: m, s: m} b.Close() if len(e.MethodsCalled) != 1 || len(m.MethodsCalled) != 1 || m.MethodsCalled[0] != "Close" || e.MethodsCalled[0] != "Close" { @@ -181,8 +181,8 @@ func TestBackendClose(t *testing.T) { } // error on login close - m = &MockBackend{} - e = &MockBackend{ErrReturn: errors.New("failed")} + m = &mockBackend{} + e = &mockBackend{ErrReturn: errors.New("failed")} b = backend{u: m, l: e, s: m} b.Close() if len(m.MethodsCalled) != 2 || len(e.MethodsCalled) != 1 || m.MethodsCalled[0] != "Close" || m.MethodsCalled[1] != "Close" || e.MethodsCalled[0] != "Close" { @@ -193,38 +193,38 @@ func TestBackendClose(t *testing.T) { /***********************************************************************/ type LoginReturn struct { - Login *UserLogin + Login *userLogin Err error } type SessionReturn struct { - Session *UserLoginSession + Session *loginSession Err error } type SessionRememberReturn struct { - Session *UserLoginSession - RememberMe *UserLoginRememberMe + Session *loginSession + RememberMe *rememberMeSession Err error } type RememberMeReturn struct { - RememberMe *UserLoginRememberMe + RememberMe *rememberMeSession Err error } type GetUserReturn struct { - User *User + User *user Err error } -type GetEmailSessionReturn struct { +type getEmailSessionReturn struct { Session *emailSession Err error } -type MockBackend struct { - Backender +type mockBackend struct { + backender GetUserLoginReturn *LoginReturn ExpirationReturn *time.Time GetSessionReturn *SessionReturn @@ -232,7 +232,7 @@ type MockBackend struct { RenewSessionReturn *SessionReturn AddUserReturn error GetUserReturn *GetUserReturn - GetEmailSessionReturn *GetEmailSessionReturn + getEmailSessionReturn *getEmailSessionReturn CreateLoginReturn *LoginReturn UpdateEmailReturn *SessionReturn UpdatePasswordReturn *SessionReturn @@ -243,100 +243,100 @@ type MockBackend struct { MethodsCalled []string } -func (b *MockBackend) GetLogin(email, loginProvider string) (*UserLogin, error) { +func (b *mockBackend) GetLogin(email, loginProvider string) (*userLogin, error) { b.MethodsCalled = append(b.MethodsCalled, "GetLogin") return b.GetUserLoginReturn.Login, b.GetUserLoginReturn.Err } -func (b *MockBackend) GetSession(sessionHash string) (*UserLoginSession, error) { +func (b *mockBackend) GetSession(sessionHash string) (*loginSession, error) { b.MethodsCalled = append(b.MethodsCalled, "GetSession") return b.GetSessionReturn.Session, b.GetSessionReturn.Err } -func (b *MockBackend) CreateSession(email, sessionHash string, sessionRenewTimeUTC, sessionExpireTimeUTC time.Time, rememberMe bool, rememberMeSelector, rememberMeTokenHash string, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC time.Time) (*UserLoginSession, *UserLoginRememberMe, error) { +func (b *mockBackend) CreateSession(email, sessionHash string, sessionRenewTimeUTC, sessionExpireTimeUTC time.Time, rememberMe bool, rememberMeSelector, rememberMeTokenHash string, rememberMeRenewTimeUTC, rememberMeExpireTimeUTC time.Time) (*loginSession, *rememberMeSession, error) { b.MethodsCalled = append(b.MethodsCalled, "CreateSession") return b.CreateSessionReturn.Session, b.CreateSessionReturn.RememberMe, b.CreateSessionReturn.Err } -func (b *MockBackend) RenewSession(sessionHash string, renewTimeUTC time.Time) (*UserLoginSession, error) { +func (b *mockBackend) RenewSession(sessionHash string, renewTimeUTC time.Time) (*loginSession, error) { b.MethodsCalled = append(b.MethodsCalled, "RenewSession") return b.RenewSessionReturn.Session, b.RenewSessionReturn.Err } -func (b *MockBackend) GetRememberMe(selector string) (*UserLoginRememberMe, error) { +func (b *mockBackend) GetRememberMe(selector string) (*rememberMeSession, error) { b.MethodsCalled = append(b.MethodsCalled, "GetRememberMe") return b.GetRememberMeReturn.RememberMe, b.GetRememberMeReturn.Err } -func (b *MockBackend) RenewRememberMe(selector string, renewTimeUTC time.Time) (*UserLoginRememberMe, error) { +func (b *mockBackend) RenewRememberMe(selector string, renewTimeUTC time.Time) (*rememberMeSession, error) { b.MethodsCalled = append(b.MethodsCalled, "RenewRememberMe") return b.RenewRememberMeReturn.RememberMe, b.RenewRememberMeReturn.Err } -func (b *MockBackend) AddUser(email string) error { +func (b *mockBackend) AddUser(email string) error { b.MethodsCalled = append(b.MethodsCalled, "AddUser") return b.AddUserReturn } -func (b *MockBackend) CreateEmailSession(email, emailVerifyHash string) error { +func (b *mockBackend) CreateEmailSession(email, emailVerifyHash string) error { b.MethodsCalled = append(b.MethodsCalled, "CreateEmailSession") return b.ErrReturn } -func (b *MockBackend) GetEmailSession(emailVerifyHash string) (*emailSession, error) { +func (b *mockBackend) GetEmailSession(emailVerifyHash string) (*emailSession, error) { b.MethodsCalled = append(b.MethodsCalled, "GetEmailSession") - return b.GetEmailSessionReturn.Session, b.GetEmailSessionReturn.Err + return b.getEmailSessionReturn.Session, b.getEmailSessionReturn.Err } -func (b *MockBackend) DeleteEmailSession(emailVerifyHash string) error { +func (b *mockBackend) DeleteEmailSession(emailVerifyHash string) error { b.MethodsCalled = append(b.MethodsCalled, "DeleteEmailSession") return b.ErrReturn } -func (b *MockBackend) GetUser(email string) (*User, error) { +func (b *mockBackend) GetUser(email string) (*user, error) { b.MethodsCalled = append(b.MethodsCalled, "GetUser") return b.GetUserReturn.User, b.GetUserReturn.Err } -func (b *MockBackend) UpdateUser(email, fullname, company, pictureURL string) error { +func (b *mockBackend) UpdateUser(email, fullname, company, pictureURL string) error { b.MethodsCalled = append(b.MethodsCalled, "UpdateUser") return b.ErrReturn } -func (b *MockBackend) CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*UserLogin, error) { +func (b *mockBackend) CreateLogin(email, passwordHash, fullName, homeDirectory string, uidNumber, gidNumber int, mailQuota, fileQuota string) (*userLogin, error) { b.MethodsCalled = append(b.MethodsCalled, "CreateLogin") return b.CreateLoginReturn.Login, b.CreateLoginReturn.Err } -func (b *MockBackend) UpdateEmail(email string, password string, newEmail string) (*UserLoginSession, error) { +func (b *mockBackend) UpdateEmail(email string, password string, newEmail string) (*loginSession, error) { b.MethodsCalled = append(b.MethodsCalled, "UpdateEmail") return b.UpdateEmailReturn.Session, b.UpdateEmailReturn.Err } -func (b *MockBackend) UpdatePassword(email string, oldPassword string, newPassword string) (*UserLoginSession, error) { +func (b *mockBackend) UpdatePassword(email string, oldPassword string, newPassword string) (*loginSession, error) { b.MethodsCalled = append(b.MethodsCalled, "UpdatePassword") return b.UpdatePasswordReturn.Session, b.UpdatePasswordReturn.Err } -func (b *MockBackend) InvalidateSession(sessionHash string) error { +func (b *mockBackend) InvalidateSession(sessionHash string) error { b.MethodsCalled = append(b.MethodsCalled, "InvalidateSession") return b.ErrReturn } -func (b *MockBackend) InvalidateSessions(email string) error { +func (b *mockBackend) InvalidateSessions(email string) error { b.MethodsCalled = append(b.MethodsCalled, "InvalidateSessions") return b.ErrReturn } -func (b *MockBackend) InvalidateRememberMe(selector string) error { +func (b *mockBackend) InvalidateRememberMe(selector string) error { b.MethodsCalled = append(b.MethodsCalled, "InvalidateRememberMe") return b.ErrReturn } -func (b *MockBackend) Close() error { +func (b *mockBackend) Close() error { b.MethodsCalled = append(b.MethodsCalled, "Close") return b.ErrReturn } func loginSuccess() *LoginReturn { - return &LoginReturn{&UserLogin{Email: "test@test.com", ProviderKey: "$6$rounds=200000$pYt48w3PgDcRoCMx$sxbuADDhNI9nNe35HcrFYW7vpWLLMNiPBKcbqOgaRxTBYE8hePJWvmuN9dp.783JmDZBhDJRG956Wc/fzghhh."}, nil} // cryptoHash of "correctPassword" + return &LoginReturn{&userLogin{Email: "test@test.com", ProviderKey: "$6$rounds=200000$pYt48w3PgDcRoCMx$sxbuADDhNI9nNe35HcrFYW7vpWLLMNiPBKcbqOgaRxTBYE8hePJWvmuN9dp.783JmDZBhDJRG956Wc/fzghhh."}, nil} // cryptoHash of "correctPassword" } func loginErr() *LoginReturn { @@ -344,38 +344,38 @@ func loginErr() *LoginReturn { } func sessionSuccess(renewTimeUTC, expireTimeUTC time.Time) *SessionReturn { - return &SessionReturn{&UserLoginSession{"test@test.com", "sessionHash", renewTimeUTC, expireTimeUTC}, nil} + return &SessionReturn{&loginSession{"test@test.com", "sessionHash", renewTimeUTC, expireTimeUTC}, nil} } func sessionErr() *SessionReturn { - return &SessionReturn{&UserLoginSession{}, errors.New("failed")} + return &SessionReturn{&loginSession{}, errors.New("failed")} } func rememberMe(renewTimeUTC, expireTimeUTC time.Time) *RememberMeReturn { // hash of the word "token" - return &RememberMeReturn{&UserLoginRememberMe{TokenHash: "PEaenWxYddN6Q_NT1PiOYfz4EsZu7jRXRlpAsNpBU-A=", ExpireTimeUTC: expireTimeUTC, RenewTimeUTC: renewTimeUTC}, nil} + return &RememberMeReturn{&rememberMeSession{TokenHash: "PEaenWxYddN6Q_NT1PiOYfz4EsZu7jRXRlpAsNpBU-A=", ExpireTimeUTC: expireTimeUTC, RenewTimeUTC: renewTimeUTC}, nil} } func rememberErr() *RememberMeReturn { - return &RememberMeReturn{&UserLoginRememberMe{}, errors.New("failed")} + return &RememberMeReturn{&rememberMeSession{}, errors.New("failed")} } func sessionRemember(renewTimeUTC, expireTimeUTC time.Time) *SessionRememberReturn { - return &SessionRememberReturn{&UserLoginSession{"test@test.com", "sessionHash", renewTimeUTC, expireTimeUTC}, &UserLoginRememberMe{TokenHash: "PEaenWxYddN6Q_NT1PiOYfz4EsZu7jRXRlpAsNpBU-A=", ExpireTimeUTC: expireTimeUTC, RenewTimeUTC: renewTimeUTC}, nil} + return &SessionRememberReturn{&loginSession{"test@test.com", "sessionHash", renewTimeUTC, expireTimeUTC}, &rememberMeSession{TokenHash: "PEaenWxYddN6Q_NT1PiOYfz4EsZu7jRXRlpAsNpBU-A=", ExpireTimeUTC: expireTimeUTC, RenewTimeUTC: renewTimeUTC}, nil} } func sessionRememberErr() *SessionRememberReturn { return &SessionRememberReturn{nil, nil, errors.New("failed")} } -func getEmailSessionSuccess() *GetEmailSessionReturn { - return &GetEmailSessionReturn{&emailSession{Email: "email", EmailVerifyHash: "hash"}, nil} +func getEmailSessionSuccess() *getEmailSessionReturn { + return &getEmailSessionReturn{&emailSession{Email: "email", EmailVerifyHash: "hash"}, nil} } -func getEmailSessionErr() *GetEmailSessionReturn { - return &GetEmailSessionReturn{nil, errors.New("failed")} +func getEmailSessionErr() *getEmailSessionReturn { + return &getEmailSessionReturn{nil, errors.New("failed")} } func getUserSuccess() *GetUserReturn { - return &GetUserReturn{&User{FullName: "name", PrimaryEmail: "test@test.com"}, nil} + return &GetUserReturn{&user{FullName: "name", PrimaryEmail: "test@test.com"}, nil} } func getUserErr() *GetUserReturn { diff --git a/cookieStore.go b/cookieStore.go index 89f15fd..06be47e 100644 --- a/cookieStore.go +++ b/cookieStore.go @@ -1,89 +1,89 @@ -// This file taken with some modification from authboss -// github.com/go-authboss -package main - -import ( - "net/http" - "time" - - "github.com/gorilla/securecookie" -) - -var cookieStoreInstance *securecookie.SecureCookie - -type CookieStorer interface { - Get(key string, result interface{}) error - Put(key string, value interface{}) error - PutWithExpire(key string, expireMins int, value interface{}) error - Delete(key string) -} - -type cookieStore struct { - w http.ResponseWriter - r *http.Request - secureOnly bool -} - -func NewCookieStore(w http.ResponseWriter, r *http.Request, cookieKey []byte, secureOnly bool) CookieStorer { - if cookieStoreInstance == nil { - cookieStoreInstance = securecookie.New(cookieKey, nil) - } - return &cookieStore{w, r, secureOnly} -} - -func (s *cookieStore) Encode(key string, value interface{}) (string, error) { - return cookieStoreInstance.Encode(key, value) -} - -func (s *cookieStore) Decode(key string, value string, result interface{}) error { - return cookieStoreInstance.Decode(key, value, result) -} - -func (s *cookieStore) Get(key string, result interface{}) error { - cookie, err := s.r.Cookie(key) - if err != nil { - return err - } - - err = s.Decode(key, cookie.Value, result) - if err != nil { - s.Delete(key) // problem decoding the cookie, so delete - return err - } - return nil -} - -func (s *cookieStore) Put(key string, value interface{}) error { - return s.PutWithExpire(key, 60*24*30, value) // default to 30 day expiration -} - -func (s *cookieStore) PutWithExpire(key string, expireMins int, value interface{}) error { - encoded, err := s.Encode(key, value) - if err != nil { - return err - } - - http.SetCookie(s.w, newCookie(key, encoded, s.secureOnly, expireMins)) - return nil -} - -func (s *cookieStore) Delete(key string) { - cookie := &http.Cookie{ - MaxAge: -1, - Name: key, - Path: "/", - } - http.SetCookie(s.w, cookie) -} - -func newCookie(name string, value string, secureOnly bool, expireMins int) *http.Cookie { - return &http.Cookie{ - Expires: time.Now().UTC().Add(time.Duration(expireMins) * time.Minute), - Name: name, - Value: value, - Path: "/", - HttpOnly: true, - Secure: secureOnly, - MaxAge: expireMins, - } -} +// This file taken with some modification from authboss +// github.com/go-authboss +package main + +import ( + "net/http" + "time" + + "github.com/gorilla/securecookie" +) + +var cookieStoreInstance *securecookie.SecureCookie + +type cookieStorer interface { + Get(key string, result interface{}) error + Put(key string, value interface{}) error + PutWithExpire(key string, expireMins int, value interface{}) error + Delete(key string) +} + +type cookieStore struct { + w http.ResponseWriter + r *http.Request + secureOnly bool +} + +func newCookieStore(w http.ResponseWriter, r *http.Request, cookieKey []byte, secureOnly bool) cookieStorer { + if cookieStoreInstance == nil { + cookieStoreInstance = securecookie.New(cookieKey, nil) + } + return &cookieStore{w, r, secureOnly} +} + +func (s *cookieStore) Encode(key string, value interface{}) (string, error) { + return cookieStoreInstance.Encode(key, value) +} + +func (s *cookieStore) Decode(key string, value string, result interface{}) error { + return cookieStoreInstance.Decode(key, value, result) +} + +func (s *cookieStore) Get(key string, result interface{}) error { + cookie, err := s.r.Cookie(key) + if err != nil { + return err + } + + err = s.Decode(key, cookie.Value, result) + if err != nil { + s.Delete(key) // problem decoding the cookie, so delete + return err + } + return nil +} + +func (s *cookieStore) Put(key string, value interface{}) error { + return s.PutWithExpire(key, 60*24*30, value) // default to 30 day expiration +} + +func (s *cookieStore) PutWithExpire(key string, expireMins int, value interface{}) error { + encoded, err := s.Encode(key, value) + if err != nil { + return err + } + + http.SetCookie(s.w, newCookie(key, encoded, s.secureOnly, expireMins)) + return nil +} + +func (s *cookieStore) Delete(key string) { + cookie := &http.Cookie{ + MaxAge: -1, + Name: key, + Path: "/", + } + http.SetCookie(s.w, cookie) +} + +func newCookie(name string, value string, secureOnly bool, expireMins int) *http.Cookie { + return &http.Cookie{ + Expires: time.Now().UTC().Add(time.Duration(expireMins) * time.Minute), + Name: name, + Value: value, + Path: "/", + HttpOnly: true, + Secure: secureOnly, + MaxAge: expireMins, + } +} diff --git a/cookieStore_test.go b/cookieStore_test.go index c4f06e6..5f92388 100644 --- a/cookieStore_test.go +++ b/cookieStore_test.go @@ -16,13 +16,13 @@ var cookieKey = []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 func getCookieStore() *cookieStore { r, _ := http.NewRequest("GET", "www.google.com", nil) - return NewCookieStore(httptest.NewRecorder(), r, cookieKey, false).(*cookieStore) + return newCookieStore(httptest.NewRecorder(), r, cookieKey, false).(*cookieStore) } func TestNewCookieStore(t *testing.T) { r := &http.Request{} w := httptest.NewRecorder() - actual := NewCookieStore(w, r, cookieKey, false).(*cookieStore) + actual := newCookieStore(w, r, cookieKey, false).(*cookieStore) if actual.w != w || actual.r != r { t.Fatal("expected correct init", actual) } @@ -104,7 +104,7 @@ func substringBetween(source, from, to string) string { /****************************************************************************/ type MockCookieStore struct { - CookieStorer + cookieStorer cookies map[string]interface{} getErr error putErr error diff --git a/loginStore.go b/loginStore.go index 3a8d70d..6369e9f 100644 --- a/loginStore.go +++ b/loginStore.go @@ -4,24 +4,24 @@ import ( "fmt" ) -type LoginStorer interface { - Login(email, password string, rememberMe bool) (*UserLogin, error) +type loginStorer interface { + Login(email, password string, rememberMe bool) (*userLogin, error) - CreateLogin(email, fullName, password string, mailQuota, fileQuota int) (*UserLogin, error) + CreateLogin(email, fullName, password string, mailQuota, fileQuota int) (*userLogin, error) UpdateEmail() error UpdatePassword() error } type loginStore struct { - backend Backender - mailer Mailer + backend backender + mailer mailer } -func NewLoginStore(backend Backender, mailer Mailer) LoginStorer { +func newLoginStore(backend backender, mailer mailer) loginStorer { return &loginStore{backend, mailer} } -func (s *loginStore) Login(email, password string, rememberMe bool) (*UserLogin, error) { +func (s *loginStore) Login(email, password string, rememberMe bool) (*userLogin, error) { if !isValidEmail(email) { return nil, newAuthError("Please enter a valid email address.", nil) } @@ -43,7 +43,7 @@ func (s *loginStore) Login(email, password string, rememberMe bool) (*UserLogin, } /**************** TODO: send 0 for UID and GID numbers and empty quotas if mailQuota and fileQuota are 0 **********************/ -func (s *loginStore) CreateLogin(email, fullName, password string, mailQuota, fileQuota int) (*UserLogin, error) { +func (s *loginStore) CreateLogin(email, fullName, password string, mailQuota, fileQuota int) (*userLogin, error) { passwordHash, err := cryptoHash(password) if err != nil { return nil, newLoggedError("Unable to create login", err) diff --git a/loginStore_test.go b/loginStore_test.go index 8d4015e..9c66e9e 100644 --- a/loginStore_test.go +++ b/loginStore_test.go @@ -4,14 +4,14 @@ import ( "testing" ) -func getLoginStore(mailErr error, backend *MockBackend) LoginStorer { +func getLoginStore(mailErr error, backend *mockBackend) loginStorer { return &loginStore{backend, &TextMailer{Err: mailErr}} } func TestNewLoginStore(t *testing.T) { - b := &MockBackend{} + b := &mockBackend{} m := &TextMailer{} - actual := NewLoginStore(b, m).(*loginStore) + actual := newLoginStore(b, m).(*loginStore) if actual.backend != b { t.Fatal("expected correct init") } @@ -26,7 +26,7 @@ var loginTests = []struct { GetUserLoginReturn *LoginReturn ErrReturn error MethodsCalled []string - ExpectedResult *UserLoginRememberMe + ExpectedResult *rememberMeSession ExpectedErr string }{ { @@ -52,7 +52,7 @@ var loginTests = []struct { Scenario: "Incorrect password", Email: "email@example.com", Password: "wrongPassword", - GetUserLoginReturn: &LoginReturn{Login: &UserLogin{Email: "test@test.com", ProviderKey: "1234"}}, + GetUserLoginReturn: &LoginReturn{Login: &userLogin{Email: "test@test.com", ProviderKey: "1234"}}, MethodsCalled: []string{"GetUserLogin"}, ExpectedErr: "Invalid username or password", }, @@ -71,10 +71,10 @@ func TestAuthLogin(t *testing.T) { t.SkipNow() } for i, test := range loginTests { - backend := &MockBackend{GetUserLoginReturn: test.GetUserLoginReturn, ErrReturn: test.ErrReturn} + backend := &mockBackend{GetUserLoginReturn: test.GetUserLoginReturn, ErrReturn: test.ErrReturn} store := getLoginStore(nil, backend).(*loginStore) val, err := store.Login(test.Email, test.Password, test.RememberMe) - methods := store.backend.(*MockBackend).MethodsCalled + methods := store.backend.(*mockBackend).MethodsCalled if (err == nil && test.ExpectedErr != "" || err != nil && test.ExpectedErr != err.Error()) || !collectionEqual(test.MethodsCalled, methods) { t.Errorf("Scenario[%d] failed: %s\nexpected err:%v\tactual err:%v\nexpected val:%v\tactual val:%v\nexpected methods: %s\tactual methods: %s", i, test.Scenario, test.ExpectedErr, err, test.ExpectedResult, val, test.MethodsCalled, methods) @@ -83,30 +83,30 @@ func TestAuthLogin(t *testing.T) { } /****************************************************************************/ -type MockLoginStore struct { +type mockLoginStore struct { LoginReturn *LoginReturn } -func NewMockLoginStore() LoginStorer { - return &MockLoginStore{} +func newMockLoginStore() loginStorer { + return &mockLoginStore{} } -func (s *MockLoginStore) Login(email, password string, rememberMe bool) (*UserLogin, error) { +func (s *mockLoginStore) Login(email, password string, rememberMe bool) (*userLogin, error) { return s.LoginReturn.Login, s.LoginReturn.Err } -func (s *MockLoginStore) LoginBasic() (*UserLogin, error) { +func (s *mockLoginStore) LoginBasic() (*userLogin, error) { return s.LoginReturn.Login, s.LoginReturn.Err } -func (s *MockLoginStore) CreateLogin(email, fullName, password string, cloudQuota, fileQuota int) (*UserLogin, error) { +func (s *mockLoginStore) CreateLogin(email, fullName, password string, cloudQuota, fileQuota int) (*userLogin, error) { return s.LoginReturn.Login, s.LoginReturn.Err } -func (s *MockLoginStore) UpdateEmail() error { +func (s *mockLoginStore) UpdateEmail() error { return s.LoginReturn.Err } -func (s *MockLoginStore) UpdatePassword() error { +func (s *mockLoginStore) UpdatePassword() error { return s.LoginReturn.Err } diff --git a/mailer.go b/mailer.go index 6fef9cf..6c3f6e7 100644 --- a/mailer.go +++ b/mailer.go @@ -8,7 +8,7 @@ import ( "gopkg.in/gomail.v2" ) -type Mailer interface { +type mailer interface { SendWelcome(to string, data interface{}) error SendVerify(to string, data interface{}) error SendNewLogin(to string, data interface{}) error @@ -17,13 +17,13 @@ type Mailer interface { SendPasswordChanged(to string, data interface{}) error } -type Sender interface { +type sender interface { Send(to, subject, body string) error } type emailer struct { templateCache *template.Template - sender Sender + sender sender VerifyEmailTemplate string VerifyEmailSubject string diff --git a/mailer_test.go b/mailer_test.go index 2ec2955..0a3891d 100644 --- a/mailer_test.go +++ b/mailer_test.go @@ -87,7 +87,7 @@ func (s *NilSender) Send(to, subject, body string) error { type TextMailer struct { Err error - Mailer + mailer MessageTo string MessageData interface{} } diff --git a/nginxauth.go b/nginxauth.go index 6f7d89a..6834ecf 100644 --- a/nginxauth.go +++ b/nginxauth.go @@ -68,8 +68,8 @@ type authConf struct { } type nginxauth struct { - backend Backender - mailer Mailer + backend backender + mailer mailer cookieKey []byte conf authConf } @@ -91,12 +91,12 @@ func newNginxAuth() (*nginxauth, error) { log.Fatal(err) } - s := NewBackendRedisSession(config.RedisServer, config.RedisPort, config.RedisPassword, config.RedisMaxIdle, config.RedisMaxConnections, config.StoragePrefix) - l, err := NewBackendLDAPLogin(config.LdapServer, config.LdapPort, config.LdapBindDn, config.LdapPassword, config.LdapBaseDn, config.LdapUserFilter) + s := newBackendRedisSession(config.RedisServer, config.RedisPort, config.RedisPassword, config.RedisMaxIdle, config.RedisMaxConnections, config.StoragePrefix) + l, err := newBackendLDAPLogin(config.LdapServer, config.LdapPort, config.LdapBindDn, config.LdapPassword, config.LdapBaseDn, config.LdapUserFilter) if err != nil { return nil, err } - u := NewBackendMemory() + u := newBackendMemory() /*u, err := newBackendDbUser(config.DbServer, config.DbPort, config.DbUser, config.DbPassword, config.DbDatabase, config.GetUserLoginQuery, config.AddUserQuery, config.VerifyEmailQuery, config.UpdateUserQuery) if err != nil { return nil, err @@ -162,14 +162,78 @@ func fileLoggerHandler(h http.Handler) http.Handler { return handlers.CombinedLoggingHandler(logFile, h) } -func (s *nginxauth) method(name string, handler func(authStore AuthStorer, w http.ResponseWriter, r *http.Request)) http.HandlerFunc { +func (s *nginxauth) method(name string, handler func(authStore authStorer, w http.ResponseWriter, r *http.Request)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method != name { http.Error(w, "Unsupported method", http.StatusInternalServerError) return } secureOnly := strings.HasPrefix(r.Referer(), "https") // proxy to back-end so if referer is secure connection, we can use secureOnly cookies - authStore := NewAuthStore(s.backend, s.mailer, w, r, s.conf.StoragePrefix, s.cookieKey, secureOnly) + authStore := newAuthStore(s.backend, s.mailer, w, r, s.conf.StoragePrefix, s.cookieKey, secureOnly) handler(authStore, w, r) } } + +func auth(authStore authStorer, w http.ResponseWriter, r *http.Request) { + session, err := authStore.GetSession() + if err != nil { + http.Error(w, "Authentication required: "+err.Error(), http.StatusUnauthorized) + if a, ok := err.(*authError); ok { + fmt.Println(a.Trace()) + } + } else { + addUserHeader(session, w) + } +} + +func authBasic(authStore authStorer, w http.ResponseWriter, r *http.Request) { + session, err := authStore.GetBasicAuth() + if err != nil { + w.Header().Set("WWW-Authenticate", "Basic realm='Endfirst.com'") + http.Error(w, "Authentication required: "+err.Error(), http.StatusUnauthorized) + } else { + addUserHeader(session, w) + } +} + +func login(authStore authStorer, w http.ResponseWriter, r *http.Request) { + run(authStore.Login, w) +} + +func register(authStore authStorer, w http.ResponseWriter, r *http.Request) { + run(authStore.Register, w) +} + +func createProfile(authStore authStorer, w http.ResponseWriter, r *http.Request) { + run(authStore.CreateProfile, w) +} + +func updateEmail(authStore authStorer, w http.ResponseWriter, r *http.Request) { + run(authStore.UpdateEmail, w) +} + +func updatePassword(authStore authStorer, w http.ResponseWriter, r *http.Request) { + run(authStore.UpdatePassword, w) +} + +func verifyEmail(authStore authStorer, w http.ResponseWriter, r *http.Request) { + run(authStore.VerifyEmail, w) +} + +func run(method func() error, w http.ResponseWriter) { + err := method() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + if a, ok := err.(*authError); ok { + fmt.Println(a.Trace()) + } + } else { + w.Header().Add("Access-Control-Allow-Origin", "*") + w.Header().Add("Content-Type", "application/javascript") + fmt.Fprint(w, "{ \"result\": \"Success\" }") + } +} + +func addUserHeader(session *loginSession, w http.ResponseWriter) { + w.Header().Add("X-User", session.Email) +} diff --git a/nginxauth_test.go b/nginxauth_test.go index 8ff59b3..b70b204 100644 --- a/nginxauth_test.go +++ b/nginxauth_test.go @@ -1,6 +1,8 @@ package main import ( + "errors" + "net/http/httptest" "testing" ) @@ -31,3 +33,145 @@ func TestNewEmailer(t *testing.T) { } n.NewEmailer() } + +func TestAuth(t *testing.T) { + w := httptest.NewRecorder() + storer := &mockAuthStorer{ErrReturn: errors.New("failed")} + auth(storer, w, nil) + if w.Body.String() != "Authentication required: failed\n" || storer.LastRun != "GetSession" { + t.Error("expected auth to fail", w.Body.String(), storer.LastRun) + } + + w = httptest.NewRecorder() + storer = &mockAuthStorer{SessionReturn: &loginSession{Email: "test@test.com"}} + auth(storer, w, nil) + if w.Header().Get("X-User") != "test@test.com" || storer.LastRun != "GetSession" { + t.Error("expected User header to be set", w.Header().Get("X-User"), storer.LastRun) + } +} + +func TestAuthBasic(t *testing.T) { + w := httptest.NewRecorder() + storer := &mockAuthStorer{ErrReturn: errors.New("failed")} + authBasic(storer, w, nil) + if w.Body.String() != "Authentication required: failed\n" || storer.LastRun != "GetBasicAuth" { + t.Error("expected auth to fail", w.Body.String(), storer.LastRun) + } + + w = httptest.NewRecorder() + storer = &mockAuthStorer{SessionReturn: &loginSession{Email: "test@test.com"}} + authBasic(storer, w, nil) + if w.Header().Get("X-User") != "test@test.com" || storer.LastRun != "GetBasicAuth" { + t.Error("expected User header to be set", w.Header().Get("X-User"), storer.LastRun) + } +} + +func TestLogin(t *testing.T) { + w := httptest.NewRecorder() + storer := &mockAuthStorer{ErrReturn: errors.New("failed")} + login(storer, w, nil) + if w.Body.String() != "failed\n" || storer.LastRun != "Login" { + t.Error("expected to fail", w.Body.String(), storer.LastRun) + } + + w = httptest.NewRecorder() + storer = &mockAuthStorer{SessionReturn: &loginSession{}} + login(storer, w, nil) + if w.Body.String() != `{ "result": "Success" }` || storer.LastRun != "Login" { + t.Error("expected success", w.Body.String(), storer.LastRun) + } +} + +func TestRegister(t *testing.T) { + w := httptest.NewRecorder() + storer := &mockAuthStorer{ErrReturn: errors.New("failed")} + register(storer, w, nil) + if w.Body.String() != "failed\n" || storer.LastRun != "Register" { + t.Error("expected to fail", w.Body.String(), storer.LastRun) + } +} + +func TestCreateProfile(t *testing.T) { + w := httptest.NewRecorder() + storer := &mockAuthStorer{ErrReturn: errors.New("failed")} + createProfile(storer, w, nil) + if w.Body.String() != "failed\n" || storer.LastRun != "CreateProfile" { + t.Error("expected to fail", w.Body.String(), storer.LastRun) + } +} + +func TestUpdateEmail(t *testing.T) { + w := httptest.NewRecorder() + storer := &mockAuthStorer{ErrReturn: errors.New("failed")} + updateEmail(storer, w, nil) + if w.Body.String() != "failed\n" || storer.LastRun != "UpdateEmail" { + t.Error("expected to fail", w.Body.String(), storer.LastRun) + } +} + +func TestUpdatePassword(t *testing.T) { + w := httptest.NewRecorder() + storer := &mockAuthStorer{ErrReturn: errors.New("failed")} + updatePassword(storer, w, nil) + if w.Body.String() != "failed\n" || storer.LastRun != "UpdatePassword" { + t.Error("expected to fail", w.Body.String(), storer.LastRun) + } +} + +func TestVerifyEmail(t *testing.T) { + w := httptest.NewRecorder() + storer := &mockAuthStorer{ErrReturn: errors.New("failed")} + verifyEmail(storer, w, nil) + if w.Body.String() != "failed\n" || storer.LastRun != "VerifyEmail" { + t.Error("expected to fail", w.Body.String(), storer.LastRun) + } +} + +func TestAddUserHeader(t *testing.T) { + w := httptest.NewRecorder() + addUserHeader(&loginSession{Email: "test@test.com"}, w) + if w.Header().Get("X-User") != "test@test.com" { + t.Error("expected halfauth header", w.Header()) + } +} + +/*******************************************************/ +type mockAuthStorer struct { + SessionReturn *loginSession + ErrReturn error + LastRun string +} + +func (s *mockAuthStorer) GetSession() (*loginSession, error) { + s.LastRun = "GetSession" + return s.SessionReturn, s.ErrReturn +} + +func (s *mockAuthStorer) GetBasicAuth() (*loginSession, error) { + s.LastRun = "GetBasicAuth" + return s.SessionReturn, s.ErrReturn +} +func (s *mockAuthStorer) Login() error { + s.LastRun = "Login" + return s.ErrReturn +} +func (s *mockAuthStorer) Register() error { + s.LastRun = "Register" + return s.ErrReturn +} +func (s *mockAuthStorer) CreateProfile() error { + s.LastRun = "CreateProfile" + return s.ErrReturn +} +func (s *mockAuthStorer) VerifyEmail() error { + s.LastRun = "VerifyEmail" + return s.ErrReturn +} +func (s *mockAuthStorer) UpdateEmail() error { + s.LastRun = "UpdateEmail" + return s.ErrReturn +} +func (s *mockAuthStorer) UpdatePassword() error { + s.LastRun = "UpdatePassword" + return s.ErrReturn +} diff --git a/sessionStore.go b/sessionStore.go index 48b24c2..9d8f323 100644 --- a/sessionStore.go +++ b/sessionStore.go @@ -5,9 +5,9 @@ import ( "time" ) -type SessionStorer interface { - GetSession() (*UserLoginSession, error) - CreateSession(email string, rememberMe bool) (*UserLoginSession, error) +type sessionStorer interface { + GetSession() (*loginSession, error) + CreateSession(email string, rememberMe bool) (*loginSession, error) } type sessionCookie struct { @@ -24,16 +24,16 @@ type rememberMeCookie struct { } type sessionStore struct { - b SessionBackender - cookieStore CookieStorer + b sessionBackender + cookieStore cookieStorer r *http.Request } -func NewSessionStore(b SessionBackender, w http.ResponseWriter, r *http.Request, customPrefix string, cookieKey []byte, secureOnlyCookie bool) SessionStorer { +func newSessionStore(b sessionBackender, w http.ResponseWriter, r *http.Request, customPrefix string, cookieKey []byte, secureOnlyCookie bool) sessionStorer { emailCookieName = customPrefix + "Email" sessionCookieName = customPrefix + "Session" rememberMeCookieName = customPrefix + "RememberMe" - return &sessionStore{b, NewCookieStore(w, r, cookieKey, secureOnlyCookie), r} + return &sessionStore{b, newCookieStore(w, r, cookieKey, secureOnlyCookie), r} } var emailCookieName = "Email" @@ -47,7 +47,7 @@ const sessionExpireDuration time.Duration = time.Hour const rememberMeRenewDuration time.Duration = time.Hour const rememberMeExpireDuration time.Duration = time.Hour * 24 * 30 // 30 days -func (s *sessionStore) GetSession() (*UserLoginSession, error) { +func (s *sessionStore) GetSession() (*loginSession, error) { cookie, err := s.getSessionCookie() if err != nil || cookie.SessionID == "" { // impossible to get the session if there is no cookie return nil, newAuthError("Session cookie not found", err) @@ -71,7 +71,7 @@ func (s *sessionStore) GetSession() (*UserLoginSession, error) { return session, nil } -func (s *sessionStore) getRememberMe() (*UserLoginRememberMe, error) { +func (s *sessionStore) getRememberMe() (*rememberMeSession, error) { cookie, err := s.getRememberMeCookie() if err != nil || cookie.Selector == "" { // impossible to get the remember Me if there is no cookie return nil, newAuthError("RememberMe cookie not found", err) @@ -104,7 +104,7 @@ func (s *sessionStore) getRememberMe() (*UserLoginRememberMe, error) { return rememberMe, nil } -func (s *sessionStore) renewSession(sessionID, sessionHash string, renewTimeUTC, expireTimeUTC *time.Time) (*UserLoginSession, error) { +func (s *sessionStore) renewSession(sessionID, sessionHash string, renewTimeUTC, expireTimeUTC *time.Time) (*loginSession, error) { if renewTimeUTC.Before(time.Now().UTC()) && expireTimeUTC.After(time.Now().UTC()) { session, err := s.b.RenewSession(sessionHash, time.Now().UTC().Add(sessionRenewDuration)) if err != nil { @@ -136,7 +136,7 @@ func (s *sessionStore) renewSession(sessionID, sessionHash string, renewTimeUTC, return session, nil } -func (s *sessionStore) CreateSession(email string, rememberMe bool) (*UserLoginSession, error) { +func (s *sessionStore) CreateSession(email string, rememberMe bool) (*loginSession, error) { var err error var selector, token, tokenHash string if rememberMe { diff --git a/sessionStore_test.go b/sessionStore_test.go index d5210f8..9fa73e0 100644 --- a/sessionStore_test.go +++ b/sessionStore_test.go @@ -6,7 +6,7 @@ import ( "time" ) -func getSessionStore(emailCookieToReturn *emailCookie, sessionCookieToReturn *sessionCookie, rememberMeCookieToReturn *rememberMeCookie, hasCookieGetError, hasCookiePutError bool, backend *MockBackend) *sessionStore { +func getSessionStore(emailCookieToReturn *emailCookie, sessionCookieToReturn *sessionCookie, rememberMeCookieToReturn *rememberMeCookie, hasCookieGetError, hasCookiePutError bool, backend *mockBackend) *sessionStore { r := &http.Request{} cookieStore := NewMockCookieStore(map[string]interface{}{emailCookieName: emailCookieToReturn, sessionCookieName: sessionCookieToReturn, rememberMeCookieName: rememberMeCookieToReturn}, hasCookieGetError, hasCookiePutError) return &sessionStore{backend, cookieStore, r} @@ -21,7 +21,7 @@ var getSessionTests = []struct { RenewSessionReturn *SessionReturn GetRememberMeReturn *RememberMeReturn MethodsCalled []string - ExpectedResult *UserLoginRememberMe + ExpectedResult *rememberMeSession ExpectedErr string }{ { @@ -43,7 +43,7 @@ var getSessionTests = []struct { { Scenario: "Get Session Error", SessionCookie: sessionCookieGood(futureTime, futureTime), - GetSessionReturn: &SessionReturn{&UserLoginSession{}, errSessionNotFound}, + GetSessionReturn: &SessionReturn{&loginSession{}, errSessionNotFound}, MethodsCalled: []string{"GetSession"}, ExpectedErr: "Failed to verify session", }, @@ -57,10 +57,10 @@ var getSessionTests = []struct { func TestGetSession(t *testing.T) { for i, test := range getSessionTests { - backend := &MockBackend{GetSessionReturn: test.GetSessionReturn, RenewSessionReturn: test.RenewSessionReturn} + backend := &mockBackend{GetSessionReturn: test.GetSessionReturn, RenewSessionReturn: test.RenewSessionReturn} store := getSessionStore(nil, test.SessionCookie, nil, test.HasCookieGetError, test.HasCookiePutError, backend) val, err := store.GetSession() - methods := store.b.(*MockBackend).MethodsCalled + methods := store.b.(*mockBackend).MethodsCalled if (err == nil && test.ExpectedErr != "" || err != nil && test.ExpectedErr != err.Error()) || !collectionEqual(test.MethodsCalled, methods) { t.Errorf("Scenario[%d] failed: %s\nexpected err:%v\tactual err:%v\nexpected val:%v\tactual val:%v\nexpected methods: %s\tactual methods: %s", i, test.Scenario, test.ExpectedErr, err, test.ExpectedResult, val, test.MethodsCalled, methods) @@ -78,7 +78,7 @@ var renewSessionTests = []struct { RenewSessionReturn *SessionReturn GetRememberMeReturn *RememberMeReturn MethodsCalled []string - ExpectedResult *UserLoginRememberMe + ExpectedResult *rememberMeSession ExpectedErr string }{ { @@ -140,10 +140,10 @@ var renewSessionTests = []struct { // NOTE - can't currently get coverage for the error at approx line 147 for the saveSessionCookie error func TestRenewSession(t *testing.T) { for i, test := range renewSessionTests { - backend := &MockBackend{RenewSessionReturn: test.RenewSessionReturn, GetRememberMeReturn: test.GetRememberMeReturn} + backend := &mockBackend{RenewSessionReturn: test.RenewSessionReturn, GetRememberMeReturn: test.GetRememberMeReturn} store := getSessionStore(nil, nil, test.RememberCookie, test.HasCookieGetError, test.HasCookiePutError, backend) val, err := store.renewSession("sessionId", "sessionHash", &test.RenewTimeUTC, &test.ExpireTimeUTC) - methods := store.b.(*MockBackend).MethodsCalled + methods := store.b.(*mockBackend).MethodsCalled if (err == nil && test.ExpectedErr != "" || err != nil && test.ExpectedErr != err.Error()) || !collectionEqual(test.MethodsCalled, methods) { t.Errorf("Scenario[%d] failed: %s\nexpected err:%v\tactual err:%v\nexpected val:%v\tactual val:%v\nexpected methods: %s\tactual methods: %s", i, test.Scenario, test.ExpectedErr, err, test.ExpectedResult, val, test.MethodsCalled, methods) @@ -159,7 +159,7 @@ var rememberMeTests = []struct { GetRememberMeReturn *RememberMeReturn RenewRememberMeReturn *RememberMeReturn MethodsCalled []string - ExpectedResult *UserLoginRememberMe + ExpectedResult *rememberMeSession ExpectedErr string }{ { @@ -176,7 +176,7 @@ var rememberMeTests = []struct { { Scenario: "Get RememberMe Error", RememberCookie: rememberCookie(futureTime, futureTime), - GetRememberMeReturn: &RememberMeReturn{&UserLoginRememberMe{}, errRememberMeNotFound}, + GetRememberMeReturn: &RememberMeReturn{&rememberMeSession{}, errRememberMeNotFound}, MethodsCalled: []string{"GetRememberMe"}, ExpectedErr: "Unable to find matching RememberMe in DB", }, @@ -191,7 +191,7 @@ var rememberMeTests = []struct { Scenario: "Renew RememberMe Error", RememberCookie: rememberCookie(pastTime, futureTime), GetRememberMeReturn: rememberMe(pastTime, futureTime), - RenewRememberMeReturn: &RememberMeReturn{&UserLoginRememberMe{}, errRememberMeNotFound}, + RenewRememberMeReturn: &RememberMeReturn{&rememberMeSession{}, errRememberMeNotFound}, MethodsCalled: []string{"GetRememberMe", "RenewRememberMe"}, ExpectedErr: "Unable to renew RememberMe", }, @@ -206,10 +206,10 @@ var rememberMeTests = []struct { func TestRememberMe(t *testing.T) { for i, test := range rememberMeTests { - backend := &MockBackend{GetRememberMeReturn: test.GetRememberMeReturn, RenewRememberMeReturn: test.RenewRememberMeReturn} + backend := &mockBackend{GetRememberMeReturn: test.GetRememberMeReturn, RenewRememberMeReturn: test.RenewRememberMeReturn} store := getSessionStore(nil, nil, test.RememberCookie, test.HasCookieGetError, test.HasCookiePutError, backend) val, err := store.getRememberMe() - methods := store.b.(*MockBackend).MethodsCalled + methods := store.b.(*mockBackend).MethodsCalled if (err == nil && test.ExpectedErr != "" || err != nil && test.ExpectedErr != err.Error()) || !collectionEqual(test.MethodsCalled, methods) { t.Errorf("Scenario[%d] failed: %s\nexpected err:%v\tactual err:%v\nexpected val:%v\tactual val:%v\nexpected methods: %s\tactual methods: %s", i, test.Scenario, test.ExpectedErr, err, test.ExpectedResult, val, test.MethodsCalled, methods) @@ -226,7 +226,7 @@ var createSessionTests = []struct { RememberMeCookie *rememberMeCookie CreateSessionReturn *SessionRememberReturn MethodsCalled []string - ExpectedResult *UserLoginRememberMe + ExpectedResult *rememberMeSession ExpectedErr string }{ { @@ -276,10 +276,10 @@ var createSessionTests = []struct { func TestCreateSession(t *testing.T) { for i, test := range createSessionTests { - backend := &MockBackend{CreateSessionReturn: test.CreateSessionReturn} + backend := &mockBackend{CreateSessionReturn: test.CreateSessionReturn} store := getSessionStore(nil, test.SessionCookie, test.RememberMeCookie, test.HasCookieGetError, test.HasCookiePutError, backend) val, err := store.CreateSession("test@test.com", test.RememberMe) - methods := store.b.(*MockBackend).MethodsCalled + methods := store.b.(*mockBackend).MethodsCalled if (err == nil && test.ExpectedErr != "" || err != nil && test.ExpectedErr != err.Error()) || !collectionEqual(test.MethodsCalled, methods) { t.Errorf("Scenario[%d] failed: %s\nexpected err:%v\tactual err:%v\nexpected val:%v\tactual val:%v\nexpected methods: %s\tactual methods: %s", i, test.Scenario, test.ExpectedErr, err, test.ExpectedResult, val, test.MethodsCalled, methods) @@ -288,14 +288,14 @@ func TestCreateSession(t *testing.T) { } /*************************************************************************************/ -type MockSessionStore struct { +type mockSessionStore struct { SessionReturn *SessionReturn } -func (m *MockSessionStore) GetSession() (*UserLoginSession, error) { +func (m *mockSessionStore) GetSession() (*loginSession, error) { return m.SessionReturn.Session, m.SessionReturn.Err } -func (m *MockSessionStore) CreateSession(email string, rememberMe bool) (*UserLoginSession, error) { +func (m *mockSessionStore) CreateSession(email string, rememberMe bool) (*loginSession, error) { return m.SessionReturn.Session, m.SessionReturn.Err }