Last active
May 4, 2017 15:14
-
-
Save Mudpuppy12/db9f2a2b4ab62babd72a1edddd4b5273 to your computer and use it in GitHub Desktop.
Example Iris Session / Basic Auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// main.go | |
package main | |
import ( | |
"time" | |
"github.com/kataras/iris" | |
"github.com/kataras/iris/config" | |
"github.com/kataras/iris/middleware/basicauth" | |
"github.com/kataras/iris/middleware/logger" | |
"github.com/kataras/iris/sessions" | |
) | |
func loginRequired(ctx *iris.Context) { | |
session := sess.Start(ctx) | |
if v := session.Get("username"); v != nil { | |
ctx.Next() | |
} else { | |
ctx.RedirectTo("/login") | |
} | |
} | |
var sess *sessions.Manager | |
func init() { | |
sessConfig := config.Sessions{ | |
Provider: "memory", // if you set it to "" means that sessions are disabled. | |
Cookie: "yoursessionCOOKIEID", | |
Expires: config.CookieExpireNever, | |
GcDuration: time.Duration(2) * time.Hour, | |
} | |
sess = sessions.New(sessConfig) // or just sessions.New() | |
} | |
func main() { | |
authentication := basicauth.Default(map[string]string{"admin": "admin"}) | |
iris.Config.Render.Template.Directory = "templates" | |
iris.Config.Render.Template.Engine = config.PongoEngine // or iris.PongoEngine without need to import the config | |
iris.Use(logger.New(iris.Logger)) | |
// Home | |
iris.Get("/", loginRequired, func(ctx *iris.Context) { | |
session := sess.Start(ctx) | |
ctx.MustRender("index.html", map[string]interface{}{"username": session.Get("username"), "is_admin": true}) | |
}) | |
// login | |
iris.Get("/login", authentication, func(ctx *iris.Context) { | |
session := sess.Start(ctx) | |
session.Set("username", ctx.GetString("auth")) | |
ctx.MustRender("login.html", map[string]interface{}{"username": session.Get("username")}) | |
}) | |
// Logout | |
iris.Get("/logout", func(ctx *iris.Context) { | |
sess.Destroy(ctx) | |
ctx.Write("Logged out, Session destroyed") | |
}) | |
println("Server is running at :8080") | |
iris.Listen(":8080") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment