Exemple #1
0
func ViewLogin(c *context.Context) {
	cookie := c.GetCookie("MtimeCIUserId")
	if len(cookie) <= 0 {
		c.Redirect(302, "/login?url="+url.QueryEscape(c.Input.Uri()))
	}
	beego.Informational(cookie)
}
Exemple #2
0
func HandleAccess(ctx *context.Context) {
	token := ctx.GetCookie("epic_user_token")
	ok, _ := tools.VerifyToken(token)
	if len(token) != 0 && ok {
		ctx.Redirect(302, "/succeed")
	}
}
Exemple #3
0
func LoginUserFromRememberCookie(user *models.User, ctx *context.Context) (success bool) {
	userName := ctx.GetCookie(setting.CookieUserName)
	if len(userName) == 0 {
		return false
	}

	defer func() {
		if !success {
			DeleteRememberCookie(ctx)
		}
	}()

	user.UserName = userName
	if err := user.Read("UserName"); err != nil {
		return false
	}

	secret := utils.EncodeMd5(user.Rands + user.Password)
	value, _ := ctx.GetSecureCookie(secret, setting.CookieRememberName)
	if value != userName {
		return false
	}

	LoginUser(user, ctx, true)

	return true
}
Exemple #4
0
func FilterUser(ctx *context.Context) {
	if (ctx.Input.IsGet() || ctx.Input.IsPost()) && (ctx.Input.URL() == loginPageURL || ctx.Input.URL() == logoutPageURL) {
		// Don't redirect itself to prevent the circle
	} else {
		user, ok := ctx.Input.Session("user").(*rbac.User)

		if ok == false {
			if guiMessage := guimessagedisplay.GetGUIMessageFromContext(ctx); guiMessage != nil {
				guiMessage.AddDanger("Unauthorized")
			}
			ctx.Redirect(302, loginPageURL)
		} else {
			// Authorize
			if user.HasPermission(componentName, ctx.Input.Method(), ctx.Input.URL()) == false {
				if guiMessage := guimessagedisplay.GetGUIMessageFromContext(ctx); guiMessage != nil {
					guiMessage.AddDanger("User is not authorized to this page. Please use another user with priviledge.")
				}
				ctx.Redirect(302, loginPageURL)
			}

			// Resource check is in another place since GUI doesn't place the resource name in url

			// Audit log
			go func() {
				sendAuditLog(ctx, user.Name, true)
			}()
		}
	}
}
Exemple #5
0
func (this *BaseController) LoginUserFromRememberCookie(u *user.User, ctx *context.Context) (success bool) {
	userName := ctx.GetCookie(setting.CookieUsername)
	if len(userName) == 0 {
		return false
	}

	defer func() {
		if !success {
			this.DeleteRememberCookie(ctx)
		}
	}()
	u.Username = userName
	if err := this.UserService.Read(u, "Username"); err != nil {
		return false
	}

	secret := utils.EncodeMd5(u.PasswordSalt + u.Password)
	value, _ := ctx.GetSecureCookie(secret, setting.CookieRememberName)
	if value != userName {
		return false
	}

	this.LoginUserRememberCookie(u, ctx, true)

	return true
}
Exemple #6
0
// Handler beego filter handler for serve captcha image
func (c *Captcha) Handler(ctx *context.Context) {
	var chars []byte

	id := path.Base(ctx.Request.RequestURI)
	if i := strings.Index(id, "."); i != -1 {
		id = id[:i]
	}

	key := c.key(id)

	if len(ctx.Input.Query("reload")) > 0 {
		chars = c.genRandChars()
		if err := c.store.Put(key, chars, c.Expiration); err != nil {
			ctx.Output.SetStatus(500)
			ctx.WriteString("captcha reload error")
			beego.Error("Reload Create Captcha Error:", err)
			return
		}
	} else {
		if v, ok := c.store.Get(key).([]byte); ok {
			chars = v
		} else {
			ctx.Output.SetStatus(404)
			ctx.WriteString("captcha not found")
			return
		}
	}

	img := NewImage(chars, c.StdWidth, c.StdHeight)
	if _, err := img.WriteTo(ctx.ResponseWriter); err != nil {
		beego.Error("Write Captcha Image Error:", err)
	}
}
Exemple #7
0
// Render takes a Beego context, template name and a Context (map[string]interface{}).
// The template is parsed and cached, and gets executed into beegoCtx's ResponseWriter.
//
// Templates are looked up in `templates/` instead of Beego's default `views/` so that
// Beego doesn't attempt to load and parse our templates with `html/template`.
func Render(beegoCtx *context.Context, tmpl string, ctx Context) error {
	template, err := p2.FromCache(path.Join(templateDir, tmpl))
	if err != nil {
		panic(err)
	}

	var pCtx p2.Context
	if ctx == nil {
		pCtx = p2.Context{}
	} else {
		pCtx = p2.Context(ctx)
	}

	if xsrf, ok := beegoCtx.GetSecureCookie(beego.BConfig.WebConfig.XSRFKey, "_xsrf"); ok {
		pCtx["_xsrf"] = xsrf
	}

	// Only override "flash" if it hasn't already been set in Context
	if _, ok := ctx["flash"]; !ok {
		if ctx == nil {
			ctx = Context{}
		}
		ctx["flash"] = readFlash(beegoCtx)
	}

	return template.ExecuteWriter(pCtx, beegoCtx.ResponseWriter)
}
// 检测登录,跳转登录界面
func checkLogin(c *context.Context) {
	uid, ok := c.Input.Session("uid").(int64)
	if !ok || uid <= 0 {
		if c.Request.RequestURI != "/login" {
			c.Redirect(302, "/login")
		}
	}
}
Exemple #9
0
func (p *ControllerRegistor) recoverPanic(context *beecontext.Context) {
	if err := recover(); err != nil {
		if err == USERSTOPRUN {
			return
		}
		if RunMode == "dev" {
			if !RecoverPanic {
				panic(err)
			} else {
				if ErrorsShow {
					if handler, ok := ErrorMaps[fmt.Sprint(err)]; ok {
						executeError(handler, context)
						return
					}
				}
				var stack string
				Critical("the request url is ", context.Input.Url())
				Critical("Handler crashed with error", err)
				for i := 1; ; i++ {
					_, file, line, ok := runtime.Caller(i)
					if !ok {
						break
					}
					Critical(fmt.Sprintf("%s:%d", file, line))
					stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d", file, line))
				}
				showErr(err, context, stack)
			}
		} else {
			if !RecoverPanic {
				panic(err)
			} else {
				// in production model show all infomation
				if ErrorsShow {
					if handler, ok := ErrorMaps[fmt.Sprint(err)]; ok {
						executeError(handler, context)
						return
					} else if handler, ok := ErrorMaps["503"]; ok {
						executeError(handler, context)
						return
					} else {
						context.WriteString(fmt.Sprint(err))
					}
				} else {
					Critical("the request url is ", context.Input.Url())
					Critical("Handler crashed with error", err)
					for i := 1; ; i++ {
						_, file, line, ok := runtime.Caller(i)
						if !ok {
							break
						}
						Critical(fmt.Sprintf("%s:%d", file, line))
					}
				}
			}
		}
	}
}
Exemple #10
0
// FilterAuth prevents the user from accessing protected pages if they are not
// logged in.
func FilterAuth(ctx *context.Context) {
	if ctx.Input.GetData("user") == nil {
		ctx.Redirect(302, fmt.Sprintf(
			"%s?redirect=%s",
			beego.URLFor("UserController.Login"),
			url.QueryEscape(ctx.Request.URL.Path),
		))
	}
}
Exemple #11
0
// get login redirect url from cookie
func GetLoginRedirect(ctx *context.Context) string {
	loginRedirect := strings.TrimSpace(ctx.GetCookie("login_to"))
	if utils.IsMatchHost(loginRedirect) == false {
		loginRedirect = "/"
	} else {
		ctx.SetCookie("login_to", "", -1, "/")
	}
	return loginRedirect
}
Exemple #12
0
func IsLogin(ctx *context.Context) bool {
	username := ctx.GetCookie("username")
	password := ctx.GetCookie("password")
	if beego.AppConfig.String("username") == username &&
		beego.AppConfig.String("password") == password {
		return true
	}
	return false
}
Exemple #13
0
func WriteJson(ctx *context.Context, i interface{}) error {
	data, err := json.Marshal(i)
	if err != nil {
		fmt.Println(err)
		return err
	}
	ctx.WriteString(string(data))
	return nil
}
Exemple #14
0
func (me *StatusCode) Write(ctx *context.Context, code EUmsError, err error) {
	me.Code = int(code)

	j, _ := json.Marshal(me)

	ctx.WriteString(string(j))

	beego.Info(string(j), code.ToString(), err)
}
func loginFilter(ctx *context.Context) {

	user := ctx.Input.CruSession.Get("user")
	//user := this.GetSession("user")
	fmt.Println("loginFilter user")
	fmt.Println(user)
	if user == nil && ctx.Request.RequestURI != "/" && ctx.Request.RequestURI != "/login" {
		ctx.Redirect(302, "/")
	}
}
Exemple #16
0
// general use of redirect callback
func (this *SocialAuth) handleAccess(ctx *context.Context) {
	redirect, _, err := this.OAuthAccess(ctx)
	if err != nil {
		beego.Error("SocialAuth.handleAccess", err)
	}

	if len(redirect) > 0 {
		ctx.Redirect(302, redirect)
	}
}
Exemple #17
0
func DocsStatic(ctx *context.Context) {
	uri := ctx.Input.Params[":all"]
	if len(uri) > 0 {
		lang := ctx.GetCookie("lang")
		if !i18n.IsExist(lang) {
			lang = "en-US"
		}
		http.ServeFile(ctx.ResponseWriter, ctx.Request, "docs/"+lang+"/"+"images/"+uri)
	}
}
Exemple #18
0
func HandleRedirect(ctx *context.Context) {
	redirect, err := SocialAuth.OAuthRedirect(ctx)
	if err != nil {
		beego.Error("SocialAuth.handleRedirect", err)
	}

	if len(redirect) > 0 {
		ctx.Redirect(302, redirect)
	}
}
Exemple #19
0
func OAuthAccess(ctx *context.Context) {
	redirect, _, err := setting.SocialAuth.OAuthAccess(ctx)
	if err != nil {
		beego.Error("OAuthAccess", err)
	}

	if len(redirect) > 0 {
		ctx.Redirect(302, redirect)
	}
}
Exemple #20
0
func FilterUser(ctx *context.Context) {
	adminUrl := []string{"organizations", "users", "reports"}

	for _, url := range adminUrl {
		if strings.Contains(ctx.Request.RequestURI, url) {
			if adminUser, ok := ctx.Input.Session("adminUser").(string); !ok || adminUser != beego.AppConfig.String("conf::admin_user") {
				ctx.Redirect(302, "/login")
			}
			return
		}
	}

}
Exemple #21
0
func CheckLogin(ctx *context.Context) {
	if ctx.Request.RequestURI != "/login" {
		sess, err := models.GlobalSessions.SessionStart(ctx.ResponseWriter, ctx.Request)
		if err != nil || sess == nil {
			ctx.Abort(401, "session nil")
		}
		sessioner := sess.Get("gosessionkey")
		beego.Debug("session:", sess)
		beego.Debug("check login gosessionkey:", sessioner)
		if fmt.Sprintf("%v", sessioner) != "beego1234" {
			ctx.Redirect(401, "/login")
		}
	}
}
Exemple #22
0
func HandleAccess(ctx *context.Context) {
	redirect, userSocial, err := SocialAuth.OAuthAccess(ctx)
	if err != nil {
		beego.Error("SocialAuth.handleAccess", err)
	}

	if userSocial != nil {
		SetInfoToSession(ctx, userSocial)
	}

	if len(redirect) > 0 {
		ctx.Redirect(302, redirect)
	}
}
func filterUser(ctx *context.Context) {
	u, ok := ctx.Input.Session("current_user").(*goth.User)
	if !ok {
		ctx.Redirect(302, "/login")
	}

	if gu := ctx.Input.GetData("github_user"); gu == nil {
		g, err := github.GetCurrentUser(u.AccessToken)
		if err != nil {
			ctx.Redirect(302, "/404.html")
		}
		ctx.Input.SetData("github_user", g)
	}
}
Exemple #24
0
func FilterCheckLogin(ctx *context.Context) {
	url := ctx.Request.RequestURI
	if strings.HasPrefix(url, "/user") || "" == url || strings.HasPrefix(url, "/api") {
		return
	}

	userId, ok := ctx.Input.Session(cache.SESSION_UID).(int64)
	user := models.GetUserById(userId)
	if !ok || nil == user {
		ctx.Output.Session("originURL", ctx.Request.RequestURI)
		ctx.Redirect(302, "/user/login")
	} else if strings.HasPrefix(url, "/root") && "ADMIN" != user.RoleName {
		ctx.Redirect(302, "/user/nopermission")
	}
}
Exemple #25
0
func HandleAccess(ctx *context.Context) {
	redirect, userSocial, err := SocialAuth.OAuthAccess(ctx)
	if err != nil {
		beego.Error("SocialAuth.handleAccess", err)
	}

	if userSocial != nil {
		fmt.Println("Identify: %s, AccessToken: %s", userSocial.Identify, userSocial.Data.AccessToken)
	}
	ctx.Input.CruSession.Set("custom_userSocial_identify", userSocial.Identify)
	if len(redirect) > 0 {
		ctx.Redirect(302, redirect)
	}

}
Exemple #26
0
func IsTokenInvalidAndRedirect(c guimessagedisplay.SessionUtility, ctx *context.Context, err error) bool {
	if IsTokenInvalid(err) {
		guimessage := guimessagedisplay.GetGUIMessage(c)
		guimessage.AddDanger("User token is expired. Please login agin.")
		guimessage.RedirectMessage(c)

		c.DelSession("user")
		c.DelSession("tokenHeaderMap")

		ctx.Redirect(302, "/gui/login/")

		return true
	} else {
		return false
	}
}
Exemple #27
0
// show error string as simple text message.
// if error string is empty, show 500 error as default.
func exception(errcode string, ctx *context.Context) {
	code, err := strconv.Atoi(errcode)
	if err != nil {
		code = 503
	}
	if h, ok := ErrorMaps[errcode]; ok {
		executeError(h, ctx, code)
		return
	} else if h, ok := ErrorMaps["503"]; ok {
		executeError(h, ctx, code)
		return
	} else {
		ctx.ResponseWriter.WriteHeader(code)
		ctx.WriteString(errcode)
	}
}
Exemple #28
0
// Render takes a Beego context, template name and a Context (map[string]interface{}).
// The template is parsed and cached, and gets executed into beegoCtx's ResponseWriter.
//
// Templates are looked up in `templates/` instead of Beego's default `views/` so that
// Beego doesn't attempt to load and parse our templates with `html/template`.
func Render(beegoCtx *context.Context, tmpl string, ctx Context) {
	mutex.RLock()
	template, ok := templates[tmpl]
	mutex.RUnlock()

	if !ok || devMode {
		var err error

		// default ViewsPath
		prefix := beego.AppConfig.String("ViewsPath")
		if prefix == "" {
			prefix = "views/"
		}

		template, err = p2.FromFile(prefix + tmpl)
		if err != nil {
			panic(err)
		}
		mutex.Lock()
		templates[tmpl] = template
		mutex.Unlock()
	}

	var pCtx p2.Context
	if ctx == nil {
		pCtx = p2.Context{}
	} else {
		pCtx = p2.Context(ctx)
	}

	if xsrf, ok := beegoCtx.GetSecureCookie(beego.XSRFKEY, "_xsrf"); ok {
		pCtx["_xsrf"] = xsrf
	}

	// Only override "flash" if it hasn't already been set in Context
	if _, ok := ctx["flash"]; !ok {
		if ctx == nil {
			ctx = Context{}
		}
		ctx["flash"] = readFlash(beegoCtx)
	}

	err := template.ExecuteWriter(pCtx, beegoCtx.ResponseWriter)
	if err != nil {
		panic(err)
	}
}
Exemple #29
0
func filter(ctx *context.Context) {
	url := ctx.Request.URL.Path
	if strings.HasPrefix(url, "/static/") || strings.HasPrefix(url, "/login/md5") {
		return
	}

	sess, _ := beego.GlobalSessions.SessionStart(ctx.ResponseWriter, ctx.Request)
	user := sess.Get("user")
	if user != nil {

	} else {
		if url != "/login/" && url != "/login" && url != "/login/login" {
			ctx.Redirect(302, "/login")
			return
		}
	}
}
Exemple #30
0
Fichier : user.go Projet : sllt/ac
func giveCookie(ctx *context.Context) {
	_, err := ctx.Request.Cookie("uid")
	if err != nil {
		//没有cookie
		uid := GetID()
		h := md5.New()
		h.Write([]byte(uid))
		cookie := hex.EncodeToString(h.Sum(nil))
		err = models.AddUser(uid, cookie)
		if err != nil {
			return
		}
		ctx.SetCookie("uid", cookie, 1<<31-1)
		beego.Info(cookie)

	}
	return
}