github.com/kotovmak/go-admin@v1.1.1/adapter/adapter.go (about)

     1  // Copyright 2019 GoAdmin Core Team. All rights reserved.
     2  // Use of this source code is governed by a Apache-2.0 style
     3  // license that can be found in the LICENSE file.
     4  
     5  package adapter
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"net/url"
    11  
    12  	"github.com/kotovmak/go-admin/context"
    13  	"github.com/kotovmak/go-admin/modules/auth"
    14  	"github.com/kotovmak/go-admin/modules/config"
    15  	"github.com/kotovmak/go-admin/modules/constant"
    16  	"github.com/kotovmak/go-admin/modules/db"
    17  	"github.com/kotovmak/go-admin/modules/errors"
    18  	"github.com/kotovmak/go-admin/modules/logger"
    19  	"github.com/kotovmak/go-admin/modules/menu"
    20  	"github.com/kotovmak/go-admin/plugins"
    21  	"github.com/kotovmak/go-admin/plugins/admin/models"
    22  	"github.com/kotovmak/go-admin/template"
    23  	"github.com/kotovmak/go-admin/template/types"
    24  )
    25  
    26  // WebFrameWork is an interface which is used as an adapter of
    27  // framework and goAdmin. It must implement two methods. Use registers
    28  // the routes and the corresponding handlers. Content writes the
    29  // response to the corresponding context of framework.
    30  type WebFrameWork interface {
    31  	// Name return the web framework name.
    32  	Name() string
    33  
    34  	// Use method inject the plugins to the web framework engine which is the
    35  	// first parameter.
    36  	Use(app interface{}, plugins []plugins.Plugin) error
    37  
    38  	// Content add the panel html response of the given callback function to
    39  	// the web framework context which is the first parameter.
    40  	Content(ctx interface{}, fn types.GetPanelFn, fn2 context.NodeProcessor, navButtons ...types.Button)
    41  
    42  	// User get the auth user model from the given web framework context.
    43  	User(ctx interface{}) (models.UserModel, bool)
    44  
    45  	// AddHandler inject the route and handlers of GoAdmin to the web framework.
    46  	AddHandler(method, path string, handlers context.Handlers)
    47  
    48  	DisableLog()
    49  
    50  	Static(prefix, path string)
    51  
    52  	Run() error
    53  
    54  	// Helper functions
    55  	// ================================
    56  
    57  	SetApp(app interface{}) error
    58  	SetConnection(db.Connection)
    59  	GetConnection() db.Connection
    60  	SetContext(ctx interface{}) WebFrameWork
    61  	GetCookie() (string, error)
    62  	Lang() string
    63  	Path() string
    64  	Method() string
    65  	FormParam() url.Values
    66  	Query() url.Values
    67  	IsPjax() bool
    68  	Redirect()
    69  	SetContentType()
    70  	Write(body []byte)
    71  	CookieKey() string
    72  	HTMLContentType() string
    73  }
    74  
    75  // BaseAdapter is a base adapter contains some helper functions.
    76  type BaseAdapter struct {
    77  	db db.Connection
    78  }
    79  
    80  // SetConnection set the db connection.
    81  func (base *BaseAdapter) SetConnection(conn db.Connection) {
    82  	base.db = conn
    83  }
    84  
    85  // GetConnection get the db connection.
    86  func (base *BaseAdapter) GetConnection() db.Connection {
    87  	return base.db
    88  }
    89  
    90  // HTMLContentType return the default content type header.
    91  func (*BaseAdapter) HTMLContentType() string {
    92  	return "text/html; charset=utf-8"
    93  }
    94  
    95  // CookieKey return the cookie key.
    96  func (*BaseAdapter) CookieKey() string {
    97  	return auth.DefaultCookieKey
    98  }
    99  
   100  // GetUser is a helper function get the auth user model from the context.
   101  func (*BaseAdapter) GetUser(ctx interface{}, wf WebFrameWork) (models.UserModel, bool) {
   102  	cookie, err := wf.SetContext(ctx).GetCookie()
   103  
   104  	if err != nil {
   105  		return models.UserModel{}, false
   106  	}
   107  
   108  	user, exist := auth.GetCurUser(cookie, wf.GetConnection())
   109  	return user.ReleaseConn(), exist
   110  }
   111  
   112  // GetUse is a helper function adds the plugins to the framework.
   113  func (*BaseAdapter) GetUse(app interface{}, plugin []plugins.Plugin, wf WebFrameWork) error {
   114  	if err := wf.SetApp(app); err != nil {
   115  		return err
   116  	}
   117  
   118  	for _, plug := range plugin {
   119  		for path, handlers := range plug.GetHandler() {
   120  			if plug.Prefix() == "" {
   121  				wf.AddHandler(path.Method, path.URL, handlers)
   122  			} else {
   123  				wf.AddHandler(path.Method, config.Url("/"+plug.Prefix()+path.URL), handlers)
   124  			}
   125  		}
   126  	}
   127  
   128  	return nil
   129  }
   130  
   131  func (*BaseAdapter) Run() error         { panic("not implement") }
   132  func (*BaseAdapter) DisableLog()        { panic("not implement") }
   133  func (*BaseAdapter) Static(_, _ string) { panic("not implement") }
   134  
   135  // GetContent is a helper function of adapter.Content
   136  func (base *BaseAdapter) GetContent(ctx interface{}, getPanelFn types.GetPanelFn, wf WebFrameWork,
   137  	navButtons types.Buttons, fn context.NodeProcessor) {
   138  
   139  	var (
   140  		newBase          = wf.SetContext(ctx)
   141  		cookie, hasError = newBase.GetCookie()
   142  	)
   143  
   144  	if hasError != nil || cookie == "" {
   145  		newBase.Redirect()
   146  		return
   147  	}
   148  
   149  	user, authSuccess := auth.GetCurUser(cookie, wf.GetConnection())
   150  
   151  	if !authSuccess {
   152  		newBase.Redirect()
   153  		return
   154  	}
   155  
   156  	var (
   157  		panel types.Panel
   158  		err   error
   159  	)
   160  
   161  	if !auth.CheckPermissions(user, newBase.Path(), newBase.Method(), newBase.FormParam()) {
   162  		panel = template.WarningPanel(errors.NoPermission, template.NoPermission403Page)
   163  	} else {
   164  		panel, err = getPanelFn(ctx)
   165  		if err != nil {
   166  			panel = template.WarningPanel(err.Error())
   167  		}
   168  	}
   169  
   170  	fn(panel.Callbacks...)
   171  
   172  	tmpl, tmplName := template.Default().GetTemplate(newBase.IsPjax())
   173  
   174  	buf := new(bytes.Buffer)
   175  	hasError = tmpl.ExecuteTemplate(buf, tmplName, types.NewPage(&types.NewPageParam{
   176  		User:         user,
   177  		Menu:         menu.GetGlobalMenu(user, wf.GetConnection(), newBase.Lang()).SetActiveClass(config.URLRemovePrefix(newBase.Path())),
   178  		Panel:        panel.GetContent(config.IsProductionEnvironment()),
   179  		Assets:       template.GetComponentAssetImportHTML(),
   180  		Buttons:      navButtons.CheckPermission(user),
   181  		TmplHeadHTML: template.Default().GetHeadHTML(),
   182  		TmplFootJS:   template.Default().GetFootJS(),
   183  		Iframe:       newBase.Query().Get(constant.IframeKey) == "true",
   184  	}))
   185  
   186  	if hasError != nil {
   187  		logger.Error(fmt.Sprintf("error: %s adapter content, ", newBase.Name()), hasError)
   188  	}
   189  
   190  	newBase.SetContentType()
   191  	newBase.Write(buf.Bytes())
   192  }