예제 #1
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,
		})
	})
}