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
}
Exemple #2
0
func (tr *TaskRouter) Register(r martini.Router) {
	r.Get("", tr.GetAllTasks)
	r.Post("", tr.CreateTask)
	r.Get("/:id", tr.GetTask)
	r.Put("/:id", tr.CreateTask)
	r.Delete("/:id", tr.CancelTask)
}
func (lr *LocationRouter) Register(r martini.Router) {

	r.Get("/calibration/scores", lr.GetCalibrateScores)
	r.Get("/calibration/device", lr.GetCalibrateDevice)
	r.Get("/calibration/progress", lr.GetCalibrationProgress)

	r.Post("/thing", lr.PostCreateThing)

}
Exemple #4
0
func (lr *RoomRouter) Register(r martini.Router) {

	r.Get("", lr.GetAll)
	r.Post("", lr.PostNewRoom)
	r.Get("/:id", lr.GetRoom)
	r.Delete("/:id", lr.DeleteRoom)
	r.Put("/:id", lr.UpdateRoom)
	// r.Get("/:id/things", lr.GetThings) Not sure if this was used
	r.Put("/:id/calibrate", lr.PutCalibrateRoom)
	r.Put("/:id/apps/:appName", lr.PutAppRoomMessage)

}
Exemple #5
0
func attachAPI(api martini.Router) {
	api.Get("/user", getCurrentUser)
	api.Get("/users", getUsers)
	api.Post("/users", newUser)

	api.Get("/users/:name", getUser)
	//api.Put("/users/:name", updateUser)

	api.Get("/users/:name/projects", getProjects)
	//api.Post("/users/:name/projects", newProject)

	//apiGets.HandleFunc("/projects", getProjects)
}
func (us UserService) Register(router martini.Router) {
	utils.Log.Debug("Registering UserService!")

	router.Group("/users", func(rtr martini.Router) {
		rtr.Post("", PreventReauth, binding.Bind(models.User{}), us.Create)
		rtr.Post("/update", EnsureAuth, binding.Bind(models.User{}), us.Update)
	})

	router.Get("/signout", us.SignOut)
	router.Get("/signup", PreventReauth, us.SignUp)
	router.Get("/signin", PreventReauth, binding.Bind(models.User{}), us.SignIn)
	router.Post("/signin", PreventReauth, binding.Bind(models.User{}), us.Authenticate)
	router.Get("/dashboard", EnsureAuth, us.Dashboard)
	router.Get("/settings", EnsureAuth, us.Edit)
	router.Get("/settings/:category", EnsureAuth, us.Edit)
	router.Get("/wakatime/sync", EnsureAuth, us.SyncHeartbeats)
}
Exemple #7
0
func configureRoutes(router martini.Router) {
	// 404 handler
	router.NotFound(func(render render.Render) {
		render.Redirect("/404")
	})

	// Common Routes
	router.Get("/", controllers.Home)
	router.Get("/404", controllers.NotFound)
	router.Get("/500", controllers.InternalServerError)

	// Player Routes
	router.Get("/players", controllers.GetPlayers)
	router.Get("/player/new", controllers.GetNewPlayer)
	router.Post("/player/new", binding.Form(controllers.PlayerData{}), controllers.CreatePlayer)
	router.Get("/player/:id", controllers.GetPlayerById)
	router.Post("/player/:id", binding.Form(controllers.PlayerData{}), binding.Form(controllers.OriginalData{}), controllers.ModifyPlayer)

	// Game Routes
	router.Get("/games", controllers.GetGames)
	router.Get("/game/new", controllers.GetNewGame)
	router.Post("/game/new", binding.Form(controllers.GameData{}), controllers.CreateGame)
	router.Get("/game/:id", controllers.GetGameById)
}
Exemple #8
0
func (ws WebhookService) Register(router martini.Router) {
	router.Post("/webhook/:git_service", ws.Handle)
}
Exemple #9
0
func SetupCommentRoutes(r martini.Router) {
	r.Get("/comments", ListComments)
	r.Get("/todo/:id/comments", ListCommentsByTodo)
	r.Post("/comments", binding.Json(Comment{}), CreateComment)
}
Exemple #10
0
func SetupTodoRoutes(r martini.Router) {
	r.Get("/todos", ListTodos)
	r.Post("/todos", binding.Json(Todo{}), CreateTodo)
	r.Put("/todos", binding.Json(Todo{}), UpdateTodo)
}
Exemple #11
0
// BindRoutes binds API routes.
func BindRoutes(r martini.Router) {

	r.NotFound(func(req *http.Request, r render.Render) {
		r.JSON(http.StatusNotFound, []string{"The requested url does not exists."})
	})

	r.Get("/api/status", Status)

	// Registration
	r.Group("/api", func(r martini.Router) {
		r.Group("/accounts", func(r martini.Router) {
			r.Post("/register", binding.Bind(accounts.RegisterViewModel{}), NotificatorHandler(), accounts.Register)
		})
	}, GatekeeperRouteHandler())

	// DASHBOARD GATEKEEPER
	r.Group("/api", func(r martini.Router) {
		r.Group("/auth", func(r martini.Router) {
			r.Post("/password", binding.Bind(auth.PasswordRequest{}), auth.Password)
		})
	}, GatekeeperRouteHandler(), AccountScopeHandler(), RepositoryScopeHandler())

	//ADMIN
	r.Group("/api", func(r martini.Router) {
		r.Get("/accounts", accounts.Index)
		r.Post("/accounts", binding.Bind(accounts.AccountViewModel{}), accounts.Post)
		r.Delete("/:id", accounts.Delete)
	}, AdminRouteHandler())

	//Owner / Manager
	r.Group("/api", func(r martini.Router) {
		r.Group("/accounts", func(r martini.Router) {
			r.Get("/:id", accounts.Get)
			r.Put("/:id", binding.Bind(accounts.AccountViewModel{}), accounts.Put)
		})

		r.Get("/devices", devices.Index)
		r.Post("/devices", binding.Bind(devices.DeviceViewModel{}), devices.Post)
		r.Group("/devices", func(r martini.Router) {
			r.Get("/:id", devices.Get)
			r.Put("/:id", binding.Bind(devices.DeviceViewModel{}), devices.Put)
			r.Post("/register", binding.Bind(devices.DeviceViewModel{}), devices.Post)
			r.Delete("/:id", devices.Delete)
		})

		r.Get("/doors", doors.Index)
		r.Post("/doors", binding.Bind(doors.DoorViewModel{}), doors.Post)
		r.Group("/doors", func(r martini.Router) {
			r.Get("/:id", doors.Get)
			r.Put("/:id", binding.Bind(doors.DoorViewModel{}), doors.Put)
			r.Delete("/:id", doors.Delete)
		})

		r.Post("/people", binding.Bind(people.PersonViewModel{}), people.Post)
		r.Group("/people", func(r martini.Router) {
			r.Post("/sync", BridgeHandler(), people.Sync)
			r.Delete("/:id", people.Delete)
		})

	}, AccountScopeHandler(), RepositoryScopeHandler(), SecuredRouteHandler(), ManagerRestrictedRouteHandler())

	//Account
	r.Group("/api", func(r martini.Router) {
		r.Group("/accounts", func(r martini.Router) {
			r.Get("/:id", accounts.Get)
		})

		r.Post("/notifications", NotificatorHandler(), binding.Bind(notifications.ViewModel{}), notifications.Notify)

		r.Get("/people", people.Index)
		r.Group("/people", func(r martini.Router) {
			r.Get("/:id", people.Get)
			r.Put("/:id", binding.Bind(people.PersonViewModel{}), people.Put)
		})

	}, AccountScopeHandler(), RepositoryScopeHandler(), SecuredRouteHandler())
}
func (this *EurekaRequestPost) SetRoutes(r martini.Router) {
	r.Post("/apps/:appId", this.requestRegisterApp)
}
Exemple #13
0
func MockRouter(r martini.Router) {
	r.Get("/**", GetMock)
	r.Post("/**", GetMock)
}
Exemple #14
0
func PresetRouter(r martini.Router) {
	r.Get("/", GetPreset)
	r.Post("/", CreatePreset)
}
func EnsureWorkWithKeys(r martini.Router, qs *quests.QuestStorage, db *d.MainDb) martini.Router {
	//todo add group and refactor normal
	r.Post("/load/up", w.LoginRequired, w.AutHandler.CheckIncludeAnyRole(MANAGER), func(render render.Render, request *http.Request) {
		xlsFileReg := regexp.MustCompile(".+\\.xlsx?")
		file, header, err := request.FormFile("file")
		if err != nil {
			render.HTML(200, "new_keys", w.AddCurrentUser(GetKeysInfo(fmt.Sprintf("Ошибка загрузки файлика: %v", err), qs), request, db))
			return
		}
		log.Printf("Form file information: file: %+v \nheader:%v, %v\nerr:%v", file, header.Filename, header.Header, err)
		defer file.Close()

		data, err := ioutil.ReadAll(file)
		if err != nil {
			render.HTML(200, "new_keys", w.AddCurrentUser(GetKeysInfo(fmt.Sprintf("Ошибка загрузки файлика: %v", err), qs), request, db))
			return
		}

		if xlsFileReg.MatchString(header.Filename) {
			xlFile, err := xlsx.OpenBinary(data)
			log.Printf("file: %+v, err: %v", xlFile, err)
			if err != nil || xlFile == nil {
				render.HTML(200, "quests/new_keys", w.AddCurrentUser(GetKeysInfo(fmt.Sprintf("Ошибка обработки файлика: %v", err), qs), request, db))
				return
			}
			skip_rows, _ := strconv.Atoi(request.FormValue("skip-rows"))
			skip_cols, _ := strconv.Atoi(request.FormValue("skip-cols"))

			parse_res, _ := w.ParseExportXlsx(xlFile, skip_rows, skip_cols)
			for _, prel := range parse_res {
				qs.AddStep(prel[0], prel[1], prel[2])
			}
		} else {
			render.HTML(200, "new_keys", w.AddCurrentUser(GetKeysInfo("Файл имеет не то расширение :(", qs), request, db))
		}

		render.Redirect("/new_keys")
	})

	r.Get("/new_keys", w.LoginRequired, w.AutHandler.CheckIncludeAnyRole(MANAGER), func(r render.Render, req *http.Request) {
		log.Printf("CONSOLE WEB will show keys")
		r.HTML(200, "new_keys", w.AddCurrentUser(GetKeysInfo("", qs), req, db), render.HTMLOptions{Layout: "base"})
	})

	r.Post("/add_key", w.LoginRequired, w.AutHandler.CheckIncludeAnyRole(MANAGER), func(user auth.User, render render.Render, request *http.Request) {
		start_key := request.FormValue("start-key")
		next_key := request.FormValue("next-key")
		description := request.FormValue("description")

		log.Printf("CONSOLE WEB add key %s -> %s -> %s", start_key, description, next_key)
		if start_key != "" && description != "" {
			key, err := qs.AddStep(start_key, description, next_key)
			log.Printf("QW is error? %v key: %v", err, key)
			render.Redirect("/new_keys")
		} else {
			render.HTML(200, "console/new_keys", w.AddCurrentUser(GetKeysInfo("Невалидные значения ключа или ответа", qs), request, db))
		}
	})

	r.Post("/delete_key/:key", w.LoginRequired, w.AutHandler.CheckIncludeAnyRole(MANAGER), func(params martini.Params, render render.Render) {
		key := params["key"]
		err := qs.DeleteStep(key)
		log.Printf("CONSOLE WEB will delete %v (%v)", key, err)
		render.Redirect("/new_keys")
	})

	r.Post("/update_key/:key", w.LoginRequired, w.AutHandler.CheckIncludeAnyRole(MANAGER), func(params martini.Params, render render.Render, request *http.Request) {
		key_id := params["key"]

		start_key := request.FormValue("start-key")
		next_key := request.FormValue("next-key")
		description := request.FormValue("description")

		err := qs.UpdateStep(key_id, start_key, description, next_key)
		log.Printf("CONSOLE WEB was update key %s %s %s %s\n err? %v", key_id, start_key, description, next_key, err)
		render.Redirect("/new_keys")
	})

	r.Get("/delete_key_all", w.LoginRequired, w.AutHandler.CheckIncludeAnyRole(MANAGER), func(render render.Render) {
		log.Printf("CONSOLE WEB was delete all keys")
		qs.Steps.RemoveAll(bson.M{})
		render.Redirect("/new_keys")
	})

	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
}