78 lines
1.5 KiB
Go
78 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"gopkg.in/gin-gonic/gin.v1"
|
|
)
|
|
|
|
func main() {
|
|
router := gin.Default()
|
|
|
|
router.LoadHTMLGlob("./templates/*")
|
|
router.Static("/static", "./static")
|
|
|
|
router.GET("/login", login)
|
|
api := router.Group("/api/v1")
|
|
{
|
|
api.GET("/logout", logout)
|
|
api.GET("/login", func(c *gin.Context) {
|
|
c.Redirect(http.StatusPermanentRedirect, "/login")
|
|
})
|
|
api.POST("/login", loginPost)
|
|
|
|
// Unauthenticated routes
|
|
api.GET("/check", func(c *gin.Context) {
|
|
c.String(http.StatusOK, "Accessible")
|
|
})
|
|
api.GET("/hello", func(c *gin.Context) {
|
|
c.String(http.StatusOK, "Hello, World!")
|
|
})
|
|
|
|
// Restricted group
|
|
r := api.Group("/restricted")
|
|
{
|
|
//r.Use(middleware.JWT([]byte(secret)))
|
|
r.GET("", restricted)
|
|
}
|
|
}
|
|
|
|
router.Run(":1323")
|
|
}
|
|
|
|
func restricted(c *gin.Context) {
|
|
claims, ok := verifyLogin(c)
|
|
if !ok {
|
|
c.Redirect(http.StatusTemporaryRedirect, "/login")
|
|
return
|
|
}
|
|
|
|
name := claims["name"].(string)
|
|
c.String(http.StatusOK, "Welcome "+name+"!")
|
|
}
|
|
|
|
func login(c *gin.Context) {
|
|
if _, ok := verifyLogin(c); ok {
|
|
c.Redirect(http.StatusTemporaryRedirect, "/api/v1/hello")
|
|
return
|
|
}
|
|
|
|
c.HTML(http.StatusOK, "login.html", nil)
|
|
}
|
|
|
|
func logout(c *gin.Context) {
|
|
clearLogin(c)
|
|
}
|
|
|
|
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")
|
|
}
|