AuthRequest validate test

This commit is contained in:
Daniel Krol 2022-06-07 20:08:41 -04:00
parent fd46875c48
commit a4048262d8
3 changed files with 46 additions and 5 deletions

View file

@ -6,7 +6,7 @@ import (
// Test stubs for now
func TestAuthNewTokenSuccess(t *testing.T) {
func TestAuthNewToken(t *testing.T) {
auth := Auth{}
authToken, err := auth.NewToken(234, "dId", "my-scope")

View file

@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"net/mail"
"orblivion/lbry-id/auth"
"orblivion/lbry-id/store"
)
@ -16,10 +17,24 @@ type AuthRequest struct {
Password auth.Password `json:"password"`
}
// TODO - validate funcs probably should return error rather than bool for
// idiomatic golang
func (r *AuthRequest) validate() bool {
return (r.DeviceId != "" &&
r.Email != auth.Email("") && // TODO email validation. Here or store. Stdlib does it: https://stackoverflow.com/a/66624104
r.Password != auth.Password(""))
e, err := mail.ParseAddress(string(r.Email))
if err != nil {
return false
}
// "Joe <joe@example.com>" is valid according to ParseAddress. Likewise
// " joe@example.com". Etc. We only want the exact address, "joe@example.com"
// to be valid. ParseAddress will extract the exact address as e.Address. So
// we'll take the input email, put it through ParseAddress, see if it parses
// successfully, and then compare the input email to e.Address to make sure
// that it was an exact address to begin with.
if string(r.Email) != e.Address {
return false
}
return (r.DeviceId != "" && r.Password != auth.Password(""))
}
func (s *Server) getAuthToken(w http.ResponseWriter, req *http.Request) {

View file

@ -154,5 +154,31 @@ func TestServerAuthHandlerErrors(t *testing.T) {
}
func TestServerValidateAuthRequest(t *testing.T) {
t.Fatalf("Test me: Implement and test AuthRequest.validate()")
authRequest := AuthRequest{DeviceId: "dId", Email: "joe@example.com", Password: "aoeu"}
if !authRequest.validate() {
t.Fatalf("Expected valid AuthRequest to successfully validate")
}
authRequest = AuthRequest{Email: "joe@example.com", Password: "aoeu"}
if authRequest.validate() {
t.Fatalf("Expected AuthRequest with missing device to not successfully validate")
}
authRequest = AuthRequest{DeviceId: "dId", Email: "joe-example.com", Password: "aoeu"}
if authRequest.validate() {
t.Fatalf("Expected AuthRequest with invalid email to not successfully validate")
}
// Note that Golang's email address parser, which I use, will accept
// "Joe <joe@example.com>" so we need to make sure to avoid accepting it. See
// the implementation.
authRequest = AuthRequest{DeviceId: "dId", Email: "Joe <joe@example.com>", Password: "aoeu"}
if authRequest.validate() {
t.Fatalf("Expected AuthRequest with email with unexpected formatting to not successfully validate")
}
authRequest = AuthRequest{DeviceId: "dId", Email: "joe@example.com"}
if authRequest.validate() {
t.Fatalf("Expected AuthRequest with missing password to not successfully validate")
}
}