package main import ( "encoding/json" "errors" "fmt" "net/http" "strconv" "time" "github.com/julienschmidt/httprouter" ) func init() { router.GET("/api/surveys", apiAuthHandler( func(u *User, _ httprouter.Params, _ []byte) HTTPResponse { if u == nil { return formatApiResponse(getSurveys(fmt.Sprintf("WHERE shown = TRUE AND NOW() > start_availability AND promo = %d ORDER BY start_availability ASC", currentPromo))) } else if u.IsAdmin { return formatApiResponse(getSurveys("ORDER BY promo DESC, start_availability ASC")) } else { return formatApiResponse(getSurveys(fmt.Sprintf("WHERE shown = TRUE AND promo = %d ORDER BY start_availability ASC", u.Promo))) } })) router.POST("/api/surveys", apiHandler(func(_ httprouter.Params, body []byte) HTTPResponse { var new Survey if err := json.Unmarshal(body, &new); err != nil { return APIErrorResponse{err: err} } if new.Promo == 0 { new.Promo = currentPromo } return formatApiResponse(NewSurvey(new.Title, new.Promo, new.Shown, new.StartAvailability, new.EndAvailability)) }, adminRestricted)) router.GET("/api/surveys/:sid", apiAuthHandler(surveyAuthHandler( func(s Survey, u *User, _ []byte) HTTPResponse { if (s.Promo == u.Promo && s.Shown) || (u != nil && u.IsAdmin) { return APIResponse{s} } else { return APIErrorResponse{ status: http.StatusForbidden, err: errors.New("Not accessible"), } } }))) router.PUT("/api/surveys/:sid", apiHandler(surveyHandler(func(current Survey, body []byte) HTTPResponse { var new Survey if err := json.Unmarshal(body, &new); err != nil { return APIErrorResponse{err: err} } new.Id = current.Id return formatApiResponse(new.Update()) }), adminRestricted)) router.DELETE("/api/surveys/:sid", apiHandler(surveyHandler( func(s Survey, _ []byte) HTTPResponse { return formatApiResponse(s.Delete()) }), adminRestricted)) router.GET("/api/surveys/:sid/score", apiAuthHandler(surveyAuthHandler( func(s Survey, u *User, _ []byte) HTTPResponse { if (s.Promo == u.Promo && s.Shown) || (u != nil && u.IsAdmin) { if score, err := s.GetScore(u); err != nil { return APIErrorResponse{err: err} } else if score == nil { return APIResponse{map[string]string{"score": "N/A"}} } else { return APIResponse{map[string]float64{"score": *score}} } } else { return APIErrorResponse{ status: http.StatusForbidden, err: errors.New("Not accessible"), } } }), loggedUser)) router.GET("/api/users/:uid/surveys/:sid/score", apiAuthHandler(func(uauth *User, ps httprouter.Params, body []byte) HTTPResponse { return surveyAuthHandler(func(s Survey, uauth *User, _ []byte) HTTPResponse { return userHandler(func(u User, _ []byte) HTTPResponse { if uauth != nil && ((s.Promo == u.Promo && s.Shown && u.Id == uauth.Id) || uauth.IsAdmin) { if score, err := s.GetScore(&u); err != nil { return APIErrorResponse{err: err} } else if score == nil { return APIResponse{map[string]string{"score": "N/A"}} } else { return APIResponse{map[string]float64{"score": *score}} } } else { return APIErrorResponse{ status: http.StatusForbidden, err: errors.New("Not accessible"), } } })(ps, body) })(uauth, ps, body) }, loggedUser)) } func surveyHandler(f func(Survey, []byte) HTTPResponse) func(httprouter.Params, []byte) HTTPResponse { return func(ps httprouter.Params, body []byte) HTTPResponse { if sid, err := strconv.Atoi(string(ps.ByName("sid"))); err != nil { return APIErrorResponse{err: err} } else if survey, err := getSurvey(sid); err != nil { return APIErrorResponse{err: err} } else { return f(survey, body) } } } func surveyAuthHandler(f func(Survey, *User, []byte) HTTPResponse) func(*User, httprouter.Params, []byte) HTTPResponse { return func(u *User, ps httprouter.Params, body []byte) HTTPResponse { if sid, err := strconv.Atoi(string(ps.ByName("sid"))); err != nil { return APIErrorResponse{err: err} } else if survey, err := getSurvey(sid); err != nil { return APIErrorResponse{err: err} } else { return f(survey, u, body) } } } type Survey struct { Id int64 `json:"id"` Title string `json:"title"` Promo uint `json:"promo"` Shown bool `json:"shown"` Corrected bool `json:"corrected"` StartAvailability time.Time `json:"start_availability"` EndAvailability time.Time `json:"end_availability"` } func getSurveys(cnd string, param ...interface{}) (surveys []Survey, err error) { if rows, errr := DBQuery("SELECT id_survey, title, promo, shown, corrected, start_availability, end_availability FROM surveys "+cnd, param...); errr != nil { return nil, errr } else { defer rows.Close() for rows.Next() { var s Survey if err = rows.Scan(&s.Id, &s.Title, &s.Promo, &s.Shown, &s.Corrected, &s.StartAvailability, &s.EndAvailability); err != nil { return } surveys = append(surveys, s) } if err = rows.Err(); err != nil { return } return } } func getSurvey(id int) (s Survey, err error) { err = DBQueryRow("SELECT id_survey, title, promo, shown, corrected, start_availability, end_availability FROM surveys WHERE id_survey=?", id).Scan(&s.Id, &s.Title, &s.Promo, &s.Shown, &s.Corrected, &s.StartAvailability, &s.EndAvailability) return } func NewSurvey(title string, promo uint, shown bool, startAvailability time.Time, endAvailability time.Time) (Survey, error) { if res, err := DBExec("INSERT INTO surveys (title, promo, shown, start_availability, end_availability) VALUES (?, ?, ?, ?, ?)", title, promo, shown, startAvailability, endAvailability); err != nil { return Survey{}, err } else if sid, err := res.LastInsertId(); err != nil { return Survey{}, err } else { return Survey{sid, title, promo, shown, false, startAvailability, endAvailability}, nil } } func (s Survey) GetScore(u *User) (score *float64, err error) { err = DBQueryRow("SELECT SUM(score)/COUNT(*) FROM student_scores WHERE id_survey=? AND id_user=?", s.Id, u.Id).Scan(&score) if score != nil { *score = *score / 5.0 } return } func (s Survey) GetScores() (scores map[int64]*float64, err error) { if rows, errr := DBQuery("SELECT id_user, SUM(score)/COUNT(*) FROM student_scores WHERE id_survey=? GROUP BY id_user", s.Id); err != nil { return nil, errr } else { defer rows.Close() scores = map[int64]*float64{} for rows.Next() { var id_user int64 var score *float64 if err = rows.Scan(&id_user, &score); err != nil { return } scores[id_user] = score } if err = rows.Err(); err != nil { return } } return } func (s Survey) Update() (int64, error) { if res, err := DBExec("UPDATE surveys SET title = ?, promo = ?, shown = ?, corrected = ?, start_availability = ?, end_availability = ? WHERE id_survey = ?", s.Title, s.Promo, s.Shown, s.Corrected, s.StartAvailability, s.EndAvailability, s.Id); err != nil { return 0, err } else if nb, err := res.RowsAffected(); err != nil { return 0, err } else { return nb, err } } func (s Survey) Delete() (int64, error) { if res, err := DBExec("DELETE FROM surveys WHERE id_survey = ?", s.Id); err != nil { return 0, err } else if nb, err := res.RowsAffected(); err != nil { return 0, err } else { return nb, err } } func ClearSurveys() (int64, error) { if res, err := DBExec("DELETE FROM surveys"); err != nil { return 0, err } else if nb, err := res.RowsAffected(); err != nil { return 0, err } else { return nb, err } }