func (s *AuthSuite) testLogins(user t.TestUser, c *gc.C) error { s.createUsers(c) defer s.deleteUsers(c) key, err := auth.LoginUser(s.d, user.Email, user.Pwhash) if err != nil { return err } userBytes, err := db.GetByKey(s.d, auth.SessionKeys, []byte(user.Email)) if err != nil { return err } c.Assert(len(userBytes), gc.Not(gc.Equals), 0) var login auth.Login err = json.Unmarshal(userBytes, &login) if err != nil { return err } c.Assert(login.Key, gc.Equals, key) return nil }
func (s *AuthSuite) TestValidUser(c *gc.C) { s.createUsers(c) b := s.users["bob"] key, err := auth.LoginUser(s.d, b.Email, b.Pwhash) c.Assert(err, gc.IsNil) s.users["bob"] = t.TestUser{ Email: b.Email, LoginKey: string(key), } for i, t := range []struct { should string user t.TestUser pause int expectError string }{{ should: "Validate an existing login", user: s.users["bob"], }, { should: "Not validate an existing login with bad key", user: t.TestUser{Email: b.Email, LoginKey: "foo"}, expectError: `bad key "foo" for user "*****@*****.**"`, }, { should: "Not validate a nonexistent user", user: t.TestUser{Email: "*****@*****.**", LoginKey: "foo"}, expectError: `user "*****@*****.**" not logged in user not found`, }, { should: "Not validate a timed-out user", pause: 80, user: s.users["bob"], expectError: `user "*****@*****.**" timed out not valid`, }} { c.Logf("test %d: should %s", i, t.should) if t.expectError == "" { c.Check(s.testValidate(t.user, t.pause, c), gc.IsNil) } else { c.Check(s.testValidate(t.user, t.pause, c), gc.ErrorMatches, t.expectError) } } }
func handleLogin(d db.DB) htr.Handle { return func(w http.ResponseWriter, r *http.Request, ps htr.Params) { err := r.ParseForm() if err != nil { WriteResponse(w, newApiError("bad request: "+err.Error(), err)) log.Error("bad request: %#v", r) return } email := r.Form.Get("email") pwhash := r.Form.Get("pwhash") key, err := auth.LoginUser(d, email, pwhash) if err != nil { WriteResponse(w, newApiError(err.Error(), err)) log.Error("error logging in user %q, pwhash %q: %s", email, pwhash, err.Error()) return } log.Info("user %q logged in", email) WriteResponse(w, &auth.User{ Email: email, Key: key, }) } }
func (s *AuthSuite) logoutTests(user t.TestUser, key util.Key, login bool, c *gc.C) error { if login { key, err := auth.LoginUser(s.d, user.Email, user.Pwhash) c.Assert(err, gc.IsNil) user = t.TestUser{ Email: user.Email, Pwhash: user.Pwhash, LoginKey: string(key), } } if key != util.Key("") { user.LoginKey = string(key) } err := auth.LogoutUser(s.d, user.Email, util.Key(user.LoginKey)) if err != nil { return err } err = auth.LogoutUser(s.d, user.Email, util.Key(user.LoginKey)) c.Assert(err, gc.ErrorMatches, fmt.Sprintf("user %q not logged in user not found", user.Email)) return nil }