budgeteer/main.go
2016-11-25 17:11:02 +01:00

77 lines
1.5 KiB
Go

package main
import (
"net/http"
"gopkg.in/gin-gonic/gin.v1"
)
func main() {
router := gin.Default()
router.LoadHTMLGlob("./templates/*")
// Middleware
router.Static("static", "static")
//e.Use(middleware.Logger())
//e.Use(middleware.Recover())
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) {
claims, ok := verifyLogin(c)
if !ok {
c.Redirect(http.StatusTemporaryRedirect, "/login.html")
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 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")
}