Last active
December 24, 2021 13:59
-
-
Save oludouglas/67c8284503d4ee3d006aac0f19bad386 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is under the user.go file | |
func (h *Handler) loginUser(c echo.Context) error { | |
username := c.FormValue("username") | |
password := c.FormValue("password") | |
user := h.service.GetByUsername(username) | |
if user == nil || user.Password != password { | |
return echo.ErrUnauthorized | |
} | |
sess, err := session.Get("session", c) | |
if err != nil { | |
log.Fatal(err) | |
return err | |
} | |
sess.Options = &sessions.Options{ | |
Path: "/", | |
MaxAge: 0, | |
HttpOnly: false, | |
Secure: true, | |
} | |
sess.Values["name"] = username | |
sess.Save(c.Request(), c.Response()) | |
return c.NoContent(http.StatusOK) | |
} | |
// this is under the user_test.go file | |
func TestAuthenticateUser(t *testing.T) { | |
e := echo.New() | |
e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret")))) | |
h := &Handler{&store} // custom store interface | |
t.Run("it returns a valid session for successful login", func(t *testing.T) { | |
f := make(url.Values) | |
f.Set("username", "john") | |
f.Set("password", "secret@123") | |
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(f.Encode())) | |
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm) | |
res := httptest.NewRecorder() | |
c := e.NewContext(req, res) | |
AssertNil(t, h.loginUser(c)) | |
AssertEqual(t, http.StatusOK, res.Code) | |
sess, err := session.Get("session", c) | |
AssertNil(t, err) | |
AssertEqual(t, "john", sess.Values["name"]) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment