コード例 #1
0
ファイル: auth.go プロジェクト: kellegous/404
func setAuthCookie(w http.ResponseWriter, cfg *config.Config, sess *store.Session) error {
	env, err := secure.Sign(sess.Key, cfg.HmacKey)
	if err != nil {
		return err
	}

	var buf bytes.Buffer
	e := base62.NewEncoder(&buf)
	if _, err := e.Write(env); err != nil {
		return err
	}
	if err := e.Close(); err != nil {
		return err
	}

	// TODO(knorton): Should also be a secure cookie.
	http.SetCookie(w, &http.Cookie{
		Name:     AuthCookieName,
		Value:    buf.String(),
		Path:     "/",
		MaxAge:   24 * 60 * 60,
		HttpOnly: true,
	})

	return nil
}
コード例 #2
0
ファイル: auth.go プロジェクト: kellegous/404
func Setup(r pork.Router, ctx *context.Context) {
	r.RespondWithFunc("/auth/a", func(w pork.ResponseWriter, r *http.Request) {
		http.Redirect(w, r,
			configFromRequest(ctx.Cfg, r).AuthCodeURL(""),
			http.StatusTemporaryRedirect)
	})

	r.RespondWithFunc("/auth/z", func(w pork.ResponseWriter, r *http.Request) {
		code := r.FormValue("code")
		if code == "" {
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		tx := oauth.Transport{
			Config: configFromRequest(ctx.Cfg, r),
		}

		_, err := tx.Exchange(code)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		var user ghUser
		if err := fetchGhUser(&tx, &user); err != nil {
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		sess, err := createSessionFrom(ctx, &user, tx.Token)
		if err != nil {
			panic(err)
		}

		if err := setAuthCookie(w, ctx.Cfg, sess); err != nil {
			panic(err)
		}
	})

	r.RespondWithFunc("/auth/sock", func(w pork.ResponseWriter, r *http.Request) {
		sess, err := SessionFromRequest(ctx, r)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		buf, err := secure.Encrypt(sess.Key, ctx.Cfg.AesKey, ctx.Cfg.HmacKey)
		if err != nil {
			panic(err)
		}

		var res bytes.Buffer
		e := base62.NewEncoder(&res)
		if _, err := e.Write(buf); err != nil {
			panic(err)
		}
		e.Close()

		w.Header().Set("Content-Type", "text/plain")
		w.Write(res.Bytes())
	})

	r.RespondWithFunc("/auth/exit", func(w pork.ResponseWriter, r *http.Request) {
		sid, err := SessionIdFromRequest(ctx, r)
		if err != nil {
			panic(err)
		}

		if sid == nil {
			return
		}

		if err := store.DeleteSession(ctx, sid); err != nil {
			panic(err)
		}

		http.SetCookie(w, &http.Cookie{
			Name:     AuthCookieName,
			Value:    "",
			Path:     "/",
			MaxAge:   0,
			HttpOnly: true,
		})
	})
}