func CreateUser(w http.ResponseWriter, r *http.Request) error { var u auth.User err := json.NewDecoder(r.Body).Decode(&u) if err != nil { return &errors.Http{Code: http.StatusBadRequest, Message: err.Error()} } if !validation.ValidateEmail(u.Email) { return &errors.Http{Code: http.StatusPreconditionFailed, Message: emailError} } if !validation.ValidateLength(u.Password, passwordMinLen, passwordMaxLen) { return &errors.Http{Code: http.StatusPreconditionFailed, Message: passwordError} } gUrl := repository.GitServerUri() c := gandalf.Client{Endpoint: gUrl} if _, err := c.NewUser(u.Email, keyToMap(u.Keys)); err != nil { return fmt.Errorf("Failed to create user in the git server: %s", err) } if err := u.Create(); err == nil { w.WriteHeader(http.StatusCreated) return nil } if u.Get() == nil { err = &errors.Http{Code: http.StatusConflict, Message: "This email is already registered"} } return err }
func createUser(w http.ResponseWriter, r *http.Request) error { var u auth.User err := json.NewDecoder(r.Body).Decode(&u) if err != nil { return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()} } if !validation.ValidateEmail(u.Email) { return &errors.HTTP{Code: http.StatusBadRequest, Message: emailError} } if !validation.ValidateLength(u.Password, passwordMinLen, passwordMaxLen) { return &errors.HTTP{Code: http.StatusBadRequest, Message: passwordError} } gURL := repository.ServerURL() c := gandalf.Client{Endpoint: gURL} if _, err := c.NewUser(u.Email, keyToMap(u.Keys)); err != nil { return fmt.Errorf("Failed to create user in the git server: %s", err) } if err := u.Create(); err == nil { rec.Log(u.Email, "create-user") if limit, err := config.GetUint("quota:apps-per-user"); err == nil { quota.Create(u.Email, uint(limit)) } w.WriteHeader(http.StatusCreated) return nil } if _, err = auth.GetUserByEmail(u.Email); err == nil { err = &errors.HTTP{Code: http.StatusConflict, Message: "This email is already registered"} } return err }
func (s *AuthSuite) TestRemoveUserFromTeamShouldRemoveOnlyAppsInThatTeamInGandalfWhenUserIsInMoreThanOneTeam(c *gocheck.C) { h := testHandler{} ts := s.startGandalfTestServer(&h) defer ts.Close() u := auth.User{Email: "*****@*****.**", Password: "******"} err := u.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Users().Remove(bson.M{"email": u.Email}) s.team.AddUser(&u) s.conn.Teams().UpdateId(s.team.Name, s.team) team2 := auth.Team{Name: "team2", Users: []string{u.Email}} err = s.conn.Teams().Insert(&team2) c.Assert(err, gocheck.IsNil) defer s.conn.Teams().RemoveId(team2.Name) app1 := app.App{Name: "app1", Teams: []string{s.team.Name}} err = s.conn.Apps().Insert(&app1) c.Assert(err, gocheck.IsNil) defer s.conn.Apps().Remove(bson.M{"name": app1.Name}) app2 := app.App{Name: "app2", Teams: []string{team2.Name}} err = s.conn.Apps().Insert(&app2) c.Assert(err, gocheck.IsNil) defer s.conn.Apps().Remove(bson.M{"name": app2.Name}) err = removeUserFromTeam(u.Email, s.team.Name, s.user) c.Assert(err, gocheck.IsNil) expected := `{"repositories":["app1"],"users":["*****@*****.**"]}` c.Assert(len(h.body), gocheck.Equals, 1) c.Assert(string(h.body[0]), gocheck.Equals, expected) s.conn.Teams().FindId(s.team.Name).One(s.team) c.Assert(s.team, gocheck.Not(ContainsUser), &u) // just in case }
func (s *AuthSuite) TestRemoveUserRevokesAccessInGandalf(c *gocheck.C) { h := testHandler{} ts := s.startGandalfTestServer(&h) defer ts.Close() u := auth.User{Email: "*****@*****.**"} err := u.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Users().Remove(bson.M{"email": u.Email}) t := auth.Team{Name: "painofsalvation", Users: []string{u.Email, s.user.Email}} err = s.conn.Teams().Insert(t) c.Assert(err, gocheck.IsNil) defer s.conn.Teams().Remove(bson.M{"_id": t.Name}) a := struct { Name string Teams []string }{Name: "myApp", Teams: []string{t.Name}} err = s.conn.Apps().Insert(a) c.Assert(err, gocheck.IsNil) defer s.conn.Apps().Remove(bson.M{"name": a.Name}) request, err := http.NewRequest("DELETE", "/users", nil) c.Assert(err, gocheck.IsNil) recorder := httptest.NewRecorder() err = RemoveUser(recorder, request, &u) c.Assert(err, gocheck.IsNil) c.Assert(h.url[0], gocheck.Equals, "/repository/revoke") c.Assert(h.method[0], gocheck.Equals, "DELETE") expected := `{"repositories":["myApp"],"users":["*****@*****.**"]}` c.Assert(string(h.body[0]), gocheck.Equals, expected) }
func (s *AuthSuite) TestRemoveUserWithTheUserBeingLastMemberOfATeam(c *gocheck.C) { h := testHandler{} ts := s.startGandalfTestServer(&h) defer ts.Close() u := auth.User{Email: "*****@*****.**"} err := u.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Users().Remove(bson.M{"email": u.Email}) t := auth.Team{Name: "painofsalvation", Users: []string{u.Email}} err = s.conn.Teams().Insert(t) c.Assert(err, gocheck.IsNil) defer s.conn.Teams().Remove(bson.M{"_id": t.Name}) request, err := http.NewRequest("DELETE", "/users", nil) c.Assert(err, gocheck.IsNil) recorder := httptest.NewRecorder() err = RemoveUser(recorder, request, &u) c.Assert(err, gocheck.NotNil) e, ok := err.(*errors.Http) c.Assert(ok, gocheck.Equals, true) c.Assert(e.Code, gocheck.Equals, http.StatusForbidden) expected := `This user is the last member of the team "painofsalvation", so it cannot be removed. Please remove the team, them remove the user.` c.Assert(e.Message, gocheck.Equals, expected) }
func (s *AuthSuite) TestListTeamsReturns204IfTheUserHasNoTeam(c *gocheck.C) { u := auth.User{Email: "*****@*****.**", Password: "******"} err := u.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Users().Remove(bson.M{"email": u.Email}) request, err := http.NewRequest("GET", "/teams", nil) c.Assert(err, gocheck.IsNil) recorder := httptest.NewRecorder() err = ListTeams(recorder, request, &u) c.Assert(err, gocheck.IsNil) c.Assert(recorder.Code, gocheck.Equals, http.StatusNoContent) }
func (s *AuthSuite) TestLoginShouldreturnErrorIfThePasswordDoesNotMatch(c *gocheck.C) { u := auth.User{Email: "*****@*****.**", Password: "******"} u.Create() b := bytes.NewBufferString(`{"password":"******"}`) request, err := http.NewRequest("POST", "/users/[email protected]/tokens?:[email protected]", b) c.Assert(err, gocheck.IsNil) request.Header.Set("Content-type", "application/json") recorder := httptest.NewRecorder() err = Login(recorder, request) c.Assert(err, gocheck.NotNil) c.Assert(err, gocheck.ErrorMatches, "^Authentication failed, wrong password$") e, ok := err.(*errors.Http) c.Assert(ok, gocheck.Equals, true) c.Assert(e.Code, gocheck.Equals, http.StatusUnauthorized) }
func (s *S) TestReserveUserAppForwardQuotaExceeded(c *gocheck.C) { user := auth.User{ Email: "*****@*****.**", Quota: quota.Quota{Limit: 1, InUse: 1}, } err := user.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Users().Remove(bson.M{"email": user.Email}) app := App{ Name: "clap", Platform: "django", } previous, err := reserveUserApp.Forward(action.FWContext{Params: []interface{}{app, user}}) c.Assert(previous, gocheck.IsNil) _, ok := err.(*quota.QuotaExceededError) c.Assert(ok, gocheck.Equals, true) }
func (s *AuthSuite) TestRemoveUser(c *gocheck.C) { h := testHandler{} ts := s.startGandalfTestServer(&h) defer ts.Close() u := auth.User{Email: "*****@*****.**"} err := u.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Users().Remove(bson.M{"email": u.Email}) request, err := http.NewRequest("DELETE", "/users", nil) c.Assert(err, gocheck.IsNil) recorder := httptest.NewRecorder() err = RemoveUser(recorder, request, &u) c.Assert(err, gocheck.IsNil) n, err := s.conn.Users().Find(bson.M{"email": u.Email}).Count() c.Assert(err, gocheck.IsNil) c.Assert(n, gocheck.Equals, 0) }
func (s *AuthSuite) TestLoginShouldCreateTokenInTheDatabaseAndReturnItWithinTheResponse(c *gocheck.C) { u := auth.User{Email: "*****@*****.**", Password: "******"} u.Create() b := bytes.NewBufferString(`{"password":"******"}`) request, err := http.NewRequest("POST", "/users/[email protected]/tokens?:[email protected]", b) c.Assert(err, gocheck.IsNil) request.Header.Set("Content-type", "application/json") recorder := httptest.NewRecorder() err = Login(recorder, request) c.Assert(err, gocheck.IsNil) var user auth.User collection := s.conn.Users() err = collection.Find(bson.M{"email": "*****@*****.**"}).One(&user) var recorderJson map[string]string r, _ := ioutil.ReadAll(recorder.Body) json.Unmarshal(r, &recorderJson) c.Assert(recorderJson["token"], gocheck.Equals, user.Tokens[0].Token) }
func (s *AuthSuite) TestCreateUserHandlerReturnErrorAndConflictIfItFailsToCreateUser(c *gocheck.C) { h := testHandler{} ts := s.startGandalfTestServer(&h) defer ts.Close() u := auth.User{Email: "*****@*****.**", Password: "******"} u.Create() b := bytes.NewBufferString(`{"email":"*****@*****.**","password":"******"}`) request, err := http.NewRequest("POST", "/users", b) c.Assert(err, gocheck.IsNil) request.Header.Set("Content-type", "application/json") recorder := httptest.NewRecorder() err = CreateUser(recorder, request) c.Assert(err, gocheck.NotNil) c.Assert(err, gocheck.ErrorMatches, "This email is already registered") e, ok := err.(*errors.Http) c.Assert(ok, gocheck.Equals, true) c.Assert(e.Code, gocheck.Equals, http.StatusConflict) }
func (s *AuthSuite) TestRemoveUserFromTeamShouldRemoveAUserFromATeamIfTheTeamExistAndTheUserIsMemberOfTheTeam(c *gocheck.C) { h := testHandler{} ts := s.startGandalfTestServer(&h) defer ts.Close() u := auth.User{Email: "*****@*****.**", Password: "******"} err := u.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Users().Remove(bson.M{"email": u.Email}) s.team.AddUser(&u) s.conn.Teams().Update(bson.M{"_id": s.team.Name}, s.team) request, err := http.NewRequest("DELETE", "/teams/tsuruteam/[email protected]?:team=tsuruteam&:[email protected]", nil) c.Assert(err, gocheck.IsNil) recorder := httptest.NewRecorder() err = RemoveUserFromTeam(recorder, request, s.user) c.Assert(err, gocheck.IsNil) err = s.conn.Teams().Find(bson.M{"_id": s.team.Name}).One(s.team) c.Assert(err, gocheck.IsNil) c.Assert(s.team, gocheck.Not(ContainsUser), &u) }
func (s *S) TestGetServiceInstancesByServicesAndTeamsForUsersThatAreNotMembersOfAnyTeam(c *gocheck.C) { u := auth.User{Email: "*****@*****.**", Password: "******"} err := u.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Users().Remove(bson.M{"email": u.Email}) srvc := Service{Name: "mysql", Teams: []string{s.team.Name}, IsRestricted: true} err = srvc.Create() c.Assert(err, gocheck.IsNil) defer srvc.Delete() instance := ServiceInstance{ Name: "j4sql", ServiceName: srvc.Name, } err = instance.Create() c.Assert(err, gocheck.IsNil) defer DeleteInstance(&instance) instances, err := GetServiceInstancesByServicesAndTeams([]Service{srvc}, &u) c.Assert(err, gocheck.IsNil) c.Assert(instances, gocheck.IsNil) }
func (s *S) TestReserveUserAppBackward(c *gocheck.C) { user := auth.User{ Email: "*****@*****.**", Quota: quota.Quota{Limit: 1, InUse: 1}, } err := user.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Users().Remove(bson.M{"email": user.Email}) app := App{ Name: "clap", Platform: "django", } ctx := action.BWContext{ FWResult: map[string]string{ "app": app.Name, "user": user.Email, }, } reserveUserApp.Backward(ctx) err = auth.ReserveApp(&user) c.Assert(err, gocheck.IsNil) }
func (s *AuthSuite) TestRemoveUserShouldRemoveTheUserFromAllTeamsThatHeIsMember(c *gocheck.C) { h := testHandler{} ts := s.startGandalfTestServer(&h) defer ts.Close() u := auth.User{Email: "*****@*****.**"} err := u.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Users().Remove(bson.M{"email": u.Email}) t := auth.Team{Name: "painofsalvation", Users: []string{u.Email, s.user.Email}} err = s.conn.Teams().Insert(t) c.Assert(err, gocheck.IsNil) defer s.conn.Teams().Remove(bson.M{"_id": t.Name}) request, err := http.NewRequest("DELETE", "/users", nil) c.Assert(err, gocheck.IsNil) recorder := httptest.NewRecorder() err = RemoveUser(recorder, request, &u) c.Assert(err, gocheck.IsNil) err = s.conn.Teams().Find(bson.M{"_id": t.Name}).One(&t) c.Assert(err, gocheck.IsNil) c.Assert(t.Users, gocheck.HasLen, 1) c.Assert(t.Users[0], gocheck.Equals, s.user.Email) }
func (s *S) TestReserveUserAppForwardAppNotPointer(c *gocheck.C) { user := auth.User{ Email: "*****@*****.**", Quota: quota.Quota{Limit: 1}, } err := user.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Users().Remove(bson.M{"email": user.Email}) app := App{ Name: "clap", Platform: "django", } expected := map[string]string{"user": user.Email, "app": app.Name} previous, err := reserveUserApp.Forward(action.FWContext{Params: []interface{}{app, user}}) c.Assert(err, gocheck.IsNil) c.Assert(previous, gocheck.DeepEquals, expected) err = auth.ReserveApp(&user) _, ok := err.(*quota.QuotaExceededError) c.Assert(ok, gocheck.Equals, true) err = auth.ReleaseApp(&user) c.Assert(err, gocheck.IsNil) err = auth.ReserveApp(&user) c.Assert(err, gocheck.IsNil) }