// LoadAuthorize looks up AuthorizeData by a code. // Client information MUST be loaded together. // Optionally can return error if expired. func (storage *Storage) LoadAuthorize(code string) (d *osin.AuthorizeData, err error) { // TODO: use logger := log.NewContext(,sg) logger, errLogger := msg, errMsg logger.Log( "method", "LoadAuthorize", "code", code) // loading osin using osin storage srv, err := store.Get(storage.ctx, KeyAuth) if err != nil { return } defer srv.Close() e := &AuthorizeData{} conds := store.NewConds() conds.Add("code", code) err = srv.One(conds, e) if err != nil { return } else if e == nil { err = store.Error(http.StatusNotFound, "AuthorizeData not found for the code") return } // load client here var ok bool cli, err := storage.GetClient(e.ClientID) if err != nil { return } else if e.Client, ok = cli.(*Client); !ok { err = store.Error(http.StatusInternalServerError, "Internal Server Error") errLogger.Log( "method", "GetClient", "code", code, "cond", conds, "raw client", fmt.Sprintf("%#v", cli), "message", "Unable to cast raw client into Client") return } // load user data here if e.UserID != "" { userStore, err := store.Get(storage.ctx, KeyUser) if err != nil { return d, err } user := &User{} userStore.One(store.NewConds().Add("id", e.UserID), user) e.UserData = user } d = e.ToOsin() return }
// NewUserFunc creates the default parser of login HTTP request func NewUserFunc(idName string) UserFunc { return func(r *http.Request, us store.Store) (ou OAuth2User, err error) { var c store.Conds id := r.Form.Get(idName) if id == "" { serr := store.Error(http.StatusBadRequest, "empty user identifier") err = serr return } // different condition based on the user_id field format if govalidator.IsEmail(id) { c = store.NewConds().Add("email", id) } else { c = store.NewConds().Add("username", id) } // get user from database u := us.AllocEntity() err = us.One(c, u) if err != nil { serr := store.ExpandError(err) if serr.Status != http.StatusNotFound { serr.TellServer("Error searching user %#v: %s", id, serr.ServerMsg) return } err = serr return } // if user does not exists if u == nil { serr := store.Error(http.StatusBadRequest, "Username or Password incorrect") serr.TellServer("Unknown user %#v attempt to login", id) err = serr return } // cast the user as OAuth2User // and do password check ou, ok := u.(OAuth2User) if !ok { serr := store.Error(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) serr.TellServer("User cannot be cast as OAuth2User") err = serr return } return } }
// LoadRefresh retrieves refresh AccessData. Client information MUST be loaded together. // AuthorizeData and AccessData DON'T NEED to be loaded if not easily available. // Optionally can return error if expired. func (storage *Storage) LoadRefresh(token string) (d *osin.AccessData, err error) { // TODO: use logger := log.NewContext(,sg) logger := msg logger.Log( "method", "LoadRefresh", "token", token) srv, err := store.Get(storage.ctx, KeyAccess) if err != nil { return } defer srv.Close() e := &AccessData{} conds := store.NewConds() conds.Add("refresh_token", token) err = srv.One(conds, e) if err != nil { return } else if e == nil { err = store.Error(http.StatusNotFound, "AccessData not found for the refresh token") return } // load supplementary data if err = storage.loadAccessSupp(e); err != nil { return } d = e.ToOsin() return }
func TestService_Error(t *testing.T) { // create handler with service s := httpservice.NewJSONService("/foo/bar", func(ctx context.Context, request interface{}) (response interface{}, err error) { err = store.Error(50123, "hello error") return }) s.DecodeFunc = func(ctx context.Context, r *http.Request) (request interface{}, err error) { request = "hello world" return } h := s.Handler() // variables for decoding w := httptest.NewRecorder() h.ServeHTTP(w, nil) serr := &store.StoreError{} // try decoding dec := json.NewDecoder(w.Body) dec.Decode(serr) if err := dec.Decode(&serr); err != io.EOF { t.Errorf("error decoding response: %#v", err.Error()) } else if want, have := "hello error", serr.ClientMsg; want != have { t.Errorf("expect: %#v, got: %#v", want, have) } t.Logf("err: %#v", serr) }
// GetClient implements osin.Storage.GetClient func (storage *Storage) GetClient(id string) (c osin.Client, err error) { // TODO: use logger := log.NewContext(,sg) logger, errLogger := msg, errMsg logger.Log( "method", "GetClient", "id", id) srv, err := store.Get(storage.ctx, KeyClient) if err != nil { serr := store.Error(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) serr.TellServer("unable to get client store: %s", err) err = serr return } defer srv.Close() e := &Client{} conds := store.NewConds() conds.Add("id", id) err = srv.One(conds, e) if err != nil { serr := store.ExpandError(err) errLogger.Log( "method", "GetClient", "id", id, "cond", conds, "message", "Failed running One()", "error", serr.ServerMsg) return } else if e == nil { errLogger.Log( "method", "GetClient", "id", id, "cond", fmt.Sprintf("%#v", conds), "message", "Client not found") err = store.Error(http.StatusNotFound, "Client not found for the given id") return } c = e return }
// loadAccessSupp loads supplementary data onto an *AccessData func (storage *Storage) loadAccessSupp(e *AccessData) (err error) { // load client here var ok bool cli, err := storage.GetClient(e.ClientID) if err != nil { return } else if e.Client, ok = cli.(*Client); !ok { serr := store.Error(http.StatusInternalServerError, "Internal Server Error") serr.TellServer("Unable to cast client into Client type: %#v", cli) err = serr return } e.ClientID = e.Client.GetId() // unserialize previous AuthorizeData here if e.AuthorizeDataJSON != "" { ad := &AuthorizeData{} json.Unmarshal([]byte(e.AuthorizeDataJSON), ad) e.AuthorizeData = ad } // unserialize previous AccessData here if e.AccessDataJSON != "" { ad := &AccessData{} json.Unmarshal([]byte(e.AccessDataJSON), ad) e.AccessData = ad } // load user data here if e.UserID != "" { userStore, err := store.Get(storage.ctx, KeyUser) if err != nil { return err } user := &User{} userStore.One(store.NewConds().Add("id", e.UserID), user) e.UserData = user } return }
func TestError(t *testing.T) { estatus, ecode, emsg := testErrorCode() var err error = store.Error(ecode, emsg) code, msg := store.ParseError(err) if code != ecode { t.Errorf("code output not correct. Expect %#v but get %#v", ecode, code) } if msg != emsg { t.Errorf("msg output not correct. Expect %#v but get %#v", emsg, msg) } serr := store.ExpandError(err) if serr.Status != estatus { t.Errorf("Incorrect StoreError.Status. Expecting %#v but get %#v", estatus, serr.Status) } if serr.Code != ecode { t.Errorf("Incorrect StoreError.Code. Expecting %#v but get %#v", ecode, serr.Code) } if serr.ServerMsg != emsg { t.Errorf("Incorrect StoreError.ServerMsg. Expecting %#v but get %#v", emsg, serr.ServerMsg) } if serr.ClientMsg != emsg { t.Errorf("Incorrect StoreError.ClientMsg. Expecting %#v but get %#v", emsg, serr.ClientMsg) } if serr.DeveloperMsg != "" { t.Errorf("Incorrect StoreError.DeveloperMsg. Expecting %#v but get %#v", "", serr.DeveloperMsg) } }
func TestErrorFormat(t *testing.T) { tpl := "(%s) some custom bad request: %#v" msg := "hello world" estatus := rand.Intn(900) ecode := estatus*100 + rand.Intn(100) err := store.Error(ecode, ""). TellClient(tpl, "client", msg). TellDeveloper(tpl, "developer", msg). TellServer(tpl, "server", msg) if want, have := fmt.Sprintf(tpl, "client", msg), err.String(); want != have { t.Errorf("want: %#v, got %#v", want, have) } if want, have := fmt.Sprintf(tpl, "client", msg), fmt.Sprintf("%s", err); want != have { t.Errorf("want: %#v, got %#v", want, have) } if want, have := fmt.Sprintf(tpl, "client", msg), err.Error(); want != have { t.Errorf("want: %#v, got %#v", want, have) } if want, have := fmt.Sprintf(tpl, "client", msg), err.ClientMsg; want != have { t.Errorf("want: %#v, got %#v", want, have) } if want, have := fmt.Sprintf(tpl, "developer", msg), err.DeveloperMsg; want != have { t.Errorf("want: %#v, got %#v", want, have) } if want, have := fmt.Sprintf(tpl, "server", msg), err.ServerMsg; want != have { t.Errorf("want: %#v, got %#v", want, have) } }
// GetEndpoints generate endpoints http handers and return func (m *Manager) GetEndpoints(factory store.Factory) *Endpoints { // try to login with given request login tryLogin := func(ctx context.Context, r *http.Request) (user OAuth2User, err error) { logger := msg logger.Log( "func", "tryLogin (Manager.GetEndpoints)") // parse POST input r.ParseForm() if r.Method == "POST" { var u OAuth2User var us store.Store // get and check password non-empty password := r.Form.Get("password") if password == "" { err = errors.New("empty password") return } // obtain user store us, err = store.Get(ctx, KeyUser) if err != nil { err = store.Error( http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)). TellServer("error obtaining user store: %s", err.Error()) return } // get user by userFunc u, err = m.userFunc(r, us) if err != nil { serr := store.ExpandError(err) if serr.Status == http.StatusNotFound { err = store.Error(http.StatusBadRequest, "user id or password incorrect"). TellServer("user not found") } else { err = store.Error( http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)). TellServer("error obtaining user: %s", serr.ServerMsg) } return } // if user is nil, user not found if u == nil { err = store.Error(http.StatusBadRequest, "user not found") return } // if password does not match if !u.PasswordIs(password) { err = store.Error(http.StatusBadRequest, "user id or password incorrect"). TellServer("incorrect password") return } // return pointer of user object, allow it to be re-cast logger.Log( "func", "tryLogin (Manager.GetEndpoints)", "message", "login success") user = u return } // no POST input or incorrect login, show form // end login handling sequence and wait for // user input from login form err = store.Error(http.StatusUnauthorized, "Require login"). TellServer("no POST input") return } type ContextHandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request) *osin.Response // sessionContext takes a ContextHandlerFunc and returns // a http.HandlerFunc sessionContext := func(inner ContextHandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // per connection based context.Context, with factory ctx := store.WithFactory(context.Background(), factory) defer store.CloseAllIn(ctx) if resp := inner(ctx, w, r); resp != nil { if resp.InternalError != nil { errLogger := errMsg errLogger.Log( "func", "sessionContext (Manager.GetEndpoints)", "error", resp.InternalError.Error()) } osin.OutputJSON(resp, w, r) } } } ep := Endpoints{} // authorize endpoint ep.Auth = sessionContext(func(ctx context.Context, w http.ResponseWriter, r *http.Request) *osin.Response { logger := msg logger.Log( "endpoint", "auth") srvr := m.osinServer resp := srvr.NewResponse() resp.Storage.(*Storage).SetContext(ctx) // handle authorize request with osin if ar := srvr.HandleAuthorizeRequest(resp, r); ar != nil { logger.Log( "endpoint", "auth", "message", "handle authorize request") // TODO: maybe redirect to another URL for // dedicated login form flow? var err error if ar.UserData, err = tryLogin(ctx, r); err != nil { serr := store.ExpandError(err) logger.Log( "endpoint", "auth", "message", "handle authorize request", "error", serr.ServerMsg) lctx := &LoginFormContext{ Context: withOsinAuthRequest(ctx, ar), LoginErr: err, ResponseWriter: w, Request: r, Logger: logger, } m.showLoginForm(lctx, w, r) return nil } logger.Log( "endpoint", "auth", "message", "User obtained", "osin.AuthorizeData.UserData", fmt.Sprintf("%#v", ar.UserData)) ar.Authorized = true srvr.FinishAuthorizeRequest(resp, r, ar) } logger.Log( "endpoint", "auth", "message", "User obtained", "response", fmt.Sprintf("%#v", resp)) return resp }) // token endpoint ep.Token = sessionContext(func(ctx context.Context, w http.ResponseWriter, r *http.Request) *osin.Response { logger := msg logger.Log( "endpoint", "token") srvr := m.osinServer resp := srvr.NewResponse() resp.Storage.(*Storage).SetContext(ctx) if ar := srvr.HandleAccessRequest(resp, r); ar != nil { // TODO: handle authorization // check if the user has the permission to grant the scope logger.Log( "endpoint", "token", "message", "access successful") ar.Authorized = true srvr.FinishAccessRequest(resp, r, ar) } logger.Log( "endpoint", "token", "response", fmt.Sprintf("%#v", resp)) return resp }) // information endpoint ep.Info = sessionContext(func(ctx context.Context, w http.ResponseWriter, r *http.Request) *osin.Response { logger := msg logger.Log( "endpoint", "information") srvr := m.osinServer resp := srvr.NewResponse() resp.Storage.(*Storage).SetContext(ctx) defer resp.Close() if ir := srvr.HandleInfoRequest(resp, r); ir != nil { srvr.FinishInfoRequest(resp, r, ir) } logger.Log( "endpoint", "information", "response", fmt.Sprintf("%#v", resp)) return resp }) return &ep }