-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
main.go
99 lines (80 loc) · 2.07 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/x/errors"
"github.com/kataras/iris/v12/middleware/basicauth"
)
func newApp() *iris.Application {
app := iris.New()
/*
opts := basicauth.Options{
Realm: "Authorization Required",
MaxAge: 30 * time.Minute,
GC: basicauth.GC{
Every: 2 * time.Hour,
},
Allow: basicauth.AllowUsers(map[string]string{
"myusername": "mypassword",
"mySecondusername": "mySecondpassword",
}),
MaxTries: 2,
}
auth := basicauth.New(opts)
OR simply:
*/
auth := basicauth.Default(map[string]string{
"myusername": "mypassword",
"mySecondusername": "mySecondpassword",
})
// To the next routes of a party (group of routes):
/*
app.Use(auth)
*/
// For global effect, including not founds:
/*
app.UseRouter(auth)
*/
// For global effect, excluding http errors such as not founds:
/*
app.UseGlobal(auth) or app.Use(auth) before any route registered.
*/
// For single/per routes:
/*
app.Get("/mysecret", auth, h)
*/
app.Get("/", func(ctx iris.Context) { ctx.Redirect("/admin") })
// to party
needAuth := app.Party("/admin", auth)
{
//http://localhost:8080/admin
needAuth.Get("/", handler)
// http://localhost:8080/admin/profile
needAuth.Get("/profile", handler)
// http://localhost:8080/admin/settings
needAuth.Get("/settings", handler)
needAuth.Get("/logout", logout)
}
return app
}
func main() {
app := newApp()
// open http://localhost:8080/admin
app.Listen(":8080")
}
func handler(ctx iris.Context) {
// user := ctx.User().(*myUserType)
// or ctx.User().GetRaw().(*myUserType)
// ctx.Writef("%s %s:%s", ctx.Path(), user.Username, user.Password)
// OR if you don't have registered custom User structs:
username, password, _ := ctx.Request().BasicAuth()
ctx.Writef("%s %s:%s", ctx.Path(), username, password)
}
func logout(ctx iris.Context) {
// fires 401, invalidates the basic auth,
// logout through javascript and ajax is a better solution though.
err := ctx.Logout()
if err != nil {
errors.Internal.Err(ctx, err)
return
}
}