Ejemplo n.º 1
0
func WebRouter(u *repository.UserRepository, session sessions.Store) http.Handler {
	userRepository = u
	webInit()
	r := mux.NewRouter()

	r.Handle("/", WebAction(WebIndex)).Methods("GET")
	r.Handle("/login", WebAction(WebLogin)).Methods("POST")
	r.Handle("/register", WebAction(WebRegisterGet)).Methods("GET")
	r.Handle("/register", WebAction(WebRegister)).Methods("POST")
	r.Handle("/logout", WebAction(WebLogout))
	r.Handle("/panel", WebAction(WebPanelIndex)).Methods("GET")
	r.Handle("/panel/keys", WebAction(WebPanelKeysPost)).Methods("POST")
	r.Handle("/panel/keys/delete/{id}", WebAction(WebPanelKeysDelete)).Methods("POST")

	app := negroni.New()
	app.Use(middleware.NewSession(session))
	app.Use(middleware.NewCsrfMiddleware("csrf"))
	app.Use(middleware.NewUserMiddleware(&middleware.UserMiddlewareConfig{
		Authenticator: func(userId string) (interface{}, error) {
			userObj := domain.NewUser()
			str, err := userRepository.GetUserById(userId)
			if err != nil {
				return nil, err
			}
			json.Unmarshal([]byte(str), &userObj)
			return userObj, nil
		},
	}))
	app.UseFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		if iface := context.Get(r, "user"); iface == nil {
			user := domain.NewUser()
			context.Set(r, "user", user)
		}
		next(w, r)
	})
	app.UseFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		if 0 == strings.Index(r.URL.Path, "/panel") && !context.Get(r, "user").(*domain.User).IsLogin() {
			http.Redirect(w, r, "/webapp", http.StatusFound)
			return
		}
		if r.URL.Path == "/" && context.Get(r, "user").(*domain.User).IsLogin() {
			http.Redirect(w, r, "/webapp/panel", http.StatusFound)
			return
		}
		next(w, r)
	})
	app.UseHandler(r)
	return context.ClearHandler(app)
}
Ejemplo n.º 2
0
func (mw *UserMiddleware) MiddlewareFunc(h rest.HandlerFunc) rest.HandlerFunc {
	return func(w rest.ResponseWriter, r *rest.Request) {

		userId := r.Env["REMOTE_USER"].(string)
		res, _ := userRepository.GetUserById(userId)
		user := domain.NewUser()
		json.Unmarshal([]byte(res), user)
		r.Env["USER"] = user

		// call the handler
		h(w, r)

	}
}
Ejemplo n.º 3
0
func WebLogin(w http.ResponseWriter, r *http.Request, ctx *WebContext) (err error) {
	session := ctx.Session

	r.ParseForm()
	username := r.Form.Get("username")
	pass := r.Form.Get("pass")

	res, err := userRepository.GetUserById(username)
	if res != "" && err == nil {
		user := domain.NewUser()
		err = json.Unmarshal([]byte(res), user)

		pHash := xxhash.Checksum64([]byte(pass))
		var passBytes []byte
		passBytes = strconv.AppendUint(passBytes, pHash, 10)
		if nil == err && user.Pass == string(passBytes) {
			session.Values["user"] = username
		}
	}

	http.Redirect(w, r, "/webapp/panel", http.StatusFound)

	return
}
Ejemplo n.º 4
0
func NewWebApi() http.Handler {
	Authenticator := func(userId, password string) bool {

		res, err := userRepository.GetUserById(userId)
		if err != nil || res == "" {
			return false
		}
		user := domain.NewUser()
		err = json.Unmarshal([]byte(res), user)

		return nil == err && user.Pass == domain.HashPassword(password)
	}

	var jwt_middleware = &jwt.JWTMiddleware{
		Key:           []byte("testKey"),
		Realm:         "Unitrans",
		Timeout:       time.Hour * 30,
		MaxRefresh:    time.Hour * 24,
		Authenticator: Authenticator,
	}

	var DevStack = []rest.Middleware{
		&rest.AccessLogApacheMiddleware{},
		&rest.TimerMiddleware{},
		&rest.RecorderMiddleware{},
		&rest.PoweredByMiddleware{
			XPoweredBy: "unitrans",
		},
		&rest.RecoverMiddleware{
			EnableResponseStackTrace: true,
		},
		&rest.JsonIndentMiddleware{},
	}
	api := rest.NewApi()

	api.Use(DevStack...)
	api.Use(&rest.CorsMiddleware{
		RejectNonCorsRequests: false,
		OriginValidator: func(origin string, request *rest.Request) bool {
			return true
		},
		AllowedMethods:                []string{"GET", "POST", "PUT", "DELETE"},
		AllowedHeaders:                []string{"Authorization", "Accept", "Content-Type", "X-Custom-Header", "Origin"},
		AccessControlAllowCredentials: true,
		AccessControlMaxAge:           3600,
	})
	api.Use(&rest.IfMiddleware{
		Condition: func(request *rest.Request) bool {
			return request.URL.Path != "/login" && request.URL.Path != "/refresh" && request.URL.Path != "/register" && request.URL.Path != "/checkExists" && request.URL.Path != "/tr"
		},
		IfTrue: jwt_middleware,
	})
	api.Use(&rest.IfMiddleware{
		Condition: func(r *rest.Request) bool {
			_, ok := r.Env["REMOTE_USER"]
			return ok
		},
		IfTrue: &UserMiddleware{},
	})
	api_router, _ := rest.MakeRouter(
		rest.Post("/login", jwt_middleware.LoginHandler),
		rest.Get("/test", handle_auth),
		rest.Get("/refresh", jwt_middleware.RefreshHandler),
		rest.Post("/register", Register),
		rest.Post("/checkExists", CheckExists),

		rest.Get("/keys", KeysList),
		rest.Post("/keys", KeyCreate),
		rest.Delete("/keys/*key", KeyDelete),

		rest.Post("/tr", Translate),
	)
	api.SetApp(api_router)
	return api.MakeHandler()
}