// SetRoutes sets the crud and migration (if them exists) routes func SetRoutes(r *gin.Engine) { taskRoute := r.Group("/api/task") taskRoute.Use(jwt.Auth(config.TokenSecret)) // Task CRUD taskRoute.GET("/*id", taskRetrieveRoute) taskRoute.POST("/", taskCreateRoute) taskRoute.PUT("/:id", taskUpdateRoute) taskRoute.DELETE("/:id", taskDeleteRoute) }
func main() { // TODO: move to dotfile os.Setenv("signingToken", "yeahellobobhowareyou") models.InitDb() router := gin.Default() // TODO: namespace under /api/v1 public := router.Group("/api") public.POST("/users/auth", controllers.UserAuth) public.POST("/users", controllers.UserCreate) public.GET("/s", controllers.SubIndex) public.GET("/s/:id", controllers.SubShow) public.GET("/s/:id/posts/:postId/comments", controllers.CommentIndex) public.GET("/s/:id/posts/:postId", controllers.PostShow) public.GET("/s/:id/posts", controllers.PostIndex) public.GET("/comments/:id", controllers.CommentShow) public.GET("/comments/:id/comments", controllers.CommentIndex) private := router.Group("/api") private.Use(jwt.Auth(os.Getenv("signingToken"))) private.POST("/s", controllers.SubCreate) private.PATCH("/s/:id", controllers.SubUpdate) private.DELETE("/s/:id", controllers.SubDelete) private.POST("/s/:id/posts", controllers.PostCreate) private.PATCH("/posts/:id", controllers.PostUpdate) private.DELETE("/posts/:id", controllers.PostDelete) private.POST("/posts/:id/vote", controllers.PostVoteCreate) private.POST("/comments", controllers.CommentCreate) private.PATCH("/comments/:id", controllers.CommentUpdate) private.DELETE("/comments/:id", controllers.CommentDelete) private.POST("/comments/:id/vote", controllers.CommentVoteCreate) router.Run(":9999") }
func main() { r := gin.Default() public := r.Group("/api") public.GET("/", func(c *gin.Context) { // Create the token token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256")) // Set some claims token.Claims["ID"] = "Christopher" token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix() // Sign and get the complete encoded token as a string tokenString, err := token.SignedString([]byte(mysupersecretpassword)) if err != nil { c.JSON(500, gin.H{"message": "Could not generate token"}) } c.JSON(200, gin.H{"token": tokenString}) }) private := r.Group("/api/private") private.Use(jwt.Auth(mysupersecretpassword)) /* Set this header in your request to get here. Authorization: Bearer `token` */ private.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Hello from private"}) }) r.Run("localhost:8080") }
func main() { controller.SetSession() router := gin.Default() router.Use(static.Serve("/", static.LocalFile("../front_end/", true))) publicAPI := router.Group("/api/public") privateAPI := router.Group("/api/private") privateAPI.Use(jwt.Auth(getDecodedSecret())) publicAPI.GET("/courses", func(c *gin.Context) { courses, err := controller.FetchAllCourses() if err != nil { fmt.Println(err) } c.JSON(200, helper.GetJSONFormat(courses)) }) privateAPI.POST("/course_create", func(c *gin.Context) { data, _ := ioutil.ReadAll(c.Request.Body) courseID := controller.CreateCourse(data) authToken := c.Request.Header.Get("Authorization") if controller.UpdateUser(courseID, configFile["Auth0BaseURL"], authToken) == 200 { c.JSON(200, gin.H{"courseID": courseID}) } else { c.JSON(400, gin.H{"error": "Course creation failed."}) } }) privateAPI.POST("/course_update", func(c *gin.Context) { data, _ := ioutil.ReadAll(c.Request.Body) courseID := controller.UpdateCourse(data) if courseID != "" { c.JSON(200, gin.H{"courseID": courseID}) } else { c.JSON(400, gin.H{"error": "Course update failed."}) } }) publicAPI.GET("/course/:courseID", func(c *gin.Context) { courseID := c.Param("courseID") course, err := controller.FetchCourse(courseID) if err != nil { fmt.Println(err) } c.JSON(200, helper.GetJSONFormat(course)) }) router.Run(":8081") }
func main() { // Set up server ginServer := gin.Default() ginServer.Use(dbWare()) //login public routes ginServer.POST("/login", userLogin) ginServer.POST("/signup", userAdd) //set up private routes private := ginServer.Group("/api") private.Use(jwt.Auth(SECRET)) // user private /api routes private.DELETE("/user/delete/:email", userRemove) //link private /api routes private.GET("/link/all/:email", linkIndex) private.POST("/link/new", linkAdd) private.PUT("/link/update/:id", linkUpdate) ginServer.Run(":3001") }
func main() { router := gin.Default() v1 := router.Group("api/v1") { v1.GET("/users", GetUsers) } // Example for binding JSON ({"user": "******", "password": "******"}) router.POST("/loginJSON", func(c *gin.Context) { fmt.Println("/loginJSon been call ") var json LoginJSON c.Bind(&json) // This will infer what binder to use depending on the content-type header. req := c.Request requestToken := req.Header.Get("Authorization") /* if ah := req.Header.Get("Authorization"); ah != "" { // Should be a bearer token if len(ah) > 6 && strings.ToUpper(ah[0:6]) == "BEARER" { return Parse(ah[7:], keyFunc) } } */ fmt.Println("user is:", json.User) fmt.Println("password", json.Password) fmt.Println("requestToken", requestToken) /* debug javascript fetch */ c.JSON(http.StatusOK, gin.H{"status": "you are logged in", "user": json.User, "password": json.Password, "token": requestToken}) fmt.Println("gin.H: ", gin.H{"status": "you are logged in"}) /* debug end */ /* if json.User == "user" && json.Password == "password" { token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256")) // Set some claims token.Claims["ID"] = json.User token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix() // Sign and get the complete encoded token as a string tokenString, _ := token.SignedString([]byte(mysupersecretpassword)) c.JSON(http.StatusOK, gin.H{"status": "you are logged in", "id_token": tokenString}) fmt.Println("gin.H: ", gin.H{"status": "you are logged in", "id_token": tokenString}) } else { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) } */ }) router.GET("/auth", func(c *gin.Context) { token := c.Request.Header.Get("Authorization") fmt.Println("Authorization: ", token) c.JSON(200, gin.H{"Authorization": token}) }) /* // Example for binding a HTML form (user=manu&password=123) router.POST("/loginHTML", func(c *gin.Context) { var form LoginForm c.BindWith(&form, binding.Form) // You can also specify which binder to use. We support binding.Form, binding.JSON and binding.XML. if form.User == "manu" && form.Password == "123" { c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) } else { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) } }) */ staticHtmlPath := "/Users/qinshen/git/personal_project/todos/todos-font/layout-demo" // "/Users/qinshen/git/web-project/dashboard-ui-es6/build" router.Static("/static", staticHtmlPath) public := router.Group("/api") public.GET("/", func(c *gin.Context) { // Create the token token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256")) // Set some claims token.Claims["ID"] = "Christopher" token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix() // Sign and get the complete encoded token as a string tokenString, err := token.SignedString([]byte(mysupersecretpassword)) if err != nil { c.JSON(500, gin.H{"message": "Could not generate token"}) } c.JSON(201, gin.H{"id_token": tokenString}) }) private := router.Group("/api/private") private.Use(jwt.Auth(mysupersecretpassword)) /* Set this header in your request to get here. Authorization: Bearer `token` */ private.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Hello from private"}) }) router.Run("localhost:8080") }
func main() { getPathFromParameterAndLoadConfigFile() goth.UseProviders( facebook.New("870850926323133", "54c9687312192961b6e2b5caa319db4b", "http://localhost:8081/auth/facebook/callback"), ) gothic.GetState = func(req *http.Request) string { return req.URL.Query().Get("state") } router := gin.New() router.Use(cors.Middleware(cors.Options{ AllowHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods", "Access-Control-Allow-Origin"}, })) // Set Logger gin.DefaultWriter = config.GetLogFile() router.Use(gin.Logger()) router.Use(gin.Recovery()) tasks.SetRoutes(router) public := router.Group("/api") public.GET("/", func(c *gin.Context) { tokenString, err := createJWTToken("AnonymousUser") if err != nil { c.JSON(500, gin.H{"message": "Could not generate token"}) return } c.JSON(200, gin.H{"accessToken": tokenString}) }) private := router.Group("/api/private") private.Use(jwt.Auth(config.TokenSecret)) /* Set this header in your request to get here. Authorization: Bearer `token` */ private.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Hello from private"}) }) authRoute := router.Group("/auth") authRoute.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Go to /auth/facebook"}) }) authRoute.GET("/facebook", func(c *gin.Context) { gothic.GetProviderName = getProviderFacebook gothic.BeginAuthHandler(c.Writer, c.Request) }) authRoute.GET("/facebook/callback", func(c *gin.Context) { user, err := gothic.CompleteUserAuth(c.Writer, c.Request) if err != nil { fmt.Fprintln(c.Writer, err) return } tokenString, err := createJWTToken(user.Email) if err != nil { c.JSON(500, gin.H{"message": "Could not generate token"}) } c.JSON(200, gin.H{ "name": user.Name, "email": user.Email, "userId": user.UserID, "facebookAccessToken": user.AccessToken, "accessToken": tokenString, }) }) router.Run(config.Settings["ListenAddress"].(string)) }
/* JWTAuth JSON WEB TOKEN Auth middleware See: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing */ func JWTAuth(secretPassword string) gin.HandlerFunc { return jwt.Auth(secretPassword) }