1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-19 02:47:04 +00:00

move example flash-messages to sessions example folder and change httptest example with basicauth

Former-commit-id: 3c5f6c97629a2a6ae44e62f2900edd32c0329b50
This commit is contained in:
kataras
2017-06-10 05:00:18 +03:00
parent c4788ee4e8
commit dd26fbf26d
7 changed files with 76 additions and 47 deletions

View File

@@ -3,33 +3,57 @@ package main
import (
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/sessions"
"github.com/kataras/iris/middleware/basicauth"
)
func main() {
func buildApp() *iris.Application {
app := iris.New()
app.AttachSessionManager(sessions.New(sessions.Config{Cookie: "mysessionid"}))
authConfig := basicauth.Config{
Users: map[string]string{"myusername": "mypassword", "mySecondusername": "mySecondpassword"},
Realm: "Authorization Required", // defaults to "Authorization Required"
ContextKey: "user", // defaults to "user"
}
app.Get("/hello", func(ctx context.Context) {
sess := ctx.Session()
if !sess.HasFlash() {
ctx.HTML("<h1> Unauthorized Page! </h1>")
return
}
authentication := basicauth.New(authConfig)
ctx.JSON(context.Map{
"Message": "Hello",
"From": sess.GetFlash("name"),
// to global app.Use(authentication) (or app.UseGlobal before the .Run)
// to routes
/*
app.Get("/mysecret", authentication, func(ctx context.Context) {
username := ctx.Values().GetString("user") // the Contextkey from the authConfig
ctx.Writef("Hello authenticated user: %s ", username)
})
})
*/
app.Post("/login", func(ctx context.Context) {
sess := ctx.Session()
if !sess.HasFlash() {
sess.SetFlash("name", ctx.FormValue("name"))
}
app.Get("/", func(ctx context.Context) { ctx.Redirect("/admin") })
})
// to party
needAuth := app.Party("/admin", authentication)
{
//http://localhost:8080/admin
needAuth.Get("/", func(ctx context.Context) {
username := ctx.Values().GetString("user") // the Contextkey from the authConfig
ctx.Writef("Hello authenticated user: %s from: %s", username, ctx.Path())
})
// http://localhost:8080/admin/profile
needAuth.Get("/profile", func(ctx context.Context) {
username := ctx.Values().GetString("user") // the Contextkey from the authConfig
ctx.Writef("Hello authenticated user: %s from: %s", username, ctx.Path())
})
// http://localhost:8080/admin/settings
needAuth.Get("/settings", func(ctx context.Context) {
username := authConfig.User(ctx) // shortcut for ctx.Values().GetString("user")
ctx.Writef("Hello authenticated user: %s from: %s", username, ctx.Path())
})
}
return app
}
func main() {
app := buildApp()
app.Run(iris.Addr(":8080"))
}