controller.go 13.6 KB
Newer Older
A
#2  
astaxie 已提交
1 2 3 4
package beego

import (
	"bytes"
A
astaxie 已提交
5
	"crypto/hmac"
6
	"crypto/rand"
A
astaxie 已提交
7 8
	"crypto/sha1"
	"encoding/base64"
A
astaxie 已提交
9
	"errors"
A
astaxie 已提交
10
	"fmt"
A
#2  
astaxie 已提交
11
	"html/template"
A
astaxie 已提交
12
	"io"
A
#2  
astaxie 已提交
13
	"io/ioutil"
A
astaxie 已提交
14
	"mime/multipart"
A
#2  
astaxie 已提交
15 16
	"net/http"
	"net/url"
A
astaxie 已提交
17
	"os"
A
astaxie 已提交
18
	"reflect"
A
#2  
astaxie 已提交
19
	"strconv"
A
astaxie 已提交
20
	"strings"
A
astaxie 已提交
21
	"time"
A
astaxie 已提交
22 23 24

	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/session"
A
#2  
astaxie 已提交
25 26
)

A
astaxie 已提交
27
var (
28
	// custom error when user stop request handler manually.
A
astaxie 已提交
29 30 31
	USERSTOPRUN = errors.New("User stop run")
)

32 33
// Controller defines some basic http request handler operations, such as
// http context, template and view, session and xsrf.
A
#2  
astaxie 已提交
34
type Controller struct {
35 36 37 38 39 40
	Ctx            *context.Context
	Data           map[interface{}]interface{}
	controllerName string
	actionName     string
	TplNames       string
	Layout         string
41
	LayoutSections map[string]string // the key is the section name and the value is the template name
42 43 44 45 46 47
	TplExt         string
	_xsrf_token    string
	gotofunc       string
	CruSession     session.SessionStore
	XSRFExpire     int
	AppController  interface{}
A
#2  
astaxie 已提交
48 49
}

50
// ControllerInterface is an interface to uniform all controller handler.
A
#2  
astaxie 已提交
51
type ControllerInterface interface {
52
	Init(ct *context.Context, controllerName, actionName string, app interface{})
A
#2  
astaxie 已提交
53 54 55 56 57 58 59 60 61 62
	Prepare()
	Get()
	Post()
	Delete()
	Put()
	Head()
	Patch()
	Options()
	Finish()
	Render() error
63 64
	XsrfToken() string
	CheckXsrfCookie() bool
A
#2  
astaxie 已提交
65 66
}

67
// Init generates default values of controller operations.
68
func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{}) {
A
#2  
astaxie 已提交
69 70 71
	c.Data = make(map[interface{}]interface{})
	c.Layout = ""
	c.TplNames = ""
72 73
	c.controllerName = controllerName
	c.actionName = actionName
A
#2  
astaxie 已提交
74 75
	c.Ctx = ctx
	c.TplExt = "tpl"
A
astaxie 已提交
76
	c.AppController = app
A
#2  
astaxie 已提交
77 78
}

79
// Prepare runs after Init before request function execution.
A
#2  
astaxie 已提交
80 81 82 83
func (c *Controller) Prepare() {

}

84
// Finish runs after request function execution.
A
#2  
astaxie 已提交
85
func (c *Controller) Finish() {
A
astaxie 已提交
86 87 88

}

89
// Get adds a request function to handle GET request.
A
#2  
astaxie 已提交
90 91 92 93
func (c *Controller) Get() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

94
// Post adds a request function to handle POST request.
A
#2  
astaxie 已提交
95 96 97 98
func (c *Controller) Post() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

99
// Delete adds a request function to handle DELETE request.
A
#2  
astaxie 已提交
100 101 102 103
func (c *Controller) Delete() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

104
// Put adds a request function to handle PUT request.
A
#2  
astaxie 已提交
105 106 107 108
func (c *Controller) Put() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

109
// Head adds a request function to handle HEAD request.
A
#2  
astaxie 已提交
110 111 112 113
func (c *Controller) Head() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

114
// Patch adds a request function to handle PATCH request.
A
#2  
astaxie 已提交
115 116 117 118
func (c *Controller) Patch() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

119
// Options adds a request function to handle OPTIONS request.
A
#2  
astaxie 已提交
120 121 122 123
func (c *Controller) Options() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

124
// Render sends the response with rendered template bytes as text/html type.
A
#2  
astaxie 已提交
125
func (c *Controller) Render() error {
A
astaxie 已提交
126 127 128 129 130
	rb, err := c.RenderBytes()

	if err != nil {
		return err
	} else {
A
astaxie 已提交
131 132
		c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
		c.Ctx.Output.Body(rb)
A
astaxie 已提交
133 134 135 136
	}
	return nil
}

137
// RenderString returns the rendered template string. Do not send out response.
A
astaxie 已提交
138 139 140 141 142
func (c *Controller) RenderString() (string, error) {
	b, e := c.RenderBytes()
	return string(b), e
}

傅小黑 已提交
143
// RenderBytes returns the bytes of rendered template string. Do not send out response.
A
astaxie 已提交
144
func (c *Controller) RenderBytes() ([]byte, error) {
A
#2  
astaxie 已提交
145 146 147
	//if the controller has set layout, then first get the tplname's content set the content to the layout
	if c.Layout != "" {
		if c.TplNames == "" {
傅小黑 已提交
148
			c.TplNames = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
A
#2  
astaxie 已提交
149
		}
150
		if RunMode == "dev" {
A
astaxie 已提交
151
			BuildTemplate(ViewsPath)
152
		}
A
#2  
astaxie 已提交
153
		newbytes := bytes.NewBufferString("")
A
astaxie 已提交
154
		if _, ok := BeeTemplates[c.TplNames]; !ok {
傅小黑 已提交
155 156
			panic("can't find templatefile in the path:" + c.TplNames)
			return []byte{}, errors.New("can't find templatefile in the path:" + c.TplNames)
A
astaxie 已提交
157
		}
A
astaxie 已提交
158
		err := BeeTemplates[c.TplNames].ExecuteTemplate(newbytes, c.TplNames, c.Data)
A
astaxie 已提交
159
		if err != nil {
A
astaxie 已提交
160
			Trace("template Execute err:", err)
161
			return nil, err
A
astaxie 已提交
162
		}
A
#2  
astaxie 已提交
163 164
		tplcontent, _ := ioutil.ReadAll(newbytes)
		c.Data["LayoutContent"] = template.HTML(string(tplcontent))
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183

		if c.LayoutSections != nil {
			for sectionName, sectionTpl := range c.LayoutSections {
				if (sectionTpl == "") {
					c.Data[sectionName] = ""
					continue
				}

				sectionBytes := bytes.NewBufferString("")
				err = BeeTemplates[sectionTpl].ExecuteTemplate(sectionBytes, sectionTpl, c.Data)
				if err != nil {
					Trace("template Execute err:", err)
					return nil, err
				}
				sectionContent, _ := ioutil.ReadAll(sectionBytes)
				c.Data[sectionName] = template.HTML(string(sectionContent))
			}
		}

A
astaxie 已提交
184
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
185
		err = BeeTemplates[c.Layout].ExecuteTemplate(ibytes, c.Layout, c.Data)
A
#2  
astaxie 已提交
186 187
		if err != nil {
			Trace("template Execute err:", err)
188
			return nil, err
A
#2  
astaxie 已提交
189
		}
A
astaxie 已提交
190 191
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
192 193
	} else {
		if c.TplNames == "" {
傅小黑 已提交
194
			c.TplNames = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
A
#2  
astaxie 已提交
195
		}
196
		if RunMode == "dev" {
A
astaxie 已提交
197
			BuildTemplate(ViewsPath)
198
		}
A
astaxie 已提交
199
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
200
		if _, ok := BeeTemplates[c.TplNames]; !ok {
傅小黑 已提交
201 202
			panic("can't find templatefile in the path:" + c.TplNames)
			return []byte{}, errors.New("can't find templatefile in the path:" + c.TplNames)
A
astaxie 已提交
203
		}
A
astaxie 已提交
204
		err := BeeTemplates[c.TplNames].ExecuteTemplate(ibytes, c.TplNames, c.Data)
A
#2  
astaxie 已提交
205
		if err != nil {
A
astaxie 已提交
206
			Trace("template Execute err:", err)
207
			return nil, err
A
#2  
astaxie 已提交
208
		}
A
astaxie 已提交
209 210
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
211
	}
A
astaxie 已提交
212
	return []byte{}, nil
A
#2  
astaxie 已提交
213 214
}

215
// Redirect sends the redirection response to url with status code.
A
#2  
astaxie 已提交
216 217 218 219
func (c *Controller) Redirect(url string, code int) {
	c.Ctx.Redirect(code, url)
}

220
// Aborts stops controller handler and show the error data if code is defined in ErrorMap or code string.
A
fix #16  
astaxie 已提交
221
func (c *Controller) Abort(code string) {
222 223 224 225 226 227 228 229
	status, err := strconv.Atoi(code)
	if err == nil {
		c.Ctx.Abort(status, code)
	} else {
		c.Ctx.Abort(200, code)
	}
}

230
// StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
231
func (c *Controller) StopRun() {
A
astaxie 已提交
232
	panic(USERSTOPRUN)
A
fix #16  
astaxie 已提交
233 234
}

235 236
// UrlFor does another controller handler in this request function.
// it goes to this controller method if endpoint is not clear.
A
astaxie 已提交
237 238 239 240 241
func (c *Controller) UrlFor(endpoint string, values ...string) string {
	if len(endpoint) <= 0 {
		return ""
	}
	if endpoint[0] == '.' {
傅小黑 已提交
242
		return UrlFor(reflect.Indirect(reflect.ValueOf(c.AppController)).Type().Name()+endpoint, values...)
A
astaxie 已提交
243 244 245
	} else {
		return UrlFor(endpoint, values...)
	}
246
	return ""
A
astaxie 已提交
247 248
}

249
// ServeJson sends a json response with encoding charset.
A
astaxie 已提交
250
func (c *Controller) ServeJson(encoding ...bool) {
A
astaxie 已提交
251 252
	var hasIndent bool
	var hasencoding bool
253
	if RunMode == "prod" {
A
astaxie 已提交
254
		hasIndent = false
255
	} else {
A
astaxie 已提交
256
		hasIndent = true
257
	}
A
astaxie 已提交
258
	if len(encoding) > 0 && encoding[0] == true {
A
astaxie 已提交
259
		hasencoding = true
A
astaxie 已提交
260
	}
A
astaxie 已提交
261
	c.Ctx.Output.Json(c.Data["json"], hasIndent, hasencoding)
A
#2  
astaxie 已提交
262 263
}

傅小黑 已提交
264
// ServeJsonp sends a jsonp response.
L
lw 已提交
265
func (c *Controller) ServeJsonp() {
A
astaxie 已提交
266
	var hasIndent bool
267
	if RunMode == "prod" {
A
astaxie 已提交
268
		hasIndent = false
269
	} else {
A
astaxie 已提交
270
		hasIndent = true
L
lw 已提交
271
	}
A
astaxie 已提交
272
	c.Ctx.Output.Jsonp(c.Data["jsonp"], hasIndent)
L
lw 已提交
273 274
}

傅小黑 已提交
275
// ServeXml sends xml response.
A
#2  
astaxie 已提交
276
func (c *Controller) ServeXml() {
A
astaxie 已提交
277
	var hasIndent bool
278
	if RunMode == "prod" {
A
astaxie 已提交
279
		hasIndent = false
280
	} else {
A
astaxie 已提交
281
		hasIndent = true
282
	}
A
astaxie 已提交
283
	c.Ctx.Output.Xml(c.Data["xml"], hasIndent)
A
#2  
astaxie 已提交
284 285
}

286
// Input returns the input data map from POST or PUT request body and query string.
A
#2  
astaxie 已提交
287
func (c *Controller) Input() url.Values {
288
	ct := c.Ctx.Request.Header.Get("Content-Type")
A
astaxie 已提交
289
	if strings.Contains(ct, "multipart/form-data") {
290 291 292 293
		c.Ctx.Request.ParseMultipartForm(MaxMemory) //64MB
	} else {
		c.Ctx.Request.ParseForm()
	}
A
#2  
astaxie 已提交
294 295
	return c.Ctx.Request.Form
}
X
xiemengjun 已提交
296

297
// ParseForm maps input data map to obj struct.
298 299 300 301
func (c *Controller) ParseForm(obj interface{}) error {
	return ParseForm(c.Input(), obj)
}

302
// GetString returns the input value by key string.
303 304 305 306
func (c *Controller) GetString(key string) string {
	return c.Input().Get(key)
}

307 308
// GetStrings returns the input string slice by key string.
// it's designed for multi-value input field such as checkbox(input[type=checkbox]), multi-selection.
Y
yecrane 已提交
309
func (c *Controller) GetStrings(key string) []string {
A
fix #87  
astaxie 已提交
310 311
	r := c.Ctx.Request
	if r.Form == nil {
Y
yecrane 已提交
312 313
		return []string{}
	}
A
fix #87  
astaxie 已提交
314 315 316 317 318
	vs := r.Form[key]
	if len(vs) > 0 {
		return vs
	}
	return []string{}
Y
yecrane 已提交
319 320
}

321
// GetInt returns input value as int64.
322 323 324 325
func (c *Controller) GetInt(key string) (int64, error) {
	return strconv.ParseInt(c.Input().Get(key), 10, 64)
}

326
// GetBool returns input value as bool.
327 328 329 330
func (c *Controller) GetBool(key string) (bool, error) {
	return strconv.ParseBool(c.Input().Get(key))
}

331
// GetFloat returns input value as float64.
A
astaxie 已提交
332 333 334 335
func (c *Controller) GetFloat(key string) (float64, error) {
	return strconv.ParseFloat(c.Input().Get(key), 64)
}

336 337
// GetFile returns the file data in file upload field named as key.
// it returns the first one of multi-uploaded files.
A
astaxie 已提交
338 339 340 341
func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error) {
	return c.Ctx.Request.FormFile(key)
}

342 343
// SaveToFile saves uploaded file to new path.
// it only operates the first one of mutil-upload form file field.
A
astaxie 已提交
344 345 346 347 348 349
func (c *Controller) SaveToFile(fromfile, tofile string) error {
	file, _, err := c.Ctx.Request.FormFile(fromfile)
	if err != nil {
		return err
	}
	defer file.Close()
傅小黑 已提交
350
	f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
A
astaxie 已提交
351 352 353 354 355 356 357 358
	if err != nil {
		return err
	}
	defer f.Close()
	io.Copy(f, file)
	return nil
}

359
// StartSession starts session and load old session data info this controller.
A
astaxie 已提交
360 361
func (c *Controller) StartSession() session.SessionStore {
	if c.CruSession == nil {
362
		c.CruSession = c.Ctx.Input.CruSession
A
astaxie 已提交
363 364
	}
	return c.CruSession
X
xiemengjun 已提交
365
}
A
session  
astaxie 已提交
366

367
// SetSession puts value into session.
368
func (c *Controller) SetSession(name interface{}, value interface{}) {
A
astaxie 已提交
369 370 371 372
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Set(name, value)
A
session  
astaxie 已提交
373 374
}

375
// GetSession gets value from session.
376
func (c *Controller) GetSession(name interface{}) interface{} {
A
astaxie 已提交
377 378 379 380
	if c.CruSession == nil {
		c.StartSession()
	}
	return c.CruSession.Get(name)
A
session  
astaxie 已提交
381 382
}

383
// SetSession removes value from session.
384
func (c *Controller) DelSession(name interface{}) {
A
astaxie 已提交
385 386 387 388
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Delete(name)
A
session  
astaxie 已提交
389
}
A
fix #87  
astaxie 已提交
390

391 392
// SessionRegenerateID regenerates session id for this session.
// the session data have no changes.
393 394 395 396 397
func (c *Controller) SessionRegenerateID() {
	c.CruSession = GlobalSessions.SessionRegenerateId(c.Ctx.ResponseWriter, c.Ctx.Request)
	c.Ctx.Input.CruSession = c.CruSession
}

398
// DestroySession cleans session data and session cookie.
A
astaxie 已提交
399 400 401 402
func (c *Controller) DestroySession() {
	GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request)
}

403
// IsAjax returns this request is ajax or not.
A
fix #87  
astaxie 已提交
404
func (c *Controller) IsAjax() bool {
A
astaxie 已提交
405
	return c.Ctx.Input.IsAjax()
A
fix #87  
astaxie 已提交
406
}
A
astaxie 已提交
407

408
// GetSecureCookie returns decoded cookie value from encoded browser cookie values.
409 410 411 412 413 414 415 416
func (c *Controller) GetSecureCookie(Secret, key string) (string, bool) {
	val := c.Ctx.GetCookie(key)
	if val == "" {
		return "", false
	}

	parts := strings.SplitN(val, "|", 3)

A
astaxie 已提交
417 418 419 420
	if len(parts) != 3 {
		return "", false
	}

421 422 423 424 425 426 427 428 429 430
	vs := parts[0]
	timestamp := parts[1]
	sig := parts[2]

	h := hmac.New(sha1.New, []byte(Secret))
	fmt.Fprintf(h, "%s%s", vs, timestamp)

	if fmt.Sprintf("%02x", h.Sum(nil)) != sig {
		return "", false
	}
A
astaxie 已提交
431
	res, _ := base64.URLEncoding.DecodeString(vs)
432 433 434
	return string(res), true
}

435
// SetSecureCookie puts value into cookie after encoded the value.
A
astaxie 已提交
436
func (c *Controller) SetSecureCookie(Secret, name, val string, age int64) {
437 438 439 440 441 442 443 444 445
	vs := base64.URLEncoding.EncodeToString([]byte(val))
	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	h := hmac.New(sha1.New, []byte(Secret))
	fmt.Fprintf(h, "%s%s", vs, timestamp)
	sig := fmt.Sprintf("%02x", h.Sum(nil))
	cookie := strings.Join([]string{vs, timestamp, sig}, "|")
	c.Ctx.SetCookie(name, cookie, age, "/")
}

446
// XsrfToken creates a xsrf token string and returns.
A
astaxie 已提交
447 448
func (c *Controller) XsrfToken() string {
	if c._xsrf_token == "" {
449 450
		token, ok := c.GetSecureCookie(XSRFKEY, "_xsrf")
		if !ok {
A
astaxie 已提交
451
			var expire int64
A
astaxie 已提交
452
			if c.XSRFExpire > 0 {
A
astaxie 已提交
453
				expire = int64(c.XSRFExpire)
A
astaxie 已提交
454
			} else {
A
astaxie 已提交
455
				expire = int64(XSRFExpire)
A
astaxie 已提交
456
			}
457
			token = getRandomString(15)
458
			c.SetSecureCookie(XSRFKEY, "_xsrf", token, expire)
A
astaxie 已提交
459 460 461 462 463 464
		}
		c._xsrf_token = token
	}
	return c._xsrf_token
}

465 466 467
// CheckXsrfCookie checks xsrf token in this request is valid or not.
// the token can provided in request header "X-Xsrftoken" and "X-CsrfToken"
// or in form field value named as "_xsrf".
A
astaxie 已提交
468 469 470 471 472 473 474 475 476 477
func (c *Controller) CheckXsrfCookie() bool {
	token := c.GetString("_xsrf")
	if token == "" {
		token = c.Ctx.Request.Header.Get("X-Xsrftoken")
	}
	if token == "" {
		token = c.Ctx.Request.Header.Get("X-Csrftoken")
	}
	if token == "" {
		c.Ctx.Abort(403, "'_xsrf' argument missing from POST")
A
astaxie 已提交
478
	} else if c._xsrf_token != token {
A
astaxie 已提交
479 480 481 482 483
		c.Ctx.Abort(403, "XSRF cookie does not match POST argument")
	}
	return true
}

484
// XsrfFormHtml writes an input field contains xsrf token value.
A
astaxie 已提交
485 486
func (c *Controller) XsrfFormHtml() string {
	return "<input type=\"hidden\" name=\"_xsrf\" value=\"" +
傅小黑 已提交
487
		c._xsrf_token + "\"/>"
A
astaxie 已提交
488
}
A
fix #18  
astaxie 已提交
489

490
// GetControllerAndAction gets the executing controller name and action name.
491 492
func (c *Controller) GetControllerAndAction() (controllerName, actionName string) {
	return c.controllerName, c.actionName
A
fix #18  
astaxie 已提交
493
}
494

495
// getRandomString returns random string.
496 497 498 499 500 501 502 503 504
func getRandomString(n int) string {
	const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	var bytes = make([]byte, n)
	rand.Read(bytes)
	for i, b := range bytes {
		bytes[i] = alphanum[b%byte(len(alphanum))]
	}
	return string(bytes)
}