Esempio n. 1
0
func removeUserFromTeam(w http.ResponseWriter, r *http.Request, t *auth.Token) error {
	email := r.URL.Query().Get(":user")
	teamName := r.URL.Query().Get(":team")
	u, err := t.User()
	if err != nil {
		return err
	}
	rec.Log(u.Email, "remove-user-from-team", "team="+teamName, "user="******"Team not found"}
	}
	if !team.ContainsUser(u) {
		msg := fmt.Sprintf("You are not authorized to remove a member from the team %s", team.Name)
		return &errors.HTTP{Code: http.StatusUnauthorized, Message: msg}
	}
	if len(team.Users) == 1 {
		msg := "You can not remove this user from this team, because it is the last user within the team, and a team can not be orphaned"
		return &errors.HTTP{Code: http.StatusForbidden, Message: msg}
	}
	user, err := auth.GetUserByEmail(email)
	if err != nil {
		return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
	}
	err = removeUserFromTeamInGandalf(user, team.Name)
	if err != nil {
		return nil
	}
	return removeUserFromTeamInDatabase(user, team)
}
Esempio n. 2
0
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
}
Esempio n. 3
0
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 _, err = auth.GetUserByEmail(u.Email); err == nil {
		err = &errors.Http{Code: http.StatusConflict, Message: "This email is already registered"}
	}
	return err
}
Esempio n. 4
0
func addUserToTeam(w http.ResponseWriter, r *http.Request, t *auth.Token) error {
	teamName := r.URL.Query().Get(":team")
	email := r.URL.Query().Get(":user")
	u, err := t.User()
	if err != nil {
		return err
	}
	rec.Log(u.Email, "add-user-to-team", "team="+teamName, "user="******"Team not found"}
	}
	if !team.ContainsUser(u) {
		msg := fmt.Sprintf("You are not authorized to add new users to the team %s", team.Name)
		return &errors.HTTP{Code: http.StatusUnauthorized, Message: msg}
	}
	user, err := auth.GetUserByEmail(email)
	if err != nil {
		return &errors.HTTP{Code: http.StatusNotFound, Message: "User not found"}
	}
	actions := []*action.Action{
		&addUserToTeamInGandalfAction,
		&addUserToTeamInDatabaseAction,
	}
	pipeline := action.NewPipeline(actions...)
	return pipeline.Execute(user.Email, u, team)
}
Esempio n. 5
0
func removeUserFromTeam(email, teamName string, u *auth.User) error {
	conn, err := db.Conn()
	if err != nil {
		return err
	}
	defer conn.Close()
	team := new(auth.Team)
	err = conn.Teams().FindId(teamName).One(team)
	if err != nil {
		return &errors.Http{Code: http.StatusNotFound, Message: "Team not found"}
	}
	if !team.ContainsUser(u) {
		msg := fmt.Sprintf("You are not authorized to remove a member from the team %s", team.Name)
		return &errors.Http{Code: http.StatusUnauthorized, Message: msg}
	}
	if len(team.Users) == 1 {
		msg := "You can not remove this user from this team, because it is the last user within the team, and a team can not be orphaned"
		return &errors.Http{Code: http.StatusForbidden, Message: msg}
	}
	user, err := auth.GetUserByEmail(email)
	if err != nil {
		return &errors.Http{Code: http.StatusNotFound, Message: err.Error()}
	}
	err = removeUserFromTeamInGandalf(user, team.Name)
	if err != nil {
		return nil
	}
	return removeUserFromTeamInDatabase(user, team)
}
Esempio n. 6
0
func (s *ActionsSuite) TestAddKeyInDatabaseActionBackward(c *gocheck.C) {
	key := &auth.Key{Name: "mysshkey", Content: "my-ssh-key"}
	u := &auth.User{Email: "*****@*****.**", Password: "******"}
	u.AddKey(*key)
	err := u.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	c.Assert(u.Keys, gocheck.DeepEquals, []auth.Key{*key}) // just in case
	ctx := action.BWContext{
		Params: []interface{}{key, u},
	}
	addKeyInDatabaseAction.Backward(ctx)
	u, err = auth.GetUserByEmail(u.Email)
	c.Assert(err, gocheck.IsNil)
	c.Assert(u.Keys, gocheck.DeepEquals, []auth.Key{})
}
Esempio n. 7
0
func (s *ActionsSuite) TestAddKeyInDatabaseActionForward(c *gocheck.C) {
	key := &auth.Key{Name: "mysshkey", Content: "my-ssh-key"}
	u := &auth.User{Email: "*****@*****.**", Password: "******"}
	err := u.Create()
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	c.Assert(err, gocheck.IsNil)
	ctx := action.FWContext{
		Params: []interface{}{key, u},
	}
	result, err := addKeyInDatabaseAction.Forward(ctx)
	c.Assert(err, gocheck.IsNil)
	c.Assert(result, gocheck.IsNil) // we do not need it
	u, err = auth.GetUserByEmail(u.Email)
	c.Assert(err, gocheck.IsNil)
	c.Assert(u.Keys, gocheck.DeepEquals, []auth.Key{*key})
}
Esempio n. 8
0
func resetPassword(w http.ResponseWriter, r *http.Request) error {
	email := r.URL.Query().Get(":email")
	token := r.URL.Query().Get("token")
	u, err := auth.GetUserByEmail(email)
	if err != nil {
		if err == auth.ErrUserNotFound {
			return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
		} else if e, ok := err.(*errors.ValidationError); ok {
			return &errors.HTTP{Code: http.StatusBadRequest, Message: e.Error()}
		}
		return err
	}
	if token == "" {
		rec.Log(email, "reset-password-gen-token")
		return u.StartPasswordReset()
	}
	rec.Log(email, "reset-password")
	return u.ResetPassword(token)
}
Esempio n. 9
0
func login(w http.ResponseWriter, r *http.Request) error {
	var pass map[string]string
	err := json.NewDecoder(r.Body).Decode(&pass)
	if err != nil {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: "Invalid JSON"}
	}
	password, ok := pass["password"]
	if !ok {
		msg := "You must provide a password to login"
		return &errors.HTTP{Code: http.StatusBadRequest, Message: msg}
	}
	u, err := auth.GetUserByEmail(r.URL.Query().Get(":email"))
	if err != nil {
		if e, ok := err.(*errors.ValidationError); ok {
			return &errors.HTTP{Code: http.StatusBadRequest, Message: e.Message}
		} else if err == auth.ErrUserNotFound {
			return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
		}
		return err
	}
	rec.Log(u.Email, "login")
	t, err := u.CreateToken(password)
	if err != nil {
		switch err.(type) {
		case *errors.ValidationError:
			return &errors.HTTP{
				Code:    http.StatusBadRequest,
				Message: err.(*errors.ValidationError).Message,
			}
		case auth.AuthenticationFailure:
			return &errors.HTTP{
				Code:    http.StatusUnauthorized,
				Message: err.Error(),
			}
		default:
			return err
		}
	}
	fmt.Fprintf(w, `{"token":"%s"}`, t.Token)
	return nil
}
Esempio n. 10
0
File: app.go Progetto: janqii/tsuru
// Delete deletes an app.
//
// Delete an app is a process composed of four steps:
//
//       1. Destroy the bucket and S3 credentials (if bucket-support is
//       enabled).
//       2. Destroy the app unit using juju
//       3. Unbind all service instances from the app
//       4. Remove the app from the database
func Delete(app *App) error {
	gURL := repository.ServerURL()
	(&gandalf.Client{Endpoint: gURL}).RemoveRepository(app.Name)
	useS3, _ := config.GetBool("bucket-support")
	if useS3 {
		destroyBucket(app)
	}
	if len(app.Units) > 0 {
		Provisioner.Destroy(app)
		app.unbind()
	}
	token := app.Env["TSURU_APP_TOKEN"].Value
	auth.DeleteToken(token)
	if owner, err := auth.GetUserByEmail(app.Owner); err == nil {
		auth.ReleaseApp(owner)
	}
	conn, err := db.Conn()
	if err != nil {
		return err
	}
	defer conn.Close()
	return conn.Apps().Remove(bson.M{"name": app.Name})
}
Esempio n. 11
0
		key := ctx.Params[0].(*auth.Key)
		u := ctx.Params[1].(*auth.User)
		removeKeyFromDatabase(key, u)
	},
}

var addUserToTeamInGandalfAction = action.Action{
	Forward: func(ctx action.FWContext) (action.Result, error) {
		email := ctx.Params[0].(string)
		u := ctx.Params[1].(*auth.User)
		t := ctx.Params[2].(*auth.Team)
		return nil, addUserToTeamInGandalf(email, u, t)
	},
	Backward: func(ctx action.BWContext) {
		email := ctx.Params[0].(string)
		u, err := auth.GetUserByEmail(email)
		if err != nil {
			return
		}
		t := ctx.Params[2].(*auth.Team)
		removeUserFromTeamInGandalf(u, t.Name)
	},
}

var addUserToTeamInDatabaseAction = action.Action{
	Forward: func(ctx action.FWContext) (action.Result, error) {
		email := ctx.Params[0].(string)
		u, err := auth.GetUserByEmail(email)
		if err != nil {
			return nil, err
		}
Esempio n. 12
0
			app = ctx.Params[0].(App)
		case *App:
			app = *ctx.Params[0].(*App)
		default:
			return nil, errors.New("First parameter must be App or *App.")
		}
		var user auth.User
		switch ctx.Params[1].(type) {
		case auth.User:
			user = ctx.Params[1].(auth.User)
		case *auth.User:
			user = *ctx.Params[1].(*auth.User)
		default:
			return nil, errors.New("Third parameter must be auth.User or *auth.User.")
		}
		usr, err := auth.GetUserByEmail(user.Email)
		if err != nil {
			return nil, err
		}
		if err := auth.ReserveApp(usr); err != nil {
			return nil, err
		}
		return map[string]string{"app": app.Name, "user": user.Email}, nil
	},
	Backward: func(ctx action.BWContext) {
		m := ctx.FWResult.(map[string]string)
		if user, err := auth.GetUserByEmail(m["user"]); err == nil {
			auth.ReleaseApp(user)
		}
	},
	MinParams: 2,