Skip to content
Snippets Groups Projects
Select Git revision
  • 0ffc32b6214f28d3d86abcd8f62a737595e67f8a
  • master default protected
2 results

main.go

Blame
  • main.go 5.43 KiB
    package main
    
    import (
    	"net/http"
    	"os"
    	"strings"
    
    	"github.com/gin-gonic/gin"
    	jwtverifier "github.com/okta/okta-jwt-verifier-golang"
    )
    
    // student represents data about a record album.
    type student struct {
    	ID   string `json:"id"`
    	Name string `json:"name"`
    }
    
    // student represents data about a record album.
    type teacher struct {
    	ID   string `json:"id"`
    	Name string `json:"name"`
    }
    
    // teachers slice to seed record teachers data.
    var teachers = []teacher{
    	{ID: "1", Name: "Malaspinas"},
    	{ID: "2", Name: "Albuquerque"},
    	{ID: "3", Name: "Jenny"},
    }
    
    // students slice to seed record students data.
    var students = []student{
    	{ID: "1", Name: "Blue Train"},
    	{ID: "2", Name: "Patrick"},
    	{ID: "3", Name: "Joseph"},
    }
    
    func main() {
    	router := gin.Default()
    
    	//Utilisateurs autorisés à faire des gets
    	getAuthorized := router.Group("/", gin.BasicAuth(gin.Accounts{
    		"foo":      os.Getenv("foo"),
    		"aristote": os.Getenv("aristote"),
    	}))
    	//Utilisateurs autorisés à faire toutes les requêtes
    	allRequestAuthorized := router.Group("/", gin.BasicAuth(gin.Accounts{
    		"aristote": os.Getenv("aristote"),
    	}))
    
    	//Students
    	getAuthorized.GET("/students", getStudents)
    	getAuthorized.GET("/students/:id", getStudentsByID)
    	allRequestAuthorized.POST("/students", postStudents)
    	allRequestAuthorized.DELETE("/studentsDel/:id", deleteStudentById)
    	//Teachers
    	router.GET("/teachers", getTeachers)
    	router.GET("/teachers/:id", getTeacherByID)
    	router.POST("/teachers", postTeachers)
    	router.DELETE("/teachersDel/:id", deleteTeacherById)
    
    	router.Run(":8080")
    }
    
    var toValidate = map[string]string{
    	"aud": "api://default",
    	"cid": "0oa3lqlg4zhSheFli5d7",
    }
    
    func verify(c *gin.Context) bool {
    	status := true
    	token := c.Request.Header.Get("Authorization")
    	if strings.HasPrefix(token, "Bearer ") {
    		token = strings.TrimPrefix(token, "Bearer ")
    		verifierSetup := jwtverifier.JwtVerifier{
    			Issuer:           "https://dev-31427777.okta.com/oauth2/default",
    			ClaimsToValidate: toValidate,
    		}
    		verifier := verifierSetup.New()
    		_, err := verifier.VerifyAccessToken(token)
    		if err != nil {
    			c.String(http.StatusForbidden, err.Error())
    			print(err.Error())
    			status = false
    		}
    	} else {
    		c.String(http.StatusUnauthorized, "Unauthorized")
    		status = false
    	}
    	return status
    }
    
    // getStudents responds with the list of all students as JSON.
    func getStudents(c *gin.Context) {
    	c.IndentedJSON(http.StatusOK, students)
    }
    
    // getStudents responds with the list of all students as JSON.
    func getTeachers(c *gin.Context) {
    	if verify(c) {
    		c.IndentedJSON(http.StatusOK, teachers)
    	}
    }
    
    // postStudents adds an album from JSON received in the request body.
    func postStudents(c *gin.Context) {
    
    	var newStudent student
    
    	// Call BindJSON to bind the received JSON to
    	// newAlbum.
    	if err := c.BindJSON(&newStudent); err != nil {
    		return
    	}
    
    	// Add the new album to the slice.
    	students = append(students, newStudent)
    	c.IndentedJSON(http.StatusCreated, newStudent)
    
    }
    
    // postAlbums adds an album from JSON received in the request body.
    func postTeachers(c *gin.Context) {
    	if verify(c) {
    		var newTeacher teacher
    
    		// Call BindJSON to bind the received JSON to
    
    		if err := c.BindJSON(&newTeacher); err != nil {
    			return
    		}
    
    		// Add the new album to the slice.
    		teachers = append(teachers, newTeacher)
    		c.IndentedJSON(http.StatusCreated, newTeacher)
    
    	}
    
    }
    
    // getStudentsByID locates the student whose ID value matches the id
    // parameter sent by the client, then returns that student as a response.
    func getStudentsByID(c *gin.Context) {
    
    	id := c.Param("id")
    
    	// Loop through the list of albums, looking for
    	// an album whose ID value matches the parameter.
    	for _, a := range students {
    		if a.ID == id {
    			c.IndentedJSON(http.StatusOK, a)
    			return
    		}
    	}
    	c.IndentedJSON(http.StatusNotFound, gin.H{"message": "student not found"})
    
    }
    
    // getTeacherByID locates the teacher whose ID value matches the id
    // parameter sent by the client, then returns that teacher as a response.
    func getTeacherByID(c *gin.Context) {
    	if verify(c) {
    
    		id := c.Param("id")
    
    		// Loop through the list of albums, looking for
    		// an album whose ID value matches the parameter.
    		for _, a := range teachers {
    			if a.ID == id {
    				c.IndentedJSON(http.StatusOK, a)
    				return
    			}
    		}
    		c.IndentedJSON(http.StatusNotFound, gin.H{"message": "teacher not found"})
    	}
    
    }
    
    //Delete a student by his ID
    func deleteStudentById(c *gin.Context) {
    
    	id := c.Param("id")
    
    	var emptyStudent student
    	for i, student := range students {
    		if student.ID == id {
    			//Suppression d'un élément dans un tableau
    			students[i] = students[len(students)-1]
    			students[len(students)-1] = emptyStudent
    			students = students[:len(students)-1]
    			c.IndentedJSON(http.StatusOK, student)
    			return
    		}
    	}
    	c.IndentedJSON(http.StatusNotFound, gin.H{"message": "student not found"})
    
    }
    
    //Delete a teacher by his ID
    func deleteTeacherById(c *gin.Context) {
    
    	if verify(c) {
    
    		id := c.Param("id")
    
    		var emptyTeacher teacher
    		for i, student := range students {
    			if student.ID == id {
    				teachers[i] = teachers[len(students)-1]
    				teachers[len(teachers)-1] = emptyTeacher
    				teachers = teachers[:len(teachers)-1]
    				c.IndentedJSON(http.StatusOK, student)
    				return
    			}
    		}
    		c.IndentedJSON(http.StatusNotFound, gin.H{"message": "teacher not found"})
    	}
    
    }