Esempio n. 1
0
func GetUserHandler(w http.ResponseWriter, r *http.Request) {
	c := communicator.New(w)
	username := r.FormValue("username")
	sid := r.FormValue("id")

	if sid != "" {
		var id int64
		fmt.Sscanf(sid, "%d", &id)
		fmt.Println(id)

		u, err := models.GetUserByID(id)
		if err != nil {
			c.Fail("Error getting user")
			return
		}

		c.OKWithData("Here is your user: "******"" {
		u, err := models.GetUser("username", username)
		if err != nil {
			c.Fail("Could not get that username")
			return
		}

		c.OKWithData("Here is your user: "******"hello?")
		c := communicator.New(w)
		fid, ok := t.Claims["id"].(float64)
		if !ok {
			c.Fail("Could not get that ID")
			return
		}

		id := int64(fid)

		u, err := models.GetUserByID(id)
		if err != nil {
			c.Fail("Error getting user")
			return
		}

		c.OKWithData("Here is your user", u)

	})(w, r)
}
Esempio n. 2
0
func R(fn func(http.ResponseWriter, *http.Request, *jwt.Token)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ts := r.FormValue("access_token")
		c := communicator.New(w)

		token, err := jwt.Parse(ts, func(t *jwt.Token) (interface{}, error) {
			if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("Unexpected signing method: %v", t.Header["alg"])
			}
			return pkey, nil
		})

		if err != nil {
			c.Fail("You are not using a valid token:" + err.Error())
			return
		}

		if !token.Valid {
			c.Fail("Something obscurely weird happened to your token!")
			return
		}

		fn(w, r, token)
	}
}
Esempio n. 3
0
func CreateWorkshopHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)

	name := r.FormValue("name")
	description := r.FormValue("description")
	explanation := r.FormValue("explanation")

	if name == "" || description == "" || explanation == "" {
		c.Fail("Invalid data")
		return
	}

	vars := mux.Vars(r)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("Unable to get user from token")
		return
	}

	s, _, err := getClassFromString(u, vars["class_id"])
	if err != nil {
		c.Fail("Could not get class info")
		return
	}

	a, err := s.CreateWorkshop(name, description, explanation)
	if err != nil {
		c.Fail("Could not create workshop")
		return
	}

	c.OKWithData("Here is your workshops", a)
}
Esempio n. 4
0
func loginHandler(w http.ResponseWriter, r *http.Request) {
	coms := communicator.New(w)

	username := r.FormValue("username")
	password := r.FormValue("password")

	u, err := models.FetchUser(username)
	if err != nil {
		fmt.Println(err)
		coms.Error("Could not fetch user")
		return
	}

	if !u.Login(password) {
		coms.Error("Incorrect password")
		return
	}

	claims := make(map[string]interface{})
	claims["id"] = u.ID
	claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

	ts, err := restrict.Token(claims)
	if err != nil {
		coms.Fail("Failure signing the token")
		return
	}

	coms.OKWithData("token", ts)
}
Esempio n. 5
0
func CreateClassHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("Unable to get your user")
		return
	}

	name := r.FormValue("name")
	description := r.FormValue("description")

	if name == "" || description == "" {
		c.Fail("Invalide data")
		return
	}

	class, err := u.NewClass(name, description)
	if err != nil {
		c.Fail("Could not create class")
		return
	}

	err = class.SetImage("imgs/home.png")
	if err != nil {
		c.Fail("Could not set home class image")
		return
	}

	c.OKWithData("Here is your class", class)
}
Esempio n. 6
0
func LoginUserHandler(w http.ResponseWriter, r *http.Request) {
	c := communicator.New(w)

	username := r.FormValue("username")
	password := r.FormValue("password")

	u, err := GetUser("username", username)
	if err != nil {
		log.Println(err)
		c.Fail("Could not get user")
		return
	}

	ok := u.Login(password)
	if !ok {
		c.Fail("Incorrect username")
		return
	}

	claims := make(map[string]interface{})
	claims["id"] = u.ID
	claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

	ts, err := restrict.Token(claims)
	if err != nil {
		c.Fail("Failure signing that token!")
		return
	}

	c.OKWithData("Here is your token", ts)
}
Esempio n. 7
0
func GetWorkshopsHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)

	vars := mux.Vars(r)
	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("Unable to get user from token")
		return
	}

	s, _, err := getClassFromString(u, vars["class_id"])
	if err != nil {
		c.Fail("Could not get class info")
		return
	}

	d, err := time.ParseDuration("168h")
	if err != nil {
		c.Fail("could not parse duration")
		return
	}

	tm := time.Now().Add(d)

	as, err := s.Workshops(tm)
	if err != nil {
		c.Fail("Could not get workshop")
		return
	}

	c.OKWithData("Here are your workshops", as)
}
Esempio n. 8
0
func SetClassImageHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)
	vars := mux.Vars(r)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("Could not get user")
		return
	}

	s, class, err := getClassFromString(u, vars["class_id"])
	if err != nil {
		c.Fail("Could not get class")
		return
	}

	if !s.IsAdmin() {
		c.Error("You are not an admin!")
		return
	}

	err = class.SetImage(r.FormValue("image_url"))
	if err != nil {
		c.Fail("Could not set image url")
		return
	}

	c.OK("Done!")
}
Esempio n. 9
0
func RemovePollHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)

	c.OKWithData("Are you removing! I don't know!", removeAnItem)

	removeAnItem = false
}
Esempio n. 10
0
func MassChangeHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("Could not get token")
		return
	}

	amountString := r.FormValue("amount")
	amount, err := strconv.Atoi(amountString)
	if err != nil {
		c.Fail("That is not a valid mass number")
		return
	}

	if amount > lastWeight && queue != (Stock{}) {
		_, err := db.Exec("INSERT INTO pantry (user, brand, category, manufacturer, description) VALUES (?, ?, ?, ?, ?)", u.ID, queue.Brand, queue.Category, queue.Manufacturer, queue.Description)
		if err != nil {
			log.Println(err)
			c.Fail("Kill the pantry")
			return
		}

		log.Println("Added item to queue")

		queue = Stock{}
	} else {
		// make user show poll
	}
}
Esempio n. 11
0
func GetWorkshopHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)
	vars := mux.Vars(r)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("COuld not get user")
		return
	}

	_, class, err := getClassFromString(u, vars["class_id"])
	if err != nil {
		c.Fail("Could not get class info")
		return
	}

	wid, err := strconv.ParseInt(vars["workshop_id"], 10, 64)
	if err != nil {
		c.Fail("Not a valid workshop id")
		return
	}

	work, err := class.Workshop(wid)
	if err != nil {
		c.Fail("Could not get workshop")
		return
	}

	c.OKWithData("Hre is your workshop", work)
}
Esempio n. 12
0
func AllFoodInPantryHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("Could not get token from user")
		return
	}

	st := []Stock{}

	rows, err := db.Query("SELECT id, weight, initial_weight, brand, category, manufacturer, description FROM pantry WHERE user = ?", u.ID)

	for rows.Next() {
		s := Stock{}

		err = rows.Scan(&s.ID, &s.Weight, &s.InitialWeight, &s.Brand, &s.Category, &s.Manufacturer, &s.Description)
		if err != nil {
			log.Println(err)

			c.Fail("Could not get information out of ID")
			return
		}

		st = append(st, s)
	}

	c.OKWithData("food.", st)
}
Esempio n. 13
0
func LoginHandler(w http.ResponseWriter, r *http.Request) {
	c := communicator.New(w)

	username := r.FormValue("username")
	password := r.FormValue("password")

	u, err := models.GetUser("username", username)
	if err != nil {
		c.Fail("Unable to find that user")
		return
	}

	ok, err := u.Login(password)
	if err != nil {
		c.Fail("Authentication error")
	}

	if !ok {
		c.Fail("That was not a matching password")
		return
	}

	claims := make(map[string]interface{})
	claims["id"] = u.ID
	claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

	ts, err := restrict.Token(claims)
	if err != nil {
		c.Fail("Failure signing that token!")
		return
	}

	c.OKWithData("Successfully logged in that user", ts)
}
Esempio n. 14
0
func InfoHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)
	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("Could not get user ID from token")
		return
	}

	c.OKWithData("Here is your user, welcome to the party", u)
}
Esempio n. 15
0
// adds a new data point to relevant statistics
// removes food items that have "ran out of stock"
func ConsumeFoodHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("Could not get user from token")
		return
	}

	idString := r.FormValue("food_item")
	quantityString := r.FormValue("quantity")

	idInt, err := strconv.Atoi(idString)
	if err != nil {
		c.Fail("That id is not int convertable")
		return
	}

	quantityInt, err := strconv.Atoi(quantityString)
	if err != nil {
		c.Fail("That qunaitty is not convertable")
		return
	}

	id := int64(idInt)
	quantity := float64(quantityInt)

	log.Println(quantity) // TODO use quantity

	s := Stock{}

	row := db.QueryRow("SELECT id, user, brand, category, manufacturer, description, weight, initial_weight FROM pantry WHERE id = ? AND user = ?", id, u.ID)
	err = row.Scan(&s.ID, &s.Category, &s.Manufacturer, &s.Description, &s.Weight, &s.InitialWeight)
	if err != nil {
		log.Println(err)
		c.Fail("Could not get that db")
		return
	}

	_, err = db.Exec("UPDATE pantry SET weight = ? AND avail = ? WHERE id = ? AND user = ?", s.Weight-quantity, (s.Weight-quantity) >= 0, s.ID, u.ID)
	if err != nil {
		log.Println(err)
		c.Fail("Could not update pantry")
		return
	}

	if s.Weight-quantity < 2 {
		message := "You are running out of " + s.Brand
		twilio.SendSMS(from, u.Phone, message, "", "")
	}

	c.OK("consumed.")
}
Esempio n. 16
0
func FoodGraphHandler(w http.ResponseWriter, r *http.Request) {
	c := communicator.New(w)
	fg := FoodGraph{
		Measurements: []Graph{
			// ideas: Weight, Eating Frequency, etc
			{Name: "Weight", Points: []float64{90, 89, 87, 87.5}},
			{Name: "Randomo", Points: []float64{22, 35, 44, 25}},
		},
	}

	c.OKWithData("Here is your graph", fg)
}
Esempio n. 17
0
func EditPageHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)
	vars := mux.Vars(r)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("COuld not get user")
		return
	}

	s, class, err := getClassFromString(u, vars["class_id"])
	if err != nil {
		c.Fail("Could not get class info")
		return
	}

	if !s.IsAdmin() {
		c.Error("You are not an admin. You cannot edit this!")
		return
	}

	wid, err := strconv.ParseInt(vars["workshop_id"], 10, 64)
	if err != nil {
		c.Fail("Not a valid workshop id")
		return
	}

	work, err := class.Workshop(wid)
	if err != nil {
		c.Fail("Could not get workshop")
		return
	}

	pid, err := strconv.ParseInt(vars["page_id"], 10, 64)
	if err != nil {
		c.Fail("Coudl not get page id")
		return
	}

	p, err := work.Page(pid)
	if err != nil {
		c.Fail("COuld not get page")
		return
	}

	err = p.Edit(r.FormValue("title"), r.FormValue("contents"))
	if err != nil {
		c.Fail("Could not edit page")
		return
	}

	c.OKWithData("here is your page", p)
}
Esempio n. 18
0
func registerHandler(w http.ResponseWriter, r *http.Request) {
	coms := communicator.New(w)

	username := r.FormValue("username")
	password := r.FormValue("password")
	email := r.FormValue("email")

	u, err := models.NewUser(username, password, email)
	if err != nil {
		coms.Error("Unable to create user")
		return
	}

	coms.OKWithData("user", u)
}
Esempio n. 19
0
func RegisterHandler(w http.ResponseWriter, r *http.Request) {
	c := communicator.New(w)

	username := r.FormValue("username")
	password := r.FormValue("password")
	email := r.FormValue("email")

	u, err := models.RegisterUser(username, password, email)
	if err != nil {
		fmt.Println(err)
		c.Fail("Could not register that user")
		return
	}

	c.OKWithData("Successfully registered that user", u)
}
Esempio n. 20
0
func GetClassesHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("Unable to get your user")
		return
	}

	classes, err := u.Classes()
	if err != nil {
		c.Fail("Unable to get classes")
		return
	}

	c.OKWithData("Here are your classes", classes)
}
Esempio n. 21
0
func GetStudentHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)
	vars := mux.Vars(r)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("Could not get user in token")
		return
	}

	s, _, err := getClassFromString(u, vars["class_id"])
	if err != nil {
		c.Fail("Unable to get that class")
		return
	}

	c.OKWithData("Here is your data", s)
}
Esempio n. 22
0
func EditWorkshopHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)
	vars := mux.Vars(r)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("COuld not get user")
		return
	}

	s, class, err := getClassFromString(u, vars["class_id"])
	if err != nil {
		c.Fail("Could not get class info")
		return
	}

	if !s.IsAdmin() {
		c.Error("You are not an admin. You cannot delete this!")
		return
	}

	wid, err := strconv.ParseInt(vars["workshop_id"], 10, 64)
	if err != nil {
		c.Fail("Not a valid workshop id")
		return
	}

	work, err := class.Workshop(wid)
	if err != nil {
		c.Fail("Could not get workshop")
		return
	}

	err = work.Edit(r.FormValue("name"), r.FormValue("description"), r.FormValue("explanation"))
	if err != nil {
		fmt.Println(err)
		c.Fail("Could not edit workshop")
		return
	}

	c.OK("Edited")
}
Esempio n. 23
0
func RegisterUserHandler(w http.ResponseWriter, r *http.Request) {
	c := communicator.New(w)
	u := User{}

	username := r.FormValue("username")
	password := r.FormValue("password")
	phone := r.FormValue("phone")

	if username == "" || password == "" || phone == "" {
		c.Fail("Incorrect user input")
		return
	}

	u, err := GetUser("username", username)
	if err == nil {
		c.Fail("That user already exists")
		return
	}

	u = User{
		Username: username,
		Password: password,
		Phone:    phone,
	}

	res, err := db.Exec("INSERT INTO users (username, password, phone) VALUES (?, ?, ?)", u.Username, u.Password, u.Phone)
	if err != nil {
		c.Fail("Could not insert user")
		return
	}

	id, err := res.LastInsertId()
	if err != nil {
		c.Fail("Could not get insert ID")
		return
	}

	u.ID = id

	c.OKWithData("Here is your user", u)
}
Esempio n. 24
0
func DeleteWorkshopHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)
	vars := mux.Vars(r)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("COuld not get user")
		return
	}

	s, class, err := getClassFromString(u, vars["class_id"])
	if err != nil {
		c.Fail("Could not get class info")
		return
	}

	if !s.IsAdmin() {
		c.Error("You are not an admin. You cannot delete this!")
		return
	}

	wid, err := strconv.ParseInt(vars["workshop_id"], 10, 64)
	if err != nil {
		c.Fail("Not a valid workshop id")
		return
	}

	work, err := class.Workshop(wid)
	if err != nil {
		c.Fail("Could not get workshop")
		return
	}

	err = work.Delete()
	if err != nil {
		c.Fail("Could not delete workshop")
		return
	}

	c.OK("Deleted successfully")
}
Esempio n. 25
0
func AddItemToQueueHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)

	upc := r.FormValue("upc")

	upcReq := UPCRequest{
		Authentication: "Jad19r2OAfrNHpZH2BcuOZQUXDTLhcrS",
		Method:         "FetchProductByUPC",
		Parameters:     map[string]string{"upc": upc},
	}

	jsonStr, err := json.Marshal(upcReq)
	if err != nil {
		c.Fail("COuld not marshall req")
		return
	}

	url := "http://api.simpleupc.com/v1.php"

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", "application/json")

	cli := http.Client{}
	resp, err := cli.Do(req)
	upcResp := UPCResponse{}

	err = json.NewDecoder(resp.Body).Decode(&upcResp)
	if err != nil {
		c.Fail("Could not decode JSON")
		return
	}

	if !upcResp.Success {
		c.Fail("You what is up you failed!")
		return
	}

	queue = upcResp.Result

	c.OK("everything is fine, whatsit is in the queuue")
}
Esempio n. 26
0
func CreateWorkshopPageHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)
	vars := mux.Vars(r)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("COuld not get user")
		return
	}

	_, class, err := getClassFromString(u, vars["class_id"])
	if err != nil {
		c.Fail("Could not get class info")
		return
	}

	wid, err := strconv.ParseInt(vars["workshop_id"], 10, 64)
	if err != nil {
		c.Fail("Not a valid workshop id")
		return
	}

	work, err := class.Workshop(wid)
	if err != nil {
		c.Fail("Could not get workshop")
		return
	}

	title := r.FormValue("title")
	content := r.FormValue("content")

	p, err := work.CreatePage(title, content)
	if err != nil {
		c.Fail("Could not create page")
		return
	}

	c.OKWithData("Here is your page", p)
}
Esempio n. 27
0
func AddUserToClassHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)
	vars := mux.Vars(r)

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("COuld not get user from supplied token")
		return
	}

	username := r.FormValue("user")

	inv, err := models.GetUser("username", username)
	if err != nil {
		c.Fail("Could not get user")
		return
	}

	s, class, err := getClassFromString(u, vars["class_id"])
	if err != nil {
		c.Fail("Could not get class")
		return
	}

	if !s.IsAdmin() {
		c.Fail("User is not admin")
		return
	}

	_, err = class.Invite(inv)
	if err != nil {
		c.Fail("Error inviting user")
		return
	}

	c.OK("Invited user")
}
Esempio n. 28
0
func messagesHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	coms := communicator.New(w)

	vars := mux.Vars(r)
	channel := vars["channel"]
	host := vars["host"]

	channelKey := host + "/#" + channel

	pageString := r.FormValue("page")
	page, err := strconv.ParseInt(pageString, 10, 64)
	if err != nil {
		coms.Fail("Could not parse page as a number")
		return
	}

	msgs, err := models.Messages(channelKey, page)
	if err != nil {
		coms.Fail("Could not fetch messages")
		return
	}

	coms.OKWithData("Here are your messages", msgs)
}
Esempio n. 29
0
// Pass in UPC number of new food
// * Fetch food info
// * Cache
func RegisterFoodHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
	c := communicator.New(w)
	weightString := r.FormValue("weight")

	weightInt, err := strconv.Atoi(weightString)
	if err != nil {
		c.Fail("Could not convert weight")
		return
	}

	weight := float64(weightInt)

	s := Stock{}

	u, err := getUserFromToken(t)
	if err != nil {
		c.Fail("Could not get user from token")
		return
	}

	log.Println(u, s)

	upc := r.FormValue("upc") // send upc to nutritionix

	upcReq := UPCRequest{
		Authentication: "Jad19r2OAfrNHpZH2BcuOZQUXDTLhcrS",
		Method:         "FetchProductByUPC",
		Parameters:     map[string]string{"upc": upc},
	}

	jsonStr, err := json.Marshal(upcReq)
	if err != nil {
		c.Fail("COuld not marshall req")
		return
	}

	url := "http://api.simpleupc.com/v1.php"

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", "application/json")

	cli := http.Client{}
	resp, err := cli.Do(req)
	upcResp := UPCResponse{}

	err = json.NewDecoder(resp.Body).Decode(&upcResp)
	if err != nil {
		c.Fail("Could not decode JSON")
		return
	}

	if !upcResp.Success {
		c.Fail("You what is up you failed!")
		return
	}

	log.Println(upcResp.Result)
	s = upcResp.Result

	res, err := db.Exec("INSERT INTO pantry (user, brand, category, manufacturer, description, weight, initial_weight) VALUES (?, ?, ?, ?, ?, ?, ?)", u.ID, s.Brand, s.Category, s.Manufacturer, s.Description, weight, weight)
	if err != nil {
		log.Println(err)
		c.Fail("Kill the pantry")
		return
	}

	id, err := res.LastInsertId()
	if err != nil {
		c.Fail("Could not get last insert id")
		return
	}

	s.ID = id
	s.Weight = weight

	c.OKWithData("Here is your res", s)
}