Compare commits

..

2 Commits

Author SHA1 Message Date
vilmibm fcc1a2dfed CheckAuth test 2022-06-30 21:49:59 -05:00
vilmibm 910bb3d00a implement check auth 2022-06-30 20:44:58 -05:00
3 changed files with 176 additions and 71 deletions

View File

@ -97,14 +97,7 @@ func getUserFromReq(opts config.Options, req *http.Request) (u *db.User, err err
opts.Logger.Printf("checking auth for %s", username) opts.Logger.Printf("checking auth for %s", username)
if u, err = db.GetUserByName(opts.DB, username); err != nil { u, err = checkAuth(opts, username, hash)
return
}
if u.Hash != hash {
u = nil
err = errors.New("bad credentials")
}
return return
} }
@ -132,6 +125,44 @@ func (a *API) InstanceInfo(ctx *ReqCtx) (resp *BBJResponse, err error) {
return return
} }
func (a *API) CheckAuth(ctx *ReqCtx) (resp *BBJResponse, err error) {
if !ctx.IsPost() {
err = badMethod()
return
}
type AuthArgs struct {
Username string `json:"target_user"`
Hash string `json:"target_hash"`
}
var args AuthArgs
if err = json.NewDecoder(ctx.Req.Body).Decode(&args); err != nil {
err = invalidArgs(err.Error())
return
}
if args.Hash == "" || args.Username == "" {
err = invalidArgs("missing either username or auth hash")
return
}
_, err = checkAuth(a.Opts, args.Username, args.Hash)
if err != nil {
if err.Error() != "bad credentials" {
return
}
err = &HTTPError{Code: 403, Msg: err.Error()}
return
}
// TODO usermap
resp = &BBJResponse{
Data: true,
}
return
}
func (a *API) UserRegister(ctx *ReqCtx) (resp *BBJResponse, err error) { func (a *API) UserRegister(ctx *ReqCtx) (resp *BBJResponse, err error) {
if !ctx.IsPost() { if !ctx.IsPost() {
err = badMethod() err = badMethod()
@ -153,7 +184,7 @@ func (a *API) UserRegister(ctx *ReqCtx) (resp *BBJResponse, err error) {
return return
} }
if err = checkAuth(a.Opts, args.Username, args.Hash); err == nil { if _, err = checkAuth(a.Opts, args.Username, args.Hash); err == nil {
a.Opts.Logger.Printf("user %s already registered", args.Username) a.Opts.Logger.Printf("user %s already registered", args.Username)
err = &HTTPError{Code: 403, Msg: "user already exists"} err = &HTTPError{Code: 403, Msg: "user already exists"}
return return
@ -173,9 +204,9 @@ func (a *API) UserRegister(ctx *ReqCtx) (resp *BBJResponse, err error) {
return return
} }
func checkAuth(opts config.Options, username, hash string) (err error) { // checkAuth returns an error if username is not associated with hash
func checkAuth(opts config.Options, username, hash string) (user *db.User, err error) {
opts.Logger.Printf("querying for %s", username) opts.Logger.Printf("querying for %s", username)
var user *db.User
if user, err = db.GetUserByName(opts.DB, username); err != nil { if user, err = db.GetUserByName(opts.DB, username); err != nil {
return return
} }

View File

@ -41,6 +41,137 @@ func userCount(db *sql.DB) (count int, err error) {
return return
} }
func Test_CheckAuth(t *testing.T) {
ts := []struct {
name string
req func() *http.Request
setup func(*config.Options) error
assert func(*BBJResponse, *testing.T)
wantErr *HTTPError
}{
{
name: "blank user",
req: func() *http.Request {
req, _ := http.NewRequest("POST", "/check_auth", strings.NewReader(`{"target_hash":"abc123"}`))
return req
},
wantErr: &HTTPError{Code: 400, Msg: "invalid args: missing either username or auth hash"},
},
{
name: "blank hash",
req: func() *http.Request {
req, _ := http.NewRequest("POST", "/check_auth", strings.NewReader(`{"target_user":"jillvalentine"}`))
return req
},
wantErr: &HTTPError{Code: 400, Msg: "invalid args: missing either username or auth hash"},
},
{
name: "bad method",
req: func() *http.Request {
r, _ := http.NewRequest("GET", "", strings.NewReader(""))
return r
},
wantErr: &HTTPError{
Msg: "bad method",
Code: 400,
},
},
{
name: "mismatch hash",
setup: func(opts *config.Options) error {
return db.CreateUser(opts.DB, db.User{
Username: "jillvalentine",
Hash: "xyz789",
Created: time.Now(),
})
},
req: func() *http.Request {
req, _ := http.NewRequest("POST", "/check_auth", strings.NewReader(`{"target_user":"jillvalentine", "target_hash":"abc123"}`))
return req
},
wantErr: &HTTPError{Code: 403, Msg: "bad credentials"},
},
{
name: "good",
setup: func(opts *config.Options) error {
return db.CreateUser(opts.DB, db.User{
Username: "jillvalentine",
Hash: "xyz789",
Created: time.Now(),
})
},
req: func() *http.Request {
req, _ := http.NewRequest("POST", "/check_auth", strings.NewReader(`{"target_user":"jillvalentine", "target_hash":"xyz789"}`))
return req
},
assert: func(resp *BBJResponse, t *testing.T) {
if !resp.Data.(bool) {
t.Error("expected true Data")
}
},
},
}
for _, tt := range ts {
t.Run(tt.name, func(t *testing.T) {
// TODO BOILERPLATE
opts, err := createTestState()
if err != nil {
t.Fatalf("failed to create test state: %s", err.Error())
return
}
var req *http.Request
if tt.req == nil {
req, _ = http.NewRequest("POST", "", strings.NewReader(`{"user_name":"albertwesker","auth_hash":"1234abc"}`))
} else {
req = tt.req()
}
teardown, err := db.Setup(opts)
if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error())
return
}
defer teardown()
err = db.EnsureSchema(*opts)
if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error())
return
}
if tt.setup != nil {
err = tt.setup(opts)
if err != nil {
t.Fatalf("setup failed: %s", err.Error())
return
}
}
// END BOILERPLATE
api := &API{Opts: *opts}
ctx := &ReqCtx{Req: req}
var resp *BBJResponse
resp, err = api.CheckAuth(ctx)
if err != nil {
if tt.wantErr == nil || tt.wantErr.Error() != err.Error() {
t.Errorf("got unexpected error: %s", err)
}
return
} else {
if tt.wantErr != nil {
t.Error("expected error, got none")
return
}
}
if tt.assert != nil {
tt.assert(resp, t)
}
})
}
}
func Test_UserRegister(t *testing.T) { func Test_UserRegister(t *testing.T) {
ts := []struct { ts := []struct {
name string name string

View File

@ -88,69 +88,12 @@ func setupAPI(opts config.Options) {
a.Invoke(w, req, a.UserRegister) a.Invoke(w, req, a.UserRegister)
}) })
http.HandleFunc("/check_auth", func(w http.ResponseWriter, req *http.Request) {
a.Invoke(w, req, a.CheckAuth)
})
} }
/* /*
http.HandleFunc("/check_auth", handler(opts, func(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
badMethod(w)
return
}
type AuthArgs struct {
Username string `json:"target_user"`
AuthHash string `json:"target_hash"`
}
var args AuthArgs
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
return
}
opts.Logf("got %s %s", args.Username, args.AuthHash)
db := opts.DB
stmt, err := db.Prepare("select auth_hash from users where user_name = ?")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
var authHash string
err = stmt.QueryRow(args.Username).Scan(&authHash)
if err != nil {
if strings.Contains(err.Error(), "no rows in result") {
opts.Logf("user not found")
writeErrorResponse(w, 404, BBJResponse{
Error: true,
Data: "user not found",
})
} else {
serverErr(w, err)
}
return
}
// TODO unique constraint on user_name
if authHash != args.AuthHash {
http.Error(w, "incorrect password", 403)
writeErrorResponse(w, 403, BBJResponse{
Error: true,
Data: "incorrect password",
})
return
}
// TODO include usermap?
writeResponse(w, BBJResponse{
Data: true,
})
}))
http.HandleFunc("/thread_index", handler(opts, func(w http.ResponseWriter, req *http.Request) { http.HandleFunc("/thread_index", handler(opts, func(w http.ResponseWriter, req *http.Request) {
db := opts.DB db := opts.DB
rows, err := db.Query("SELECT * FROM threads JOIN messages ON threads.thread_id = messages.thread_id") rows, err := db.Query("SELECT * FROM threads JOIN messages ON threads.thread_id = messages.thread_id")