func Register(w rest.ResponseWriter, r *rest.Request) { var form struct { Id string `json:"username"` Pass string `json:"password"` } r.DecodeJsonPayload(&form) if form.Pass == "" { rest.Error(w, "Invalid input", 400) return } res, err := userRepository.GetUserById(form.Id) if res != "" { rest.Error(w, "[username]exists", 400) return } user := &domain.User{Id: form.Id, Pass: domain.HashPassword(form.Pass)} bytes, _ := json.Marshal(user) userRepository.SaveUserById(form.Id, string(bytes)) res, err = userRepository.GetUserById(form.Id) log.Println(res, err) w.WriteJson(map[string]string{"Status": "OK"}) }
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() }