本文整理匯總了Golang中github.com/revel/revel.Controller類的典型用法代碼示例。如果您正苦於以下問題:Golang Controller類的具體用法?Golang Controller怎麽用?Golang Controller使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Controller類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: AuthInterceptor
func AuthInterceptor(c *revel.Controller) revel.Result {
// 全部變成首字大寫
/*
var controller = strings.Title(c.Name)
var method = strings.Title(c.MethodName)
// 是否需要驗證?
if !needValidate(controller, method) {
return nil
}
*/
// 驗證是否已登錄
// 必須是管理員
if username, ok := c.Session["Username"]; ok && username == configService.GetAdminUsername() {
return nil // 已登錄
}
// 沒有登錄, 判斷是否是ajax操作
if c.Request.Header.Get("X-Requested-With") == "XMLHttpRequest" {
re := info.NewRe()
re.Msg = "NOTLOGIN"
return c.RenderJson(re)
}
return c.Redirect("/login")
}
示例2: MSessionFilter
func MSessionFilter(c *revel.Controller, fc []revel.Filter) {
sessionId := c.Session.Id()
// 從memcache中得到cache, 賦給session
cache := revel.Session(memcache.GetMap(sessionId))
Log("memcache")
LogJ(cache)
if cache == nil {
cache = revel.Session{}
cache.Id()
}
c.Session = cache
// Make session vars available in templates as {{.session.xyz}}
c.RenderArgs["session"] = c.Session
fc[0](c, fc[1:])
// 再把session保存之
LogJ(c.Session)
memcache.SetMap(sessionId, c.Session, -1)
// 隻留下sessionId
c.Session = revel.Session{revel.SESSION_ID_KEY: sessionId}
}
示例3: AuthFilter
/*
Filter AuthFilter is Revel Filter for JWT Auth Token verification
Register it in the revel.Filters in <APP_PATH>/app/init.go
Add jwt.AuthFilter anywhere deemed appropriate, it must be register after revel.PanicFilter
revel.Filters = []revel.Filter{
revel.PanicFilter,
...
jwt.AuthFilter, // JWT Auth Token verification for Request Paths
...
}
Note: If everything looks good then Claims map made available via c.Args
and can be accessed using c.Args[jwt.TOKEN_CLAIMS_KEY]
*/
func AuthFilter(c *revel.Controller, fc []revel.Filter) {
if !anonymousPaths.MatchString(c.Request.URL.Path) {
token, err := ParseFromRequest(c.Request.Request)
if err == nil && token.Valid && !IsInBlocklist(GetAuthToken(c.Request)) {
c.Args[TOKEN_CLAIMS_KEY] = token.Claims
fc[0](c, fc[1:]) // everything looks good, move on
} else {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
revel.ERROR.Println("That's not even a token")
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
revel.ERROR.Println("Timing is everything, Token is either expired or not active yet")
} else {
revel.ERROR.Printf("Couldn't handle this token: %v", err)
}
} else {
revel.ERROR.Printf("Couldn't handle this token: %v", err)
}
c.Response.Status = http.StatusUnauthorized
c.Response.Out.Header().Add("WWW-Authenticate", Realm)
c.Result = c.RenderJson(map[string]string{
"id": "unauthorized",
"message": "Invalid or token is not provided",
})
return
}
}
fc[0](c, fc[1:]) //not applying JWT auth filter due to anonymous path
}
示例4: CheckUserAuth
func CheckUserAuth(controller *revel.Controller) revel.Result {
if controller.Action == "Static.Serve" ||
controller.Action == "App.Login" ||
controller.Action == "User.Login" ||
controller.Action == "User.Logout" {
return nil
}
var (
userAuth = new(security.UserAuth)
username string
sessionData = *security.GetSessionData(&controller.Session)
)
security.AuthCache.Get(controller.Session.Id(), userAuth)
if v, ok := sessionData["username"]; ok {
username = v.(string)
}
if userAuth != nil && username != "" && userAuth.Equal(security.UserAuthGenerate(controller.Request)) {
return nil
}
controller.Flash.Error("Please log in first")
controller.Response.Out.Header().Set("Requires-Auth", "1")
// controller.Response.Status = 401
return controller.Redirect((*User).Login)
}
示例5: adminOnly
func adminOnly(c *revel.Controller) revel.Result {
if c.Session["usertype"] == "ADMIN" {
return nil
}
c.Flash.Error(c.Message("access.message.notallowed"))
return c.Redirect(routes.App.Index())
}
示例6: checkUser
func checkUser(c *revel.Controller) revel.Result {
if _, ok := c.Session["user"]; ok {
return nil
}
c.Flash.Error(c.Message("login.message.notloggedin"))
return c.Redirect(routes.App.Login())
}
示例7: CheckLoginAdmin
func CheckLoginAdmin(c *revel.Controller) revel.Result {
if c.Session[LOGIN_USERID] == "" || models.Role(c.Session[LOGIN_USERROLE]) != models.ROLE_SUPER_ADMIN {
return c.Redirect(
revel.MainRouter.Reverse("Auth.Login", map[string]string{}).Url,
)
}
return nil
}
示例8: CheckLogin
// func init() {
// revel.InterceptFunc(CheckLogin, revel.BEFORE, &App{})
// }
func CheckLogin(c *revel.Controller) revel.Result {
if c.Session[LOGIN_USERID] == "" {
return c.Redirect(
revel.MainRouter.Reverse("Auth.Login", map[string]string{}).Url,
)
}
return nil
}
示例9: Search
// search certain content
func Search(key string, c *revel.Controller) revel.Result {
var problems []models.Problem
err := engine.Where("title = ? ", key).Find(&problems)
if err != nil {
c.Flash.Error("error %s", err.Error())
c.Redirect(routes.Notice.Crash())
}
return c.Render(problems)
}
示例10: redirectAuthenticationPageForAdmin
func redirectAuthenticationPageForAdmin(c *revel.Controller) revel.Result {
uidStr := c.Session["uid"]
uid, _ := strconv.Atoi(uidStr)
errorPage := c.RenderTemplate("errors/401.html")
if len(uidStr) == 0 {
return errorPage
}
if (models.User{}.FetchUserByUserId(uint(uid)).Status != models.UserAdmin) {
return errorPage
}
return nil
}
示例11: checkDataTypeParam
func checkDataTypeParam(c *revel.Controller) revel.Result {
dataType, ok := c.Params.Values["dataType"]
if ok && dataType[0] != "" {
if _, ok := database.SynchronizationTypes[dataType[0]]; !ok {
c.Response.Status = 400
return c.RenderJson("wrong dataType attribute")
}
return nil
}
c.Response.Status = 400
return c.RenderJson("mandatory parameter dataType is not present")
}
示例12: returnMessage
func returnMessage(c *revel.Controller, message interface{}, err error) revel.Result {
result := &opResult{}
if err != nil {
result.Result = Error
result.Message = err.Error()
revel.WARN.Fatalln(err)
} else {
result.Result = Success
result.Message = message
}
return c.RenderJson(result)
}
示例13: ServeStatic
func ServeStatic(uri, contentType string, c *revel.Controller) {
filePath := GetFilePath(uri)
revel.INFO.Printf("read static file %s\n", filePath)
file, err := os.Open(filePath)
defer file.Close()
if err != nil {
c.Result = CommonResult{Data: []byte(`sorry file not found`)}
return
}
data, err := ioutil.ReadAll(file)
if err != nil {
c.Result = CommonResult{Data: []byte(`sorry file not found`)}
return
}
c.Result = CommonResult{Data: data, ContentType: contentType}
}
示例14: authenticate
//authentication check
func authenticate(c *revel.Controller) revel.Result {
if inStringSlice(strings.ToLower(c.Action),
adminPermission) {
if !adminAuthentication(c) {
c.Flash.Error("you are not admin")
return c.Redirect("/")
}
}
if inStringSlice(strings.ToLower(c.Action),
userPermission) {
if ok := connected(c); !ok {
c.Flash.Error("please login first")
return c.Redirect(routes.Account.Login())
} else {
return nil
}
}
if inStringSlice(strings.ToLower(c.Action),
logoutCheck) {
if ok := connected(c); ok {
c.Flash.Error("can not repeat login")
return c.Redirect("/")
} else {
return nil
}
}
return nil
}
示例15: CheckLogin
//檢測登陸
func CheckLogin(c *revel.Controller) revel.Result {
//登陸頁麵,CSS, JS, Ajax, 驗證碼頁麵 都不進行登陸驗證
if c.Name == "User" && c.MethodName == "Login" || c.Name == "Ajax" || c.Name == "Static" || c.Name == "Captcha" || c.Name == "Kindeditor" {
if LANG, ok := c.Session["Lang"]; ok {
//設置語言
c.RenderArgs["currentLocale"] = LANG
} else {
//設置默認語言
c.RenderArgs["currentLocale"] = "zh"
}
return nil
} else {
UserID := utils.GetSession("UserID", c.Session)
if len(UserID) > 0 {
UserID, err := strconv.ParseInt(UserID, 10, 64)
if err != nil {
revel.WARN.Println(err)
return c.Redirect("/Login/")
}
admin := new(models.Admin)
admin_info := admin.GetById(UserID)
if admin_info.Id <= 0 {
return c.Redirect("/Login/")
}
//控製器
c.RenderArgs["Controller"] = c.Name
//動作
c.RenderArgs["action"] = c.Action
//模型
c.RenderArgs["Model"] = c.MethodName
//登陸信息
c.RenderArgs["admin_info"] = admin_info
//設置語言
c.RenderArgs["currentLocale"] = admin_info.Lang
} else {
//控製器
c.RenderArgs["Controller"] = c.Name
//動作
c.RenderArgs["action"] = c.Action
//模型
c.RenderArgs["Model"] = c.MethodName
return c.Redirect("/Login/")
}
}
return nil
}