mirror of
https://github.com/kataras/iris.git
synced 2025-12-19 10:57:05 +00:00
fix all _examples to the newest mvc, add comments to those examples and add a package-level .Configure in order to make it easier for new users. Add a deprecated panic if app.Controller is used with a small tutorial and future resource link so they can re-write their mvc app's definitions
Former-commit-id: bf07696041be9e3d178ce3c42ccec2df4bfdb2af
This commit is contained in:
@@ -6,51 +6,52 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/mvc"
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
const sessionIDKey = "UserID"
|
||||
|
||||
// paths
|
||||
const (
|
||||
PathLogin = "/user/login"
|
||||
PathLogout = "/user/logout"
|
||||
)
|
||||
|
||||
// the session key for the user id comes from the Session.
|
||||
const (
|
||||
sessionIDKey = "UserID"
|
||||
var (
|
||||
PathLogin = mvc.Response{Path: "/user/login"}
|
||||
PathLogout = mvc.Response{Path: "/user/logout"}
|
||||
)
|
||||
|
||||
// AuthController is the user authentication controller, a custom shared controller.
|
||||
type AuthController struct {
|
||||
iris.SessionController
|
||||
// context is auto-binded if struct depends on this,
|
||||
// in this controller we don't we do everything with mvc-style,
|
||||
// and that's neither the 30% of its features.
|
||||
// Ctx iris.Context
|
||||
|
||||
Source *DataSource
|
||||
User Model `iris:"model"`
|
||||
Source *DataSource
|
||||
Session *sessions.Session
|
||||
|
||||
// the whole controller is request-scoped because we already depend on Session, so
|
||||
// this will be new for each new incoming request, BeginRequest sets that based on the session.
|
||||
UserID int64
|
||||
}
|
||||
|
||||
// BeginRequest saves login state to the context, the user id.
|
||||
func (c *AuthController) BeginRequest(ctx iris.Context) {
|
||||
c.SessionController.BeginRequest(ctx)
|
||||
c.UserID, _ = c.Session.GetInt64(sessionIDKey)
|
||||
}
|
||||
|
||||
if userID := c.Session.Get(sessionIDKey); userID != nil {
|
||||
ctx.Values().Set(sessionIDKey, userID)
|
||||
// EndRequest is here just to complete the BaseController
|
||||
// in order to be tell iris to call the `BeginRequest` before the main method.
|
||||
func (c *AuthController) EndRequest(ctx iris.Context) {}
|
||||
|
||||
func (c *AuthController) fireError(err error) mvc.View {
|
||||
return mvc.View{
|
||||
Code: iris.StatusBadRequest,
|
||||
Name: "shared/error.html",
|
||||
Data: iris.Map{"Title": "User Error", "Message": strings.ToUpper(err.Error())},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *AuthController) fireError(err error) {
|
||||
if err != nil {
|
||||
c.Ctx.Application().Logger().Debug(err.Error())
|
||||
|
||||
c.Status = 400
|
||||
c.Data["Title"] = "User Error"
|
||||
c.Data["Message"] = strings.ToUpper(err.Error())
|
||||
c.Tmpl = "shared/error.html"
|
||||
}
|
||||
}
|
||||
|
||||
func (c *AuthController) redirectTo(id int64) {
|
||||
if id > 0 {
|
||||
c.Path = "/user/" + strconv.Itoa(int(id))
|
||||
}
|
||||
func (c *AuthController) redirectTo(id int64) mvc.Response {
|
||||
return mvc.Response{Path: "/user/" + strconv.Itoa(int(id))}
|
||||
}
|
||||
|
||||
func (c *AuthController) createOrUpdate(firstname, username, password string) (user Model, err error) {
|
||||
@@ -75,8 +76,8 @@ func (c *AuthController) createOrUpdate(firstname, username, password string) (u
|
||||
|
||||
func (c *AuthController) isLoggedIn() bool {
|
||||
// we don't search by session, we have the user id
|
||||
// already by the `SaveState` middleware.
|
||||
return c.Values.Get(sessionIDKey) != nil
|
||||
// already by the `BeginRequest` middleware.
|
||||
return c.UserID > 0
|
||||
}
|
||||
|
||||
func (c *AuthController) verify(username, password string) (user Model, err error) {
|
||||
@@ -101,24 +102,9 @@ func (c *AuthController) verify(username, password string) (user Model, err erro
|
||||
// if logged in then destroy the session
|
||||
// and redirect to the login page
|
||||
// otherwise redirect to the registration page.
|
||||
func (c *AuthController) logout() {
|
||||
func (c *AuthController) logout() mvc.Response {
|
||||
if c.isLoggedIn() {
|
||||
// c.Manager is the Sessions manager created
|
||||
// by the embedded SessionController, automatically.
|
||||
c.Manager.DestroyByID(c.Session.ID())
|
||||
return
|
||||
c.Session.Destroy()
|
||||
}
|
||||
|
||||
c.Path = PathLogin
|
||||
}
|
||||
|
||||
// AllowUser will check if this client is a logged user,
|
||||
// if not then it will redirect that guest to the login page
|
||||
// otherwise it will allow the execution of the next handler.
|
||||
func AllowUser(ctx iris.Context) {
|
||||
if ctx.Values().Get(sessionIDKey) != nil {
|
||||
ctx.Next()
|
||||
return
|
||||
}
|
||||
ctx.Redirect(PathLogin)
|
||||
return PathLogin
|
||||
}
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
package user
|
||||
|
||||
const (
|
||||
pathMyProfile = "/user/me"
|
||||
pathRegister = "/user/register"
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/mvc"
|
||||
)
|
||||
|
||||
var (
|
||||
// About Code: iris.StatusSeeOther ->
|
||||
// When redirecting from POST to GET request you -should- use this HTTP status code,
|
||||
// however there're some (complicated) alternatives if you
|
||||
// search online or even the HTTP RFC.
|
||||
// "See Other" RFC 7231
|
||||
pathMyProfile = mvc.Response{Path: "/user/me", Code: iris.StatusSeeOther}
|
||||
pathRegister = mvc.Response{Path: "/user/register"}
|
||||
)
|
||||
|
||||
// Controller is responsible to handle the following requests:
|
||||
@@ -17,71 +27,89 @@ type Controller struct {
|
||||
AuthController
|
||||
}
|
||||
|
||||
type formValue func(string) string
|
||||
|
||||
// BeforeActivation called once before the server start
|
||||
// and before the controller's registration, here you can add
|
||||
// dependencies, to this controller and only, that the main caller may skip.
|
||||
func (c *Controller) BeforeActivation(b mvc.BeforeActivation) {
|
||||
// bind the context's `FormValue` as well in order to be
|
||||
// acceptable on the controller or its methods' input arguments (NEW feature as well).
|
||||
b.Dependencies().Add(func(ctx iris.Context) formValue { return ctx.FormValue })
|
||||
}
|
||||
|
||||
type page struct {
|
||||
Title string
|
||||
}
|
||||
|
||||
// GetRegister handles GET:/user/register.
|
||||
func (c *Controller) GetRegister() {
|
||||
// mvc.Result can accept any struct which contains a `Dispatch(ctx iris.Context)` method.
|
||||
// Both mvc.Response and mvc.View are mvc.Result.
|
||||
func (c *Controller) GetRegister() mvc.Result {
|
||||
if c.isLoggedIn() {
|
||||
c.logout()
|
||||
return
|
||||
return c.logout()
|
||||
}
|
||||
|
||||
c.Data["Title"] = "User Registration"
|
||||
c.Tmpl = pathRegister + ".html"
|
||||
// You could just use it as a variable to win some time in serve-time,
|
||||
// this is an exersise for you :)
|
||||
return mvc.View{
|
||||
Name: pathRegister.Path + ".html",
|
||||
Data: page{"User Registration"},
|
||||
}
|
||||
}
|
||||
|
||||
// PostRegister handles POST:/user/register.
|
||||
func (c *Controller) PostRegister() {
|
||||
func (c *Controller) PostRegister(form formValue) mvc.Result {
|
||||
// we can either use the `c.Ctx.ReadForm` or read values one by one.
|
||||
var (
|
||||
firstname = c.Ctx.FormValue("firstname")
|
||||
username = c.Ctx.FormValue("username")
|
||||
password = c.Ctx.FormValue("password")
|
||||
firstname = form("firstname")
|
||||
username = form("username")
|
||||
password = form("password")
|
||||
)
|
||||
|
||||
user, err := c.createOrUpdate(firstname, username, password)
|
||||
if err != nil {
|
||||
c.fireError(err)
|
||||
return
|
||||
return c.fireError(err)
|
||||
}
|
||||
|
||||
// setting a session value was never easier.
|
||||
c.Session.Set(sessionIDKey, user.ID)
|
||||
// succeed, nothing more to do here, just redirect to the /user/me.
|
||||
return pathMyProfile
|
||||
}
|
||||
|
||||
// When redirecting from POST to GET request you -should- use this HTTP status code,
|
||||
// however there're some (complicated) alternatives if you
|
||||
// search online or even the HTTP RFC.
|
||||
c.Status = 303 // "See Other" RFC 7231
|
||||
|
||||
// Redirect to GET: /user/me
|
||||
// by changing the Path (and the status code because we're in POST request at this case).
|
||||
c.Path = pathMyProfile
|
||||
// with these static views,
|
||||
// you can use variables-- that are initialized before server start
|
||||
// so you can win some time on serving.
|
||||
// You can do it else where as well but I let them as pracise for you,
|
||||
// essentialy you can understand by just looking below.
|
||||
var userLoginView = mvc.View{
|
||||
Name: PathLogin.Path + ".html",
|
||||
Data: page{"User Login"},
|
||||
}
|
||||
|
||||
// GetLogin handles GET:/user/login.
|
||||
func (c *Controller) GetLogin() {
|
||||
func (c *Controller) GetLogin() mvc.Result {
|
||||
if c.isLoggedIn() {
|
||||
c.logout()
|
||||
return
|
||||
return c.logout()
|
||||
}
|
||||
c.Data["Title"] = "User Login"
|
||||
c.Tmpl = PathLogin + ".html"
|
||||
return userLoginView
|
||||
}
|
||||
|
||||
// PostLogin handles POST:/user/login.
|
||||
func (c *Controller) PostLogin() {
|
||||
func (c *Controller) PostLogin(form formValue) mvc.Result {
|
||||
var (
|
||||
username = c.Ctx.FormValue("username")
|
||||
password = c.Ctx.FormValue("password")
|
||||
username = form("username")
|
||||
password = form("password")
|
||||
)
|
||||
|
||||
user, err := c.verify(username, password)
|
||||
if err != nil {
|
||||
c.fireError(err)
|
||||
return
|
||||
return c.fireError(err)
|
||||
}
|
||||
|
||||
c.Session.Set(sessionIDKey, user.ID)
|
||||
c.Path = pathMyProfile
|
||||
return pathMyProfile
|
||||
}
|
||||
|
||||
// AnyLogout handles any method on path /user/logout.
|
||||
@@ -90,44 +118,72 @@ func (c *Controller) AnyLogout() {
|
||||
}
|
||||
|
||||
// GetMe handles GET:/user/me.
|
||||
func (c *Controller) GetMe() {
|
||||
func (c *Controller) GetMe() mvc.Result {
|
||||
id, err := c.Session.GetInt64(sessionIDKey)
|
||||
if err != nil || id <= 0 {
|
||||
// when not already logged in.
|
||||
c.Path = PathLogin
|
||||
return
|
||||
// when not already logged in, redirect to login.
|
||||
return PathLogin
|
||||
}
|
||||
|
||||
u, found := c.Source.GetByID(id)
|
||||
if !found {
|
||||
// if the session exists but for some reason the user doesn't exist in the "database"
|
||||
// then logout him and redirect to the register page.
|
||||
c.logout()
|
||||
return
|
||||
return c.logout()
|
||||
}
|
||||
|
||||
// set the model and render the view template.
|
||||
c.User = u
|
||||
c.Data["Title"] = "Profile of " + u.Username
|
||||
c.Tmpl = pathMyProfile + ".html"
|
||||
return mvc.View{
|
||||
Name: pathMyProfile.Path + ".html",
|
||||
Data: iris.Map{
|
||||
"Title": "Profile of " + u.Username,
|
||||
"User": u,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Controller) renderNotFound(id int64) {
|
||||
c.Status = 404
|
||||
c.Data["Title"] = "User Not Found"
|
||||
c.Data["ID"] = id
|
||||
c.Tmpl = "user/notfound.html"
|
||||
func (c *Controller) renderNotFound(id int64) mvc.View {
|
||||
return mvc.View{
|
||||
Code: iris.StatusNotFound,
|
||||
Name: "user/notfound.html",
|
||||
Data: iris.Map{
|
||||
"Title": "User Not Found",
|
||||
"ID": id,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Dispatch completes the `mvc.Result` interface
|
||||
// in order to be able to return a type of `Model`
|
||||
// as mvc.Result.
|
||||
// If this function didn't exist then
|
||||
// we should explicit set the output result to that Model or to an interface{}.
|
||||
func (u Model) Dispatch(ctx iris.Context) {
|
||||
ctx.JSON(u)
|
||||
}
|
||||
|
||||
// GetBy handles GET:/user/{id:long},
|
||||
// i.e http://localhost:8080/user/1
|
||||
func (c *Controller) GetBy(userID int64) {
|
||||
func (c *Controller) GetBy(userID int64) mvc.Result {
|
||||
// we have /user/{id}
|
||||
// fetch and render user json.
|
||||
if user, found := c.Source.GetByID(userID); !found {
|
||||
user, found := c.Source.GetByID(userID)
|
||||
if !found {
|
||||
// not user found with that ID.
|
||||
c.renderNotFound(userID)
|
||||
} else {
|
||||
c.Ctx.JSON(user)
|
||||
return c.renderNotFound(userID)
|
||||
}
|
||||
|
||||
// Q: how the hell Model can be return as mvc.Result?
|
||||
// A: I told you before on some comments and the docs,
|
||||
// any struct that has a `Dispatch(ctx iris.Context)`
|
||||
// can be returned as an mvc.Result(see ~20 lines above),
|
||||
// therefore we are able to combine many type of results in the same method.
|
||||
// For example, here, we return either an mvc.View to render a not found custom template
|
||||
// either a user which returns the Model as JSON via its Dispatch.
|
||||
//
|
||||
// We could also return just a struct value that is not an mvc.Result,
|
||||
// if the output result of the `GetBy` was that struct's type or an interface{}
|
||||
// and iris would render that with JSON as well, but here we can't do that without complete the `Dispatch`
|
||||
// function, because we may return an mvc.View which is an mvc.Result.
|
||||
return user
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user