Пример #1
0
func (app *App) handleUserModels(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		u, ok := app.getUser(r)
		if !ok {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		tx, err := app.db.Begin()
		if err != nil {
			app.dbError(w, r, err)
			return
		}
		defer tx.Rollback()
		models, err := db.UserModels(tx, u.Name)

		if err != nil {
			app.dbError(w, r, err)
			return
		}
		app.writeJson(w, models)
	default:
		http.Error(w, "I only respond to GETs", http.StatusNotImplemented)
	}
}
Пример #2
0
func (app *App) handleAllUserModels(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		_, ok := app.getUser(r)
		if !ok {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}
		// TODO
		// if u.Admin == false {
		// 	http.Error(w, "Unauthorized", http.StatusUnauthorized)
		// 	return
		// }

		tx, err := app.db.Begin()
		if err != nil {
			app.dbError(w, r, err)
			return
		}
		defer tx.Rollback()

		allUsers, err := db.AllUsers(tx)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		allModels := []db.Model{}

		for _, user := range allUsers {

			models, err := db.UserModels(tx, user.Name)
			for i, _ := range models {
				models[i].Owner = user.Name
			}

			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			allModels = append(allModels, models...)
		}

		if err != nil {
			app.dbError(w, r, err)
			return
		}
		app.writeJson(w, allModels)
	default:
		http.Error(w, "I only respond to GETs", http.StatusNotImplemented)
	}
}