func EnsureAuth(r martini.Router, mainDb *d.MainDb) martini.Router {

	r.Get("/", func(r render.Render, prms martini.Params, req *http.Request) {
		flashMessage, fType := flash.GetMessage()
		query := req.URL.Query()
		result := map[string]interface{}{
			fmt.Sprintf("flash_%v", fType): flashMessage,
			"from": query.Get("from"),
		}

		r.HTML(200, "login", AddCurrentUser(result, req, mainDb), render.HTMLOptions{Layout: "base"})
	})

	r.Post("/", binding.Bind(user{}), func(postedUser user, r render.Render, req *http.Request, w http.ResponseWriter) {
		userData, err := mainDb.Users.LoginUser(postedUser.LoginName, postedUser.Password)
		if err != nil {
			log.Printf("AUTH user %+v not found: %v", postedUser, err)
			flash.SetMessage("К сожалению, пользователь с такими данными не найден.", "error")
			r.Redirect(AUTH_URL)
			return
		} else {
			log.Printf("AUTH found user data: %v, %v, %v", userData.UserId, userData.UserName, userData.Auth)
		}
		user := NewUser(userData)
		StartAuthSession(user, w)
		redirect := req.URL.Query().Get(REDIRECT_PARAM)
		if redirect == "" {
			redirect = DefaultUrlMap.GetDefaultUrl(user.BelongsToCompany())
		}
		http.Redirect(w, req, redirect, 302)
	})
	return r
}
func EnsureWorkWithUsers(r martini.Router, db *d.MainDb) martini.Router {
	r.Group("/users", func(r martini.Router) {
		r.Get("", w.LoginRequired, w.AutHandler.CheckIncludeAnyRole(MANAGER), func(r render.Render, req *http.Request) {
			r.HTML(200, "users", w.AddCurrentUser(GetUsersInfo("", db), req, db), render.HTMLOptions{Layout: "base"})
		})

		r.Post("/add", w.LoginRequired, w.AutHandler.CheckIncludeAnyRole(MANAGER), func(r render.Render, request *http.Request) {
			u_id := strings.TrimSpace(request.FormValue("user-id"))
			u_name := strings.TrimSpace(request.FormValue("user-name"))
			u_phone := request.FormValue("user-phone")
			u_email := request.FormValue("user-e-mail")
			u_role := strings.TrimSpace(request.FormValue("user-role"))
			u_pwd := request.FormValue("user-pwd")
			u_read_rights := strings.Fields(request.FormValue("read-rights"))
			u_write_rights := strings.Fields(request.FormValue("write-rights"))
			u_belongs_to := strings.TrimSpace(request.FormValue("belongs-to"))

			log.Printf("CONSOLE WEB add user [%s]  '%s' +%s %s |%v| {%s}", u_id, u_name, u_phone, u_email, u_role, u_pwd)
			if u_name != "" && u_id != "" {
				db.Users.AddOrUpdateUserObject(d.UserData{
					UserId:      u_id,
					UserName:    u_name,
					Email:       u_email,
					Phone:       u_phone,
					Role:        u_role,
					Password:    u.PHash(u_pwd),
					LastUpdate:  time.Now(),
					ReadRights:  u_read_rights,
					WriteRights: u_write_rights,
					BelongsTo:   u_belongs_to,
				})
				r.Redirect("/users")
			} else {
				r.HTML(200,
					"users",
					w.AddCurrentUser(GetUsersInfo("Невалидные значения имени и (или) идентификатора добавляемого пользователя", db), request, db),
					render.HTMLOptions{Layout: "base"})
			}
		})

		r.Post("/delete/:id", w.LoginRequired, w.AutHandler.CheckIncludeAnyRole(MANAGER), func(params martini.Params, render render.Render) {
			uid := params["id"]
			err := db.Users.UsersCollection.Remove(bson.M{"user_id": uid})
			log.Printf("CONSOLE WEB will delete user %v (%v)", uid, err)
			render.Redirect("/users")
		})

		r.Post("/update/:id", w.LoginRequired, w.AutHandler.CheckIncludeAnyRole(MANAGER), func(params martini.Params, render render.Render, request *http.Request) {
			u_id := params["id"]
			u_name := strings.TrimSpace(request.FormValue("user-name"))
			u_phone := request.FormValue("user-phone")
			u_email := request.FormValue("user-e-mail")
			u_role := request.FormValue("user-role")
			u_pwd := request.FormValue("user-pwd")
			u_read_rights := strings.Fields(request.FormValue("read-rights"))
			u_write_rights := strings.Fields(request.FormValue("write-rights"))
			u_belongs_to := strings.TrimSpace(request.FormValue("belongs-to"))

			upd := bson.M{}
			if u_name != "" {
				upd["user_name"] = u_name
			}
			if u_email != "" {
				upd["email"] = u_email
			}
			if u_phone != "" {
				upd["phone"] = u_phone
			}
			if u_role != "" {
				upd["role"] = u_role
			}
			if u_pwd != "" {
				upd["password"] = u.PHash(u_pwd)
			}
			if len(u_read_rights) > 0 {
				upd["read_rights"] = u_read_rights
			}
			if len(u_write_rights) > 0 {
				upd["write_rights"] = u_write_rights
			}
			if u_belongs_to != "" {
				upd["belongs_to"] = u_belongs_to
			}
			db.Users.UsersCollection.Update(bson.M{"user_id": u_id}, bson.M{"$set": upd})
			log.Printf("CONSOLE WEB update user [%s]  '%s' +%s %s |%v| {%v}", u_id, u_name, u_phone, u_email, u_role, u_pwd)
			render.Redirect("/users")
		})
	})
	return r
}