Ejemplo n.º 1
0
func (re *Redirect) Render(res *wcg.Response, req *wcg.Request) {
	url := re.URL
	if !strings.HasPrefix(url, "http://") && strings.HasPrefix(url, "https://") {
		url = wcg.AbsoluteURL(req, url)
	}
	res.Redirect(url, int(re.StatusCode))
}
Ejemplo n.º 2
0
// Use returns the new *OAuth2Config for redirect url context.
func (r *OAuth2Config) Use(req *wcg.Request) *oauth2.Config {
	redirect := wcg.AbsoluteURL(req, r.RedirectURL)
	return &oauth2.Config{
		ClientID:     r.ClientID,
		ClientSecret: r.ClientSecret,
		Scopes:       r.Scopes,
		Endpoint:     r.Endpoint,
		RedirectURL:  redirect,
	}
}
func createDailyNotificationContent(req *wcg.Request) (*dailyNotificationContent, error) {
	today := lib.HumanTodayInLocation(lib.JST)
	_iepgs, err := IEPG.Query().
		Filter("StartAt >=", today).
		Filter("StartAt <", today.Add(24*time.Hour)).
		Order("StartAt").
		Execute(req)
	if err != nil {
		return nil, fmt.Errorf("Could not load IEPG records: %v", err)
	}
	iepgs := _iepgs.Data.([]pt.IEPG)
	var scheduled, skipped []pt.IEPG
	for _, iepg := range iepgs {
		if iepg.ShouldRecord() {
			scheduled = append(scheduled, iepg)
		} else {
			skipped = append(skipped, iepg)
		}
	}
	var date = lib.FormatHumanDateString(today)
	var title string
	var contentLines []string
	if len(scheduled) > 0 {
		title = fmt.Sprintf("[録画予約] %sの予約 (%d 件)", date, len(scheduled))
		contentLines = append(contentLines, "□ 予約済み")
		contentLines = append(contentLines, makeIEPGList(scheduled)...)
	}
	if len(skipped) > 0 {
		if title == "" {
			title = fmt.Sprintf("[録画予約] %sの予約はありません (除外 %d件)", date, len(skipped))
		}
		if len(contentLines) > 0 {
			contentLines = append(contentLines, "")
		}
		contentLines = append(contentLines, "□ 除外")
		contentLines = append(contentLines, makeIEPGList(skipped)...)
	}
	if title == "" {
		title = fmt.Sprintf("[録画予約] %sの予約はありません", date)
	}
	if len(contentLines) > 0 {
		contentLines = append(contentLines, "")
	}
	// footer
	contentLines = append(contentLines, []string{
		"□ 設定の変更はこちら",
		wcg.AbsoluteURL(req, "/intern/pt/"),
		"",
	}...)
	return &dailyNotificationContent{
		title: title,
		lines: contentLines,
	}, nil
}
Ejemplo n.º 4
0
func bySession(router *wcg.Router, configure func()) {
	fbconfig := facebook.NewAuthConfig("dummy", "dumyy", "")
	fbconfig.RedirectURL = "/login/facebook/callback"
	fbconfig.ContextFactory = func(res *wcg.Response, req *wcg.Request) context.Context {
		return gae.NewContext(req)
	}
	fbconfig.UnauthorizedHandler = wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) {
		res.TemplatesWithStatus(401, nil, "permrejected.html", "header.html", "footer.html")
	})
	fbconfig.AuthorizedHandler = wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) {
		ref, _ := req.Session.Get("LoginRef")
		if ref != "" && strings.HasPrefix(ref, "/") {
			res.Redirect(wcg.AbsoluteURL(req, ref), http.StatusFound)
		} else {
			res.Redirect("/", http.StatusFound)
		}
	})
	fbconfig.InvalidatedHandler = wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) {
		req.Logger.Debugf("Guest user access.")
	})
	fbconfig.Scopes = []string{}
	fbauth, fbcallback, fbvalidates, fblogout := middleware.OAuth2(fbconfig)

	// set routes
	router.Before(wcg.NewNamedHandler("facebook.validate", func(res *wcg.Response, req *wcg.Request) {
		if !request.ByGuest(req) { // already authenticated
			return
		}
		if req.Session == nil {
			return
		}
		// Check the fbconfig from ServerConfig
		fbapp := configs.GetMultiValues(
			req,
			"facebook_app_id",
			"facebook_app_secret",
			"facebook_page_id",
		)
		if fbapp[0] != "" && fbapp[1] != "" {
			fbconfig.ClientID = fbapp[0]
			fbconfig.ClientSecret = fbapp[1]
			fbvalidates.Process(res, req)
		}
	}))

	router.GET("/login/facebook", wcg.NewNamedHandler("facebook.login.auth", func(res *wcg.Response, req *wcg.Request) {
		if !isFBConfigured(fbconfig) {
			return
		}
		req.Session.Set("LoginRef", req.Query("ref"))
		fbauth.Process(res, req)
	}))

	router.GET("/login/facebook/callback", wcg.NewNamedHandler("facebook.login.callback", func(res *wcg.Response, req *wcg.Request) {
		if !isFBConfigured(fbconfig) {
			return
		}
		fbcallback.Process(res, req)
	}))

	router.POST("/logout/facebook", wcg.NewNamedHandler("facebook.logout", func(res *wcg.Response, req *wcg.Request) {
		if !isFBConfigured(fbconfig) {
			return
		}
		fblogout.Process(res, req)
		res.Redirect("/", http.StatusFound)
	}))

	configure()
}
Ejemplo n.º 5
0
func setupAPIOAuth2(app *server.App) {
	var API = app.API()

	API.GET("/oauth2/clients/",
		middleware.EntityAll(entities.OAuth2ClientSettings.Query()))

	API.GET("/oauth2/clients/:key.json",
		middleware.EntityGet(entities.OAuth2ClientSettings.Get().Cache(true), "key"))

	// Create an oauth2.Config object into session and redirect to the oauth2 endpoint.
	// /admin/oauth2/callback.html will finally authorize the callback code and store the oauth2.Config into datastore.
	API.POST("/oauth2/clients/",
		middleware.ParseForm(func(v *validators.FormValidator) {
			v.Field("key").Required()
			v.Field("client_id").Required()
			v.Field("client_secret").Required()
			v.Field("auth_url").Required()
			v.Field("token_url").Required()
		}),
		server.Handler(func(req *wcg.Request) response.Response {
			cfg := &oauth2.Config{
				ClientID:     req.Form("client_id"),
				ClientSecret: req.Form("client_secret"),
				Endpoint: oauth2.Endpoint{
					AuthURL:  req.Form("auth_url"),
					TokenURL: req.Form("token_url"),
				},
				Scopes: strings.Split(req.Form("scopes"), ","),
				RedirectURL: wcg.AbsoluteURL(
					req,
					fmt.Sprintf("/api/admin/oauth2/callback/?oauth2_key=%s", req.Form("key")),
				),
			}
			data := wcg.DataBag{}
			data.Set("key", req.Form("key"))
			data.Set("client_id", cfg.ClientID)
			data.Set("client_secret", cfg.ClientSecret)
			data.Set("auth_url", cfg.Endpoint.AuthURL)
			data.Set("token_url", cfg.Endpoint.TokenURL)
			data.Set("scopes", req.Form("scopes"))
			data.Set("redirect_url", cfg.RedirectURL)
			req.Session.SetData(
				fmt.Sprintf("admin.oauth2_%s", req.Form("key")),
				data,
			)
			return response.NewRedirect(cfg.AuthCodeURL("state", oauth2.AccessTypeOffline), response.RedirectSeeOther)
		}))

	API.DELETE("/oauth2/clients/:client_id.json",
		middleware.EntityDelete(entities.OAuth2ClientSettings.Delete(), "client_id"))

	API.GET("/oauth2/callback/",
		server.Handler(func(req *wcg.Request) response.Response {
			key := req.Query("oauth2_key")
			code := req.Query("code")
			data, ok := req.Session.GetData(fmt.Sprintf("admin.oauth2_%s", key))
			if !ok {
				return response.NotFound(req)
			}
			scopes, _ := data.Get("scopes")
			cfg := &oauth2.Config{}
			cfg.ClientID, _ = data.Get("client_id")
			cfg.ClientSecret, _ = data.Get("client_secret")
			cfg.Endpoint.AuthURL, _ = data.Get("auth_url")
			cfg.Endpoint.TokenURL, _ = data.Get("token_url")
			cfg.Scopes = strings.Split(scopes, ",")
			cfg.RedirectURL, _ = data.Get("redirect_url")
			token, err := cfg.Exchange(gae.NewContext(req), code)
			if err != nil {

				return response.BadRequest(req, err)
			}
			settings := models.NewOAuth2ClientSettings(cfg, token)
			settings.Key = key
			entities.OAuth2ClientSettings.Put().Key(key).MustUpdate(req, settings)
			return response.NewRedirect("/admin/oauth2/", response.RedirectSeeOther)
		}))

}