auth
149:8267e1c8bcd1 Browse Files
Test our Postgres profileStore implementation. Update all our test cases to use time.Now().Round(time.Millisecond), because Go uses nanosecond precision on time values, but Postgres silently truncates that to millisecond precision. This caused our tests to report false failures that were just silent precision loss, not actual failures. Set up our authd server to use the Postgres store for profiles and automatically create a test scope when starting up. Log errors when creating Clients through the API, instead of just swallowing them and sending back cryptic act of god errors. Add a NewPostgres helper that returns a postgres profileStore from a connection string (passed through pq transparently). Add an Empty() bool helper to ProfileChange and BulkProfileChange types, so we can determine if there are any changes we need to act on easily. Log errors when creating Pofiles through the API, instead of just swalloing them and sending back cryptic act of god errors. Remove the ` quotes around field and table names, which are not supported in Postgres. This required adding a few functions/methods to pan. Detect situations where a profile was expected and not found, and return ErrProfileNotFound. Detect pq errors thrown when the profiles_pkey constraint is violated, and transform them to the ErrProfileAlreadyExists error. Detect empty ProfileChange and BulkProfileChange variables and abort the updateProfile and updateProfiles methods early, before invalid SQL is generated. Detect pq errors thrown when the logins_pkey constraint is violated, and transform them to the ErrLoginAlreadyExists error. Detect when removing a Login and no rows were affected, and return an ErrLoginNotFound. Create an sql dir with a postgres_init script that will initialize the schema of the tables expected in the database.
authcode_test.go authd/server.go client.go client_test.go oauth2_test.go postgres.go profile.go profile_postgres.go profile_test.go session_test.go sql/postgres_init.sql token_test.go
1.1 --- a/authcode_test.go Sat Mar 21 01:23:33 2015 -0400 1.2 +++ b/authcode_test.go Sat Mar 21 14:53:15 2015 -0400 1.3 @@ -55,7 +55,7 @@ 1.4 t.Parallel() 1.5 authCode := AuthorizationCode{ 1.6 Code: "code", 1.7 - Created: time.Now(), 1.8 + Created: time.Now().Round(time.Millisecond), 1.9 ExpiresIn: 180, 1.10 ClientID: uuid.NewID(), 1.11 Scopes: []string{"scope"}, 1.12 @@ -135,7 +135,7 @@ 1.13 ID: uuid.NewID(), 1.14 ClientID: client.ID, 1.15 URI: "https://test.secondbit.org/redirect", 1.16 - Added: time.Now(), 1.17 + Added: time.Now().Round(time.Millisecond), 1.18 } 1.19 err := testContext.SaveClient(client) 1.20 if err != nil { 1.21 @@ -147,7 +147,7 @@ 1.22 } 1.23 code := AuthorizationCode{ 1.24 Code: "myauthcode", 1.25 - Created: time.Now(), 1.26 + Created: time.Now().Round(time.Millisecond), 1.27 ExpiresIn: 180, 1.28 ClientID: uuid.NewID(), 1.29 Scopes: []string{"scope"}, 1.30 @@ -329,7 +329,7 @@ 1.31 } 1.32 code := AuthorizationCode{ 1.33 Code: "myauthcode", 1.34 - Created: time.Now(), 1.35 + Created: time.Now().Round(time.Millisecond), 1.36 ExpiresIn: 180, 1.37 ClientID: uuid.NewID(), 1.38 Scopes: []string{"scope"},
2.1 --- a/authd/server.go Sat Mar 21 01:23:33 2015 -0400 2.2 +++ b/authd/server.go Sat Mar 21 14:53:15 2015 -0400 2.3 @@ -10,17 +10,25 @@ 2.4 ) 2.5 2.6 func main() { 2.7 + p, err := auth.NewPostgres("dbname=testdb sslmode=disable") 2.8 + if err != nil { 2.9 + panic(err) 2.10 + } 2.11 store := auth.NewMemstore() 2.12 + if err != nil { 2.13 + panic(err) 2.14 + } 2.15 config := auth.Config{ 2.16 ClientStore: store, 2.17 AuthCodeStore: store, 2.18 - ProfileStore: store, 2.19 + ProfileStore: &p, 2.20 TokenStore: store, 2.21 SessionStore: store, 2.22 + ScopeStore: store, 2.23 Template: template.Must(template.New("base").ParseGlob("./templates/*.gotmpl")), 2.24 LoginURI: "/login", 2.25 } 2.26 - err := config.Init() 2.27 + err = config.Init() 2.28 if err != nil { 2.29 log.Fatal(err) 2.30 } 2.31 @@ -28,6 +36,9 @@ 2.32 if err != nil { 2.33 panic(err) 2.34 } 2.35 + err = context.CreateScopes([]auth.Scope{ 2.36 + {ID: "testscope", Name: "Test Scope"}, 2.37 + }) 2.38 2.39 router := mux.NewRouter() 2.40 auth.RegisterOAuth2(router, context)
3.1 --- a/client.go Sat Mar 21 01:23:33 2015 -0400 3.2 +++ b/client.go Sat Mar 21 14:53:15 2015 -0400 3.3 @@ -430,6 +430,7 @@ 3.4 errors = append(errors, requestError{Slug: requestErrAccessDenied}) 3.5 encode(w, r, http.StatusUnauthorized, response{Errors: errors}) 3.6 } else { 3.7 + log.Printf("Error authenticating: %#+v\n", err) 3.8 errors = append(errors, requestError{Slug: requestErrActOfGod}) 3.9 encode(w, r, http.StatusInternalServerError, response{Errors: errors}) 3.10 } 3.11 @@ -470,6 +471,7 @@ 3.12 secret := make([]byte, 32) 3.13 _, err = rand.Read(secret) 3.14 if err != nil { 3.15 + log.Printf("Error generating secret: %#+v\n", err) 3.16 encode(w, r, http.StatusInternalServerError, actOfGodResponse) 3.17 return 3.18 } 3.19 @@ -482,6 +484,7 @@ 3.20 encode(w, r, http.StatusBadRequest, response{Errors: errors}) 3.21 return 3.22 } 3.23 + log.Printf("Error saving client: %#+v\n", err) 3.24 encode(w, r, http.StatusInternalServerError, actOfGodResponse) 3.25 return 3.26 } 3.27 @@ -506,6 +509,7 @@ 3.28 } 3.29 err = c.AddEndpoints(client.ID, endpoints) 3.30 if err != nil { 3.31 + log.Printf("Error adding endpoints: %#+v\n", err) 3.32 errors = append(errors, requestError{Slug: requestErrActOfGod}) 3.33 encode(w, r, http.StatusInternalServerError, response{Errors: errors, Clients: []Client{client}}) 3.34 return
4.1 --- a/client_test.go Sat Mar 21 01:23:33 2015 -0400 4.2 +++ b/client_test.go Sat Mar 21 14:53:15 2015 -0400 4.3 @@ -142,13 +142,13 @@ 4.4 endpoint1 := Endpoint{ 4.5 ID: uuid.NewID(), 4.6 ClientID: client.ID, 4.7 - Added: time.Now(), 4.8 + Added: time.Now().Round(time.Millisecond), 4.9 URI: "https://www.example.com/", 4.10 } 4.11 endpoint2 := Endpoint{ 4.12 ID: uuid.NewID(), 4.13 ClientID: client.ID, 4.14 - Added: time.Now(), 4.15 + Added: time.Now().Round(time.Millisecond), 4.16 URI: "https://www.example.com/my/full/path", 4.17 } 4.18 for _, store := range clientStores { 4.19 @@ -311,13 +311,13 @@ 4.20 endpoint1 := Endpoint{ 4.21 ID: uuid.NewID(), 4.22 ClientID: client.ID, 4.23 - Added: time.Now(), 4.24 + Added: time.Now().Round(time.Millisecond), 4.25 URI: "https://www.example.com/first", 4.26 } 4.27 endpoint2 := Endpoint{ 4.28 ID: uuid.NewID(), 4.29 ClientID: client.ID, 4.30 - Added: time.Now(), 4.31 + Added: time.Now().Round(time.Millisecond), 4.32 URI: "https://www.example.com/my/full/path", 4.33 } 4.34 candidates := map[string]bool{ 4.35 @@ -372,13 +372,13 @@ 4.36 endpoint1 := Endpoint{ 4.37 ID: uuid.NewID(), 4.38 ClientID: client.ID, 4.39 - Added: time.Now(), 4.40 + Added: time.Now().Round(time.Millisecond), 4.41 URI: "https://www.example.com/first", 4.42 } 4.43 endpoint2 := Endpoint{ 4.44 ID: uuid.NewID(), 4.45 ClientID: client.ID, 4.46 - Added: time.Now(), 4.47 + Added: time.Now().Round(time.Millisecond), 4.48 URI: "https://www.example.com/my/full/path", 4.49 } 4.50 candidates := map[string]bool{ 4.51 @@ -717,14 +717,14 @@ 4.52 LockedUntil: time.Time{}, 4.53 PassphraseReset: "", 4.54 PassphraseResetCreated: time.Time{}, 4.55 - Created: time.Now(), 4.56 + Created: time.Now().Round(time.Millisecond), 4.57 LastSeen: time.Time{}, 4.58 } 4.59 login := Login{ 4.60 Type: "email", 4.61 Value: "test@example.com", 4.62 ProfileID: profile.ID, 4.63 - Created: time.Now(), 4.64 + Created: time.Now().Round(time.Millisecond), 4.65 LastUsed: time.Time{}, 4.66 } 4.67 w = httptest.NewRecorder() 4.68 @@ -832,14 +832,14 @@ 4.69 LockedUntil: time.Time{}, 4.70 PassphraseReset: "", 4.71 PassphraseResetCreated: time.Time{}, 4.72 - Created: time.Now(), 4.73 + Created: time.Now().Round(time.Millisecond), 4.74 LastSeen: time.Time{}, 4.75 } 4.76 login := Login{ 4.77 Type: "email", 4.78 Value: "test@example.com", 4.79 ProfileID: profile.ID, 4.80 - Created: time.Now(), 4.81 + Created: time.Now().Round(time.Millisecond), 4.82 LastUsed: time.Time{}, 4.83 } 4.84 err = c.SaveProfile(profile) 4.85 @@ -968,14 +968,14 @@ 4.86 LockedUntil: time.Time{}, 4.87 PassphraseReset: "", 4.88 PassphraseResetCreated: time.Time{}, 4.89 - Created: time.Now(), 4.90 + Created: time.Now().Round(time.Millisecond), 4.91 LastSeen: time.Time{}, 4.92 } 4.93 login := Login{ 4.94 Type: "email", 4.95 Value: "test@example.com", 4.96 ProfileID: profile.ID, 4.97 - Created: time.Now(), 4.98 + Created: time.Now().Round(time.Millisecond), 4.99 LastUsed: time.Time{}, 4.100 } 4.101 err = c.SaveProfile(profile) 4.102 @@ -997,14 +997,14 @@ 4.103 LockedUntil: time.Time{}, 4.104 PassphraseReset: "", 4.105 PassphraseResetCreated: time.Time{}, 4.106 - Created: time.Now(), 4.107 + Created: time.Now().Round(time.Millisecond), 4.108 LastSeen: time.Time{}, 4.109 } 4.110 login2 := Login{ 4.111 Type: "email", 4.112 Value: "test2@example.com", 4.113 ProfileID: profile2.ID, 4.114 - Created: time.Now(), 4.115 + Created: time.Now().Round(time.Millisecond), 4.116 LastUsed: time.Time{}, 4.117 } 4.118 err = c.SaveProfile(profile2)
5.1 --- a/oauth2_test.go Sat Mar 21 01:23:33 2015 -0400 5.2 +++ b/oauth2_test.go Sat Mar 21 14:53:15 2015 -0400 5.3 @@ -50,7 +50,7 @@ 5.4 ID: uuid.NewID(), 5.5 ClientID: client.ID, 5.6 URI: "https://test.secondbit.org/redirect", 5.7 - Added: time.Now(), 5.8 + Added: time.Now().Round(time.Millisecond), 5.9 } 5.10 err := testContext.SaveClient(client) 5.11 if err != nil { 5.12 @@ -72,7 +72,7 @@ 5.13 Active: true, 5.14 ProfileID: profile.ID, 5.15 CSRFToken: "nosurf", 5.16 - Expires: time.Now().Add(time.Hour), 5.17 + Expires: time.Now().Round(time.Millisecond).Add(time.Hour), 5.18 } 5.19 err = testContext.CreateSession(session) 5.20 if err != nil { 5.21 @@ -187,7 +187,7 @@ 5.22 ID: "testsession", 5.23 Active: true, 5.24 CSRFToken: "nosurf", 5.25 - Expires: time.Now().Add(time.Hour), 5.26 + Expires: time.Now().Round(time.Millisecond).Add(time.Hour), 5.27 } 5.28 err = testContext.CreateSession(session) 5.29 if err != nil { 5.30 @@ -262,7 +262,7 @@ 5.31 ID: "testsession", 5.32 Active: true, 5.33 CSRFToken: "nosurf", 5.34 - Expires: time.Now().Add(time.Hour), 5.35 + Expires: time.Now().Round(time.Millisecond).Add(time.Hour), 5.36 } 5.37 err = testContext.CreateSession(session) 5.38 if err != nil { 5.39 @@ -293,7 +293,7 @@ 5.40 ID: uuid.NewID(), 5.41 ClientID: client.ID, 5.42 URI: "https://test.secondbit.org/redirect", 5.43 - Added: time.Now(), 5.44 + Added: time.Now().Round(time.Millisecond), 5.45 } 5.46 err = testContext.AddEndpoints(client.ID, []Endpoint{endpoint}) 5.47 if err != nil { 5.48 @@ -313,7 +313,7 @@ 5.49 ID: uuid.NewID(), 5.50 ClientID: client.ID, 5.51 URI: "https://test.secondbit.org/redirect", 5.52 - Added: time.Now(), 5.53 + Added: time.Now().Round(time.Millisecond), 5.54 } 5.55 err = testContext.AddEndpoints(client.ID, []Endpoint{endpoint2}) 5.56 if err != nil { 5.57 @@ -366,7 +366,7 @@ 5.58 ID: uuid.NewID(), 5.59 ClientID: client.ID, 5.60 URI: "https://test.secondbit.org/redirect", 5.61 - Added: time.Now(), 5.62 + Added: time.Now().Round(time.Millisecond), 5.63 } 5.64 err := testContext.SaveClient(client) 5.65 if err != nil { 5.66 @@ -380,7 +380,7 @@ 5.67 ID: "testsession", 5.68 Active: true, 5.69 CSRFToken: "nosurf", 5.70 - Expires: time.Now().Add(time.Hour), 5.71 + Expires: time.Now().Round(time.Millisecond).Add(time.Hour), 5.72 } 5.73 err = testContext.CreateSession(session) 5.74 if err != nil { 5.75 @@ -472,7 +472,7 @@ 5.76 ID: uuid.NewID(), 5.77 ClientID: client.ID, 5.78 URI: "https://test.secondbit.org/redirect", 5.79 - Added: time.Now(), 5.80 + Added: time.Now().Round(time.Millisecond), 5.81 } 5.82 err := testContext.SaveClient(client) 5.83 if err != nil { 5.84 @@ -486,7 +486,7 @@ 5.85 ID: "testsession", 5.86 Active: true, 5.87 CSRFToken: "nosurf", 5.88 - Expires: time.Now().Add(time.Hour), 5.89 + Expires: time.Now().Round(time.Millisecond).Add(time.Hour), 5.90 } 5.91 err = testContext.CreateSession(session) 5.92 if err != nil { 5.93 @@ -600,7 +600,7 @@ 5.94 ID: "testsession", 5.95 Active: true, 5.96 CSRFToken: "nosurf", 5.97 - Expires: time.Now().Add(time.Hour), 5.98 + Expires: time.Now().Round(time.Millisecond).Add(time.Hour), 5.99 } 5.100 err = testContext.CreateSession(session) 5.101 if err != nil { 5.102 @@ -719,14 +719,14 @@ 5.103 LockedUntil: time.Time{}, 5.104 PassphraseReset: "", 5.105 PassphraseResetCreated: time.Time{}, 5.106 - Created: time.Now(), 5.107 + Created: time.Now().Round(time.Millisecond), 5.108 LastSeen: time.Time{}, 5.109 } 5.110 login := Login{ 5.111 Type: "email", 5.112 Value: "test@example.com", 5.113 ProfileID: profile.ID, 5.114 - Created: time.Now(), 5.115 + Created: time.Now().Round(time.Millisecond), 5.116 LastUsed: time.Time{}, 5.117 } 5.118 err := context.SaveProfile(profile) 5.119 @@ -788,7 +788,7 @@ 5.120 } 5.121 authCode := AuthorizationCode{ 5.122 Code: "testcode", 5.123 - Created: time.Now(), 5.124 + Created: time.Now().Round(time.Millisecond), 5.125 ExpiresIn: 600, 5.126 ClientID: client.ID, 5.127 Scopes: []string{"testscope"},
6.1 --- a/postgres.go Sat Mar 21 01:23:33 2015 -0400 6.2 +++ b/postgres.go Sat Mar 21 14:53:15 2015 -0400 6.3 @@ -2,9 +2,15 @@ 6.4 6.5 import ( 6.6 "database/sql" 6.7 +) 6.8 6.9 - _ "github.com/lib/pq" 6.10 -) 6.11 +func NewPostgres(conn string) (postgres, error) { 6.12 + db, err := sql.Open("postgres", conn) 6.13 + if err != nil { 6.14 + return postgres{}, err 6.15 + } 6.16 + return postgres{db: db}, nil 6.17 +} 6.18 6.19 type postgres struct { 6.20 db *sql.DB
7.1 --- a/profile.go Sat Mar 21 01:23:33 2015 -0400 7.2 +++ b/profile.go Sat Mar 21 14:53:15 2015 -0400 7.3 @@ -3,6 +3,7 @@ 7.4 import ( 7.5 "encoding/json" 7.6 "errors" 7.7 + "log" 7.8 "net/http" 7.9 "regexp" 7.10 "strings" 7.11 @@ -146,12 +147,16 @@ 7.12 Deleted *bool 7.13 } 7.14 7.15 +func (c ProfileChange) Empty() bool { 7.16 + return (c.Name == nil && c.Passphrase == nil && c.Iterations == nil && c.Salt == nil && c.PassphraseScheme == nil && c.Compromised == nil && c.LockedUntil == nil && c.PassphraseReset == nil && c.PassphraseResetCreated == nil && c.LastSeen == nil && c.Deleted == nil) 7.17 +} 7.18 + 7.19 // Validate checks the ProfileChange it is called on 7.20 // and asserts its internal validity, or lack thereof. 7.21 // A descriptive error will be returned in the case of 7.22 // an invalid change. 7.23 func (c ProfileChange) Validate() error { 7.24 - if c.Name == nil && c.Passphrase == nil && c.Iterations == nil && c.Salt == nil && c.PassphraseScheme == nil && c.Compromised == nil && c.LockedUntil == nil && c.PassphraseReset == nil && c.PassphraseResetCreated == nil && c.LastSeen == nil && c.Deleted == nil { 7.25 + if c.Empty() { 7.26 return ErrEmptyChange 7.27 } 7.28 if c.PassphraseScheme != nil && c.Passphrase == nil { 7.29 @@ -179,12 +184,16 @@ 7.30 Compromised *bool 7.31 } 7.32 7.33 +func (b BulkProfileChange) Empty() bool { 7.34 + return b.Compromised == nil 7.35 +} 7.36 + 7.37 // Validate checks the BulkProfileChange it is called on 7.38 // and asserts its internal validity, or lack thereof. 7.39 // A descriptive error will be returned in the case of an 7.40 // invalid change. 7.41 func (b BulkProfileChange) Validate() error { 7.42 - if b.Compromised == nil { 7.43 + if b.Empty() { 7.44 return ErrEmptyChange 7.45 } 7.46 return nil 7.47 @@ -430,6 +439,7 @@ 7.48 func CreateProfileHandler(w http.ResponseWriter, r *http.Request, context Context) { 7.49 scheme, ok := passphraseSchemes[CurPassphraseScheme] 7.50 if !ok { 7.51 + log.Printf("Error selecting passphrase scheme #%d\n", CurPassphraseScheme) 7.52 encode(w, r, http.StatusInternalServerError, actOfGodResponse) 7.53 return 7.54 } 7.55 @@ -448,6 +458,7 @@ 7.56 } 7.57 passphrase, salt, err := scheme.create(req.Passphrase, context.config.iterations) 7.58 if err != nil { 7.59 + log.Printf("Error creating encoded passphrase: %#+v\n", err) 7.60 encode(w, r, http.StatusInternalServerError, actOfGodResponse) 7.61 return 7.62 } 7.63 @@ -467,6 +478,7 @@ 7.64 encode(w, r, http.StatusBadRequest, response{Errors: []requestError{{Slug: requestErrConflict, Field: "/id"}}}) 7.65 return 7.66 } 7.67 + log.Printf("Error saving profile: %#+v\n", err) 7.68 encode(w, r, http.StatusInternalServerError, actOfGodResponse) 7.69 return 7.70 } 7.71 @@ -484,6 +496,7 @@ 7.72 encode(w, r, http.StatusBadRequest, response{Errors: []requestError{{Slug: requestErrConflict, Field: "/email"}}}) 7.73 return 7.74 } 7.75 + log.Printf("Error adding login: %#+v\n", err) 7.76 encode(w, r, http.StatusInternalServerError, actOfGodResponse) 7.77 return 7.78 } 7.79 @@ -497,6 +510,7 @@ 7.80 encode(w, r, http.StatusBadRequest, response{Errors: []requestError{{Slug: requestErrConflict, Field: "/username"}}}) 7.81 return 7.82 } 7.83 + log.Printf("Error adding login: %#+v\n", err) 7.84 encode(w, r, http.StatusInternalServerError, actOfGodResponse) 7.85 return 7.86 } 7.87 @@ -550,6 +564,7 @@ 7.88 decoder := json.NewDecoder(r.Body) 7.89 err = decoder.Decode(&req) 7.90 if err != nil { 7.91 + log.Printf("Error decoding request: %#+v\n", err) 7.92 encode(w, r, http.StatusBadRequest, invalidFormatResponse) 7.93 return 7.94 }
8.1 --- a/profile_postgres.go Sat Mar 21 01:23:33 2015 -0400 8.2 +++ b/profile_postgres.go Sat Mar 21 14:53:15 2015 -0400 8.3 @@ -4,6 +4,7 @@ 8.4 "time" 8.5 8.6 "code.secondbit.org/uuid.hg" 8.7 + "github.com/lib/pq" 8.8 "github.com/secondbit/pan" 8.9 ) 8.10 8.11 @@ -17,10 +18,10 @@ 8.12 8.13 func (p *postgres) getProfileByIDSQL(id uuid.ID) *pan.Query { 8.14 var profile Profile 8.15 - fields, _ := pan.GetQuotedFields(profile) 8.16 + fields, _ := pan.GetFields(profile) 8.17 query := pan.New(pan.POSTGRES, "SELECT "+pan.QueryList(fields)+" FROM "+pan.GetTableName(profile)) 8.18 query.IncludeWhere() 8.19 - query.Include(pan.GetColumn(profile, "ID")+" = ? AND "+pan.GetColumn(profile, "Deleted")+" = ?", id, false) 8.20 + query.Include(pan.GetUnquotedColumn(profile, "ID")+" = ? AND "+pan.GetUnquotedColumn(profile, "Deleted")+" = ?", id, false) 8.21 return query.FlushExpressions(" ") 8.22 } 8.23 8.24 @@ -31,27 +32,32 @@ 8.25 return Profile{}, err 8.26 } 8.27 var profile Profile 8.28 + var found bool 8.29 for rows.Next() { 8.30 err := pan.Unmarshal(rows, &profile) 8.31 if err != nil { 8.32 return Profile{}, err 8.33 } 8.34 + found = true 8.35 } 8.36 if err := rows.Err(); err != nil { 8.37 return Profile{}, err 8.38 } 8.39 + if !found { 8.40 + return profile, ErrProfileNotFound 8.41 + } 8.42 return profile, nil 8.43 } 8.44 8.45 func (p *postgres) getProfileByLoginSQL(value string) *pan.Query { 8.46 var profile Profile 8.47 var login Login 8.48 - fields, _ := pan.GetAbsoluteFields(profile) 8.49 + fields, _ := pan.GetUnquotedAbsoluteFields(profile) 8.50 query := pan.New(pan.POSTGRES, "SELECT "+pan.QueryList(fields)+" FROM "+pan.GetTableName(profile)) 8.51 query.Include("INNER JOIN " + pan.GetTableName(login)) 8.52 - query.Include("ON " + pan.GetAbsoluteColumnName(profile, "ID") + " = " + pan.GetAbsoluteColumnName(login, "ProfileID")) 8.53 + query.Include("ON " + pan.GetUnquotedAbsoluteColumn(profile, "ID") + " = " + pan.GetUnquotedAbsoluteColumn(login, "ProfileID")) 8.54 query.IncludeWhere() 8.55 - query.Include(pan.GetAbsoluteColumnName(login, "Value")+" = ? AND "+pan.GetAbsoluteColumnName(profile, "Deleted")+" = ?", value, false) 8.56 + query.Include(pan.GetUnquotedAbsoluteColumn(login, "Value")+" = ? AND "+pan.GetUnquotedAbsoluteColumn(profile, "Deleted")+" = ?", value, false) 8.57 return query.FlushExpressions(" ") 8.58 } 8.59 8.60 @@ -62,20 +68,25 @@ 8.61 return Profile{}, err 8.62 } 8.63 var profile Profile 8.64 + var found bool 8.65 for rows.Next() { 8.66 err := pan.Unmarshal(rows, &profile) 8.67 if err != nil { 8.68 return Profile{}, err 8.69 } 8.70 + found = true 8.71 } 8.72 if err := rows.Err(); err != nil { 8.73 return Profile{}, err 8.74 } 8.75 + if !found { 8.76 + return profile, ErrProfileNotFound 8.77 + } 8.78 return profile, nil 8.79 } 8.80 8.81 func (p *postgres) saveProfileSQL(profile Profile) *pan.Query { 8.82 - fields, values := pan.GetQuotedFields(profile) 8.83 + fields, values := pan.GetFields(profile) 8.84 query := pan.New(pan.POSTGRES, "INSERT INTO "+pan.GetTableName(profile)) 8.85 query.Include("(" + pan.QueryList(fields) + ")") 8.86 query.Include("VALUES") 8.87 @@ -86,46 +97,55 @@ 8.88 func (p *postgres) saveProfile(profile Profile) error { 8.89 query := p.saveProfileSQL(profile) 8.90 _, err := p.db.Exec(query.String(), query.Args...) 8.91 + if e, ok := err.(*pq.Error); ok && e.Constraint == "profiles_pkey" { 8.92 + err = ErrProfileAlreadyExists 8.93 + } 8.94 return err 8.95 } 8.96 8.97 func (p *postgres) updateProfileSQL(id uuid.ID, change ProfileChange) *pan.Query { 8.98 var profile Profile 8.99 query := pan.New(pan.POSTGRES, "UPDATE "+pan.GetTableName(profile)+" SET ") 8.100 - query.IncludeIfNotNil(pan.GetColumn(profile, "Name")+" = ?", change.Name) 8.101 - query.IncludeIfNotNil(pan.GetColumn(profile, "Passphrase")+" = ?", change.Passphrase) 8.102 - query.IncludeIfNotNil(pan.GetColumn(profile, "Iterations")+" = ?", change.Iterations) 8.103 - query.IncludeIfNotNil(pan.GetColumn(profile, "Salt")+" = ?", change.Salt) 8.104 - query.IncludeIfNotNil(pan.GetColumn(profile, "PassphraseScheme")+" = ?", change.PassphraseScheme) 8.105 - query.IncludeIfNotNil(pan.GetColumn(profile, "Compromised")+" = ?", change.Compromised) 8.106 - query.IncludeIfNotNil(pan.GetColumn(profile, "LockedUntil")+" = ?", change.LockedUntil) 8.107 - query.IncludeIfNotNil(pan.GetColumn(profile, "PassphraseReset")+" = ?", change.PassphraseReset) 8.108 - query.IncludeIfNotNil(pan.GetColumn(profile, "PassphraseResetCreated")+" = ?", change.PassphraseResetCreated) 8.109 - query.IncludeIfNotNil(pan.GetColumn(profile, "LastSeen")+" = ?", change.LastSeen) 8.110 - query.IncludeIfNotNil(pan.GetColumn(profile, "Deleted")+" = ?", change.Deleted) 8.111 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "Name")+" = ?", change.Name) 8.112 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "Passphrase")+" = ?", change.Passphrase) 8.113 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "Iterations")+" = ?", change.Iterations) 8.114 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "Salt")+" = ?", change.Salt) 8.115 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "PassphraseScheme")+" = ?", change.PassphraseScheme) 8.116 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "Compromised")+" = ?", change.Compromised) 8.117 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "LockedUntil")+" = ?", change.LockedUntil) 8.118 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "PassphraseReset")+" = ?", change.PassphraseReset) 8.119 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "PassphraseResetCreated")+" = ?", change.PassphraseResetCreated) 8.120 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "LastSeen")+" = ?", change.LastSeen) 8.121 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "Deleted")+" = ?", change.Deleted) 8.122 query.FlushExpressions(", ") 8.123 query.IncludeWhere() 8.124 - query.Include(pan.GetColumn(profile, "ID")+"= ?", id) 8.125 + query.Include(pan.GetUnquotedColumn(profile, "ID")+"= ?", id) 8.126 return query.FlushExpressions(" ") 8.127 } 8.128 8.129 func (p *postgres) updateProfile(id uuid.ID, change ProfileChange) error { 8.130 + if change.Empty() { 8.131 + return nil 8.132 + } 8.133 query := p.updateProfileSQL(id, change) 8.134 _, err := p.db.Exec(query.String(), query.Args...) 8.135 return err 8.136 } 8.137 8.138 func (p *postgres) updateProfilesSQL(ids []uuid.ID, change BulkProfileChange) *pan.Query { 8.139 + if change.Empty() { 8.140 + return nil 8.141 + } 8.142 var profile Profile 8.143 query := pan.New(pan.POSTGRES, "UPDATE "+pan.GetTableName(profile)+" SET ") 8.144 - query.IncludeIfNotNil(pan.GetColumn(profile, "Compromised")+" = ?", change.Compromised) 8.145 + query.IncludeIfNotNil(pan.GetUnquotedColumn(profile, "Compromised")+" = ?", change.Compromised) 8.146 query.FlushExpressions(", ") 8.147 query.IncludeWhere() 8.148 intids := make([]interface{}, len(ids)) 8.149 for pos, id := range ids { 8.150 intids[pos] = id 8.151 } 8.152 - query.Include(pan.GetColumn(profile, "ID")+" IN ("+pan.VariableList(len(ids))+")", intids...) 8.153 + query.Include(pan.GetUnquotedColumn(profile, "ID")+" IN ("+pan.VariableList(len(ids))+")", intids...) 8.154 return query.FlushExpressions(" ") 8.155 } 8.156 8.157 @@ -136,7 +156,7 @@ 8.158 } 8.159 8.160 func (p *postgres) addLoginSQL(login Login) *pan.Query { 8.161 - fields, values := pan.GetQuotedFields(login) 8.162 + fields, values := pan.GetFields(login) 8.163 query := pan.New(pan.POSTGRES, "INSERT INTO "+pan.GetTableName(login)) 8.164 query.Include("(" + pan.QueryList(fields) + ")") 8.165 query.Include("VALUES") 8.166 @@ -147,6 +167,9 @@ 8.167 func (p *postgres) addLogin(login Login) error { 8.168 query := p.addLoginSQL(login) 8.169 _, err := p.db.Exec(query.String(), query.Args...) 8.170 + if e, ok := err.(*pq.Error); ok && e.Constraint == "logins_pkey" { 8.171 + return ErrLoginAlreadyExists 8.172 + } 8.173 return err 8.174 } 8.175 8.176 @@ -154,22 +177,32 @@ 8.177 var login Login 8.178 query := pan.New(pan.POSTGRES, "DELETE FROM "+pan.GetTableName(login)) 8.179 query.IncludeWhere() 8.180 - query.Include(pan.GetColumn(login, "Value")+"= ? AND "+pan.GetColumn(login, "ProfileID")+"= ?", value, profile) 8.181 + query.Include(pan.GetUnquotedColumn(login, "Value")+"= ? AND "+pan.GetUnquotedColumn(login, "ProfileID")+"= ?", value, profile) 8.182 return query.FlushExpressions(" ") 8.183 } 8.184 8.185 func (p *postgres) removeLogin(value string, profile uuid.ID) error { 8.186 query := p.removeLoginSQL(value, profile) 8.187 - _, err := p.db.Exec(query.String(), query.Args...) 8.188 - return err 8.189 + res, err := p.db.Exec(query.String(), query.Args...) 8.190 + if err != nil { 8.191 + return err 8.192 + } 8.193 + rows, err := res.RowsAffected() 8.194 + if err != nil { 8.195 + return err 8.196 + } 8.197 + if rows == 0 { 8.198 + return ErrLoginNotFound 8.199 + } 8.200 + return nil 8.201 } 8.202 8.203 func (p *postgres) recordLoginUseSQL(value string, when time.Time) *pan.Query { 8.204 var login Login 8.205 query := pan.New(pan.POSTGRES, "UPDATE "+pan.GetTableName(login)+" SET ") 8.206 - query.Include(pan.GetColumn(login, "LastUsed")+"= ?", when) 8.207 + query.Include(pan.GetUnquotedColumn(login, "LastUsed")+"= ?", when) 8.208 query.IncludeWhere() 8.209 - query.Include(pan.GetColumn(login, "Value")+"= ?", value) 8.210 + query.Include(pan.GetUnquotedColumn(login, "Value")+"= ?", value) 8.211 return query.FlushExpressions(" ") 8.212 } 8.213 8.214 @@ -181,10 +214,10 @@ 8.215 8.216 func (p *postgres) listLoginsSQL(profile uuid.ID, num, offset int) *pan.Query { 8.217 var login Login 8.218 - fields, _ := pan.GetQuotedFields(login) 8.219 + fields, _ := pan.GetFields(login) 8.220 query := pan.New(pan.POSTGRES, "SELECT "+pan.QueryList(fields)+" FROM "+pan.GetTableName(login)) 8.221 query.IncludeWhere() 8.222 - query.Include(pan.GetColumn(login, "ProfileID")+"= ?", profile) 8.223 + query.Include(pan.GetUnquotedColumn(login, "ProfileID")+"= ?", profile) 8.224 query.IncludeLimit(int64(num)) 8.225 query.IncludeOffset(int64(offset)) 8.226 return query.FlushExpressions(" ")
9.1 --- a/profile_test.go Sat Mar 21 01:23:33 2015 -0400 9.2 +++ b/profile_test.go Sat Mar 21 14:53:15 2015 -0400 9.3 @@ -21,6 +21,16 @@ 9.4 profileChangeLastSeen 9.5 ) 9.6 9.7 +func init() { 9.8 + p, err := NewPostgres("dbname=testdb sslmode=disable") 9.9 + if err != nil { 9.10 + panic(err) 9.11 + } 9.12 + if !testing.Short() { 9.13 + profileStores = append(profileStores, &p) 9.14 + } 9.15 +} 9.16 + 9.17 var profileStores = []profileStore{NewMemstore()} 9.18 9.19 func compareProfiles(profile1, profile2 Profile) (success bool, field string, val1, val2 interface{}) { 9.20 @@ -95,11 +105,11 @@ 9.21 Salt: "salt", 9.22 PassphraseScheme: 1, 9.23 Compromised: false, 9.24 - LockedUntil: time.Now().Add(time.Hour), 9.25 + LockedUntil: time.Now().Add(time.Hour).Round(time.Millisecond), 9.26 PassphraseReset: "passphrase reset", 9.27 - PassphraseResetCreated: time.Now(), 9.28 - Created: time.Now(), 9.29 - LastSeen: time.Now(), 9.30 + PassphraseResetCreated: time.Now().Round(time.Millisecond), 9.31 + Created: time.Now().Round(time.Millisecond), 9.32 + LastSeen: time.Now().Round(time.Millisecond), 9.33 } 9.34 for _, store := range profileStores { 9.35 context := Context{profiles: store} 9.36 @@ -142,11 +152,11 @@ 9.37 Salt: "salt", 9.38 PassphraseScheme: 1, 9.39 Compromised: false, 9.40 - LockedUntil: time.Now().Add(time.Hour), 9.41 + LockedUntil: time.Now().Add(time.Hour).Round(time.Millisecond), 9.42 PassphraseReset: "passphrase reset", 9.43 - PassphraseResetCreated: time.Now(), 9.44 - Created: time.Now(), 9.45 - LastSeen: time.Now(), 9.46 + PassphraseResetCreated: time.Now().Round(time.Millisecond), 9.47 + Created: time.Now().Round(time.Millisecond), 9.48 + LastSeen: time.Now().Round(time.Millisecond), 9.49 } 9.50 for i := 0; i < variations; i++ { 9.51 var name, passphrase, salt, passphraseReset string 9.52 @@ -190,7 +200,7 @@ 9.53 expectation.Compromised = compromised 9.54 } 9.55 if i&profileChangeLockedUntil != 0 { 9.56 - lockedUntil = time.Now() 9.57 + lockedUntil = time.Now().Round(time.Millisecond) 9.58 change.LockedUntil = &lockedUntil 9.59 expectation.LockedUntil = lockedUntil 9.60 } 9.61 @@ -200,12 +210,12 @@ 9.62 expectation.PassphraseReset = passphraseReset 9.63 } 9.64 if i&profileChangePassphraseResetCreated != 0 { 9.65 - passphraseResetCreated = time.Now() 9.66 + passphraseResetCreated = time.Now().Round(time.Millisecond) 9.67 change.PassphraseResetCreated = &passphraseResetCreated 9.68 expectation.PassphraseResetCreated = passphraseResetCreated 9.69 } 9.70 if i&profileChangeLastSeen != 0 { 9.71 - lastSeen = time.Now() 9.72 + lastSeen = time.Now().Round(time.Millisecond) 9.73 change.LastSeen = &lastSeen 9.74 expectation.LastSeen = lastSeen 9.75 } 9.76 @@ -303,8 +313,8 @@ 9.77 Type: "type", 9.78 Value: "value", 9.79 ProfileID: uuid.NewID(), 9.80 - Created: time.Now().Add(-1 * time.Hour), 9.81 - LastUsed: time.Now().Add(-1 * time.Minute), 9.82 + Created: time.Now().Add(-1 * time.Hour).Round(time.Millisecond), 9.83 + LastUsed: time.Now().Add(-1 * time.Minute).Round(time.Millisecond), 9.84 } 9.85 for _, store := range profileStores { 9.86 context := Context{profiles: store} 9.87 @@ -327,7 +337,7 @@ 9.88 if !match { 9.89 t.Errorf("Expected `%v` in the `%s` field of login retrieved from %T, got `%v`", expectation, field, store, result) 9.90 } 9.91 - lastUsed := time.Now() 9.92 + lastUsed := time.Now().Round(time.Millisecond) 9.93 err = context.RecordLoginUse(login.Value, lastUsed) 9.94 if err != nil { 9.95 t.Errorf("Error recording use of login to %T: %s", store, err) 9.96 @@ -369,18 +379,18 @@ 9.97 Salt: "salt", 9.98 PassphraseScheme: 1, 9.99 Compromised: false, 9.100 - LockedUntil: time.Now().Add(time.Hour), 9.101 + LockedUntil: time.Now().Add(time.Hour).Round(time.Millisecond), 9.102 PassphraseReset: "passphrase reset", 9.103 - PassphraseResetCreated: time.Now(), 9.104 - Created: time.Now(), 9.105 - LastSeen: time.Now(), 9.106 + PassphraseResetCreated: time.Now().Round(time.Millisecond), 9.107 + Created: time.Now().Round(time.Millisecond), 9.108 + LastSeen: time.Now().Round(time.Millisecond), 9.109 } 9.110 login := Login{ 9.111 Type: "type", 9.112 Value: "value", 9.113 ProfileID: profile.ID, 9.114 - Created: time.Now().Add(-1 * time.Hour), 9.115 - LastUsed: time.Now().Add(-1 * time.Minute), 9.116 + Created: time.Now().Add(-1 * time.Hour).Round(time.Millisecond), 9.117 + LastUsed: time.Now().Add(-1 * time.Minute).Round(time.Millisecond), 9.118 } 9.119 for _, store := range profileStores { 9.120 context := Context{profiles: store} 9.121 @@ -413,9 +423,9 @@ 9.122 enteredName := "Paddy" 9.123 okPassphrase := "this is a decent passphrase" 9.124 compromised := true 9.125 - lockedUntil := time.Now() 9.126 - resetCreated := time.Now() 9.127 - lastSeen := time.Now() 9.128 + lockedUntil := time.Now().Round(time.Millisecond) 9.129 + resetCreated := time.Now().Round(time.Millisecond) 9.130 + lastSeen := time.Now().Round(time.Millisecond) 9.131 changes := map[*ProfileChange]error{ 9.132 &ProfileChange{}: ErrEmptyChange, 9.133 &ProfileChange{PassphraseScheme: &passphraseScheme}: ErrMissingPassphrase,
10.1 --- a/session_test.go Sat Mar 21 01:23:33 2015 -0400 10.2 +++ b/session_test.go Sat Mar 21 14:53:15 2015 -0400 10.3 @@ -47,7 +47,7 @@ 10.4 IP: "127.0.0.1", 10.5 UserAgent: "TestRunner", 10.6 ProfileID: uuid.NewID(), 10.7 - Created: time.Now(), 10.8 + Created: time.Now().Round(time.Millisecond), 10.9 Login: "test@example.com", 10.10 Active: true, 10.11 }
11.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 11.2 +++ b/sql/postgres_init.sql Sat Mar 21 14:53:15 2015 -0400 11.3 @@ -0,0 +1,23 @@ 11.4 +CREATE TABLE IF NOT EXISTS profiles ( 11.5 + id VARCHAR(36) PRIMARY KEY, 11.6 + name VARCHAR(64) NOT NULL, 11.7 + passphrase VARCHAR(64) NOT NULL, 11.8 + iterations INTEGER NOT NULL, 11.9 + salt VARCHAR(64) NOT NULL, 11.10 + passphrase_scheme INTEGER NOT NULL, 11.11 + compromised BOOLEAN NOT NULL, 11.12 + locked_until TIMESTAMPTZ NOT NULL, 11.13 + passphrase_reset VARCHAR(64) NOT NULL, 11.14 + passphrase_reset_created TIMESTAMPTZ NOT NULL, 11.15 + created TIMESTAMPTZ NOT NULL, 11.16 + last_seen TIMESTAMPTZ NOT NULL, 11.17 + deleted BOOLEAN NOT NULL 11.18 +); 11.19 + 11.20 +CREATE TABLE IF NOT EXISTS logins ( 11.21 + type VARCHAR(16) NOT NULL, 11.22 + value VARCHAR(64) PRIMARY KEY, 11.23 + profile_id VARCHAR(36) NOT NULL, 11.24 + created TIMESTAMPTZ NOT NULL, 11.25 + last_used TIMESTAMPTZ NOT NULL 11.26 +);
12.1 --- a/token_test.go Sat Mar 21 01:23:33 2015 -0400 12.2 +++ b/token_test.go Sat Mar 21 14:53:15 2015 -0400 12.3 @@ -50,7 +50,7 @@ 12.4 token := Token{ 12.5 AccessToken: "access", 12.6 RefreshToken: "refresh", 12.7 - Created: time.Now(), 12.8 + Created: time.Now().Round(time.Millisecond), 12.9 ExpiresIn: 3600, 12.10 TokenType: "bearer", 12.11 Scopes: []string{"scope"},