72 lines
1.4 KiB
Go
72 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"gopkg.in/gin-gonic/gin.v1"
|
|
)
|
|
|
|
func main() {
|
|
router := gin.Default()
|
|
|
|
router.LoadHTMLGlob("./templates/*")
|
|
// Middleware
|
|
//e.Use(middleware.Logger())
|
|
//e.Use(middleware.Recover())
|
|
//e.Use(middleware.Static("static"))
|
|
|
|
router.GET("/login.html", login)
|
|
a := router.Group("/api/v1")
|
|
{
|
|
a.GET("/login", func(c *gin.Context) {
|
|
c.Redirect(http.StatusPermanentRedirect, "/login.html")
|
|
})
|
|
a.POST("/login", loginPost)
|
|
|
|
// Unauthenticated routes
|
|
a.GET("/check", func(c *gin.Context) {
|
|
c.String(http.StatusOK, "Accessible")
|
|
})
|
|
a.GET("/hello", func(c *gin.Context) {
|
|
c.String(http.StatusOK, "Hello, World!")
|
|
})
|
|
}
|
|
|
|
// Restricted group
|
|
r := a.Group("/restricted")
|
|
{
|
|
//r.Use(middleware.JWT([]byte(secret)))
|
|
r.GET("", restricted)
|
|
}
|
|
|
|
router.Run(":1323")
|
|
}
|
|
|
|
func restricted(c *gin.Context) {
|
|
//user, _ := c.Get("user") //.(*jwt.Token)
|
|
//name := user.Claims["name"].(string)
|
|
name := "jan"
|
|
c.String(http.StatusOK, "Welcome "+name+"!")
|
|
}
|
|
|
|
func login(c *gin.Context) {
|
|
if verifyLogin(c) {
|
|
c.Redirect(http.StatusTemporaryRedirect, "/api/v1/hello")
|
|
return
|
|
}
|
|
|
|
c.HTML(http.StatusOK, "login.html", nil)
|
|
}
|
|
|
|
func loginPost(c *gin.Context) {
|
|
username, _ := c.GetPostForm("username")
|
|
password, _ := c.GetPostForm("password")
|
|
|
|
if username != "jan" || password != "passwort" {
|
|
c.AbortWithStatus(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
loginSuccess(c, username, "Jan Bader")
|
|
}
|