Use gin-gonic instead of httprouter
This commit is contained in:
parent
7c719d9fd5
commit
a203cdc36a
22 changed files with 1631 additions and 1355 deletions
255
surveys.go
255
surveys.go
|
|
@ -1,77 +1,142 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var (
|
||||
_score_cache = map[int64]map[int64]*float64{}
|
||||
)
|
||||
|
||||
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 OR direct IS NOT NULL) 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 {
|
||||
surveys, err := getSurveys(fmt.Sprintf("WHERE (shown = TRUE OR direct IS NOT NULL) AND promo = %d ORDER BY start_availability ASC", u.Promo))
|
||||
if err != nil {
|
||||
return APIErrorResponse{err: err}
|
||||
}
|
||||
func declareAPISurveysRoutes(router *gin.RouterGroup) {
|
||||
router.GET("/surveys", func(c *gin.Context) {
|
||||
u := c.MustGet("LoggedUser").(*User)
|
||||
|
||||
var response []Survey
|
||||
var response []*Survey
|
||||
var err error
|
||||
if u == nil {
|
||||
response, err = getSurveys(fmt.Sprintf("WHERE (shown = TRUE OR direct IS NOT NULL) AND NOW() > start_availability AND promo = %d ORDER BY start_availability ASC", currentPromo))
|
||||
} else if u.IsAdmin {
|
||||
response, err = getSurveys("ORDER BY promo DESC, start_availability ASC")
|
||||
} else {
|
||||
var surveys []*Survey
|
||||
surveys, err = getSurveys(fmt.Sprintf("WHERE (shown = TRUE OR direct IS NOT NULL) AND promo = %d ORDER BY start_availability ASC", u.Promo))
|
||||
if err == nil {
|
||||
for _, s := range surveys {
|
||||
if s.Group == "" || strings.Contains(u.Groups, ","+s.Group+",") {
|
||||
s.Group = ""
|
||||
response = append(response, s)
|
||||
}
|
||||
}
|
||||
|
||||
return formatApiResponse(response, nil)
|
||||
}
|
||||
}))
|
||||
router.POST("/api/surveys", apiHandler(func(_ httprouter.Params, body []byte) HTTPResponse {
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": "Impossible de lister les questionnaires. Veuillez réessayer dans quelques instants"})
|
||||
log.Printf("Unable to list surveys: %s", err.Error())
|
||||
} else {
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
})
|
||||
|
||||
surveysRoutes := router.Group("/surveys/:sid")
|
||||
surveysRoutes.Use(surveyHandler)
|
||||
|
||||
surveysRoutes.GET("", func(c *gin.Context) {
|
||||
u := c.MustGet("LoggedUser").(*User)
|
||||
|
||||
if u == nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"errmsg": "Veuillez vous connecter pour accéder à cette page."})
|
||||
return
|
||||
}
|
||||
|
||||
s := c.MustGet("survey").(*Survey)
|
||||
|
||||
if (s.Promo == u.Promo && (s.Group == "" || strings.Contains(u.Groups, ","+s.Group+",") && s.Shown)) || u.IsAdmin {
|
||||
c.JSON(http.StatusOK, s)
|
||||
} else {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"errmsg": "Not accessible"})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func declareAPIAuthSurveysRoutes(router *gin.RouterGroup) {
|
||||
surveysRoutes := router.Group("/surveys/:sid")
|
||||
surveysRoutes.Use(surveyHandler)
|
||||
|
||||
surveysRoutes.GET("/score", func(c *gin.Context) {
|
||||
var u *User
|
||||
if user, ok := c.Get("user"); ok {
|
||||
u = user.(*User)
|
||||
} else {
|
||||
u = c.MustGet("LoggedUser").(*User)
|
||||
}
|
||||
s := c.MustGet("survey").(*Survey)
|
||||
|
||||
if (s.Promo == u.Promo && s.Shown) || (u != nil && u.IsAdmin) {
|
||||
score, err := s.GetScore(u)
|
||||
if err != nil {
|
||||
log.Printf("Unable to GetScore(uid=%d;sid=%d): %s", u.Id, s.Id, err.Error())
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "An error occurs when trying to retrieve score."})
|
||||
return
|
||||
}
|
||||
|
||||
if score == nil {
|
||||
c.JSON(http.StatusOK, map[string]string{"score": "N/A"})
|
||||
} else {
|
||||
c.JSON(http.StatusOK, map[string]float64{"score": *score})
|
||||
}
|
||||
} else {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"errmsg": "Not accessible"})
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
declareAPIAuthAsksRoutes(surveysRoutes)
|
||||
declareAPIAuthDirectRoutes(surveysRoutes)
|
||||
declareAPIAuthGradesRoutes(surveysRoutes)
|
||||
declareAPIAuthQuestionsRoutes(surveysRoutes)
|
||||
declareAPIAuthResponsesRoutes(surveysRoutes)
|
||||
}
|
||||
|
||||
func declareAPIAdminSurveysRoutes(router *gin.RouterGroup) {
|
||||
router.POST("/surveys", func(c *gin.Context) {
|
||||
var new Survey
|
||||
if err := json.Unmarshal(body, &new); err != nil {
|
||||
return APIErrorResponse{err: err}
|
||||
if err := c.ShouldBindJSON(&new); err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if new.Promo == 0 {
|
||||
new.Promo = currentPromo
|
||||
}
|
||||
|
||||
return formatApiResponse(NewSurvey(new.Title, new.Promo, new.Group, new.Shown, new.Direct, new.StartAvailability, new.EndAvailability))
|
||||
}, adminRestricted))
|
||||
router.GET("/api/surveys/:sid", apiAuthHandler(surveyAuthHandler(
|
||||
func(s Survey, u *User, _ []byte) HTTPResponse {
|
||||
if u == nil {
|
||||
return APIErrorResponse{
|
||||
status: http.StatusUnauthorized,
|
||||
err: errors.New("Veuillez vous connecter pour accéder à cette page."),
|
||||
}
|
||||
} else if (s.Promo == u.Promo && (s.Group == "" || strings.Contains(u.Groups, ","+s.Group+",") && s.Shown)) || 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 {
|
||||
if s, err := NewSurvey(new.Title, new.Promo, new.Group, new.Shown, new.Direct, new.StartAvailability, new.EndAvailability); err != nil {
|
||||
log.Println("Unable to NewSurvey:", err)
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("An error occurs during survey creation: %s", err.Error())})
|
||||
return
|
||||
} else {
|
||||
c.JSON(http.StatusOK, s)
|
||||
}
|
||||
})
|
||||
|
||||
surveysRoutes := router.Group("/surveys/:sid")
|
||||
surveysRoutes.Use(surveyHandler)
|
||||
|
||||
surveysRoutes.PUT("", func(c *gin.Context) {
|
||||
current := c.MustGet("survey").(*Survey)
|
||||
|
||||
var new Survey
|
||||
if err := json.Unmarshal(body, &new); err != nil {
|
||||
return APIErrorResponse{err: err}
|
||||
if err := c.ShouldBindJSON(&new); err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
new.Id = current.Id
|
||||
|
|
@ -91,72 +156,41 @@ func init() {
|
|||
}
|
||||
}
|
||||
|
||||
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))
|
||||
if survey, err := new.Update(); err != nil {
|
||||
log.Println("Unable to Update survey:", err)
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("An error occurs during survey updation: %s", err.Error())})
|
||||
return
|
||||
} else {
|
||||
c.JSON(http.StatusOK, survey)
|
||||
}
|
||||
})
|
||||
surveysRoutes.DELETE("", func(c *gin.Context) {
|
||||
survey := c.MustGet("survey").(*Survey)
|
||||
|
||||
if _, err := survey.Delete(); err != nil {
|
||||
log.Println("Unable to Delete survey:", err)
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("An error occurs during survey deletion: %s", err.Error())})
|
||||
return
|
||||
} else {
|
||||
c.JSON(http.StatusOK, nil)
|
||||
}
|
||||
})
|
||||
|
||||
declareAPIAdminAsksRoutes(surveysRoutes)
|
||||
declareAPIAdminDirectRoutes(surveysRoutes)
|
||||
declareAPIAdminQuestionsRoutes(surveysRoutes)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
func surveyHandler(c *gin.Context) {
|
||||
if sid, err := strconv.Atoi(string(c.Param("sid"))); err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": "Bad survey identifier."})
|
||||
return
|
||||
} else if survey, err := getSurvey(sid); err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Survey not found."})
|
||||
return
|
||||
} else {
|
||||
c.Set("survey", survey)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -172,7 +206,7 @@ type Survey struct {
|
|||
EndAvailability time.Time `json:"end_availability"`
|
||||
}
|
||||
|
||||
func getSurveys(cnd string, param ...interface{}) (surveys []Survey, err error) {
|
||||
func getSurveys(cnd string, param ...interface{}) (surveys []*Survey, err error) {
|
||||
if rows, errr := DBQuery("SELECT id_survey, title, promo, grp, shown, direct, corrected, start_availability, end_availability FROM surveys "+cnd, param...); errr != nil {
|
||||
return nil, errr
|
||||
} else {
|
||||
|
|
@ -183,7 +217,7 @@ func getSurveys(cnd string, param ...interface{}) (surveys []Survey, err error)
|
|||
if err = rows.Scan(&s.Id, &s.Title, &s.Promo, &s.Group, &s.Shown, &s.Direct, &s.Corrected, &s.StartAvailability, &s.EndAvailability); err != nil {
|
||||
return
|
||||
}
|
||||
surveys = append(surveys, s)
|
||||
surveys = append(surveys, &s)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return
|
||||
|
|
@ -193,7 +227,8 @@ func getSurveys(cnd string, param ...interface{}) (surveys []Survey, err error)
|
|||
}
|
||||
}
|
||||
|
||||
func getSurvey(id int) (s Survey, err error) {
|
||||
func getSurvey(id int) (s *Survey, err error) {
|
||||
s = new(Survey)
|
||||
err = DBQueryRow("SELECT id_survey, title, promo, grp, shown, direct, corrected, start_availability, end_availability FROM surveys WHERE id_survey=?", id).Scan(&s.Id, &s.Title, &s.Promo, &s.Group, &s.Shown, &s.Direct, &s.Corrected, &s.StartAvailability, &s.EndAvailability)
|
||||
return
|
||||
}
|
||||
|
|
|
|||
Reference in a new issue