func (s *UserService) LoginFromCookie(r *http.Request) (*model.UserToken, error) { if s.logs.Trace() { s.logs.Printf("enter function: LoginFromCookie") } if credential := s.loadUserTokenFromCookie(r); credential != nil { if s.logs.Trace() { s.logs.Printf("Credential in cookie is : %v", credential) } user, err := userdao.GetUserWithCredential(credential[0], credential[1]) if s.logs.Trace() { s.logs.Printf("[DB] Get user with Credenial, user is : %v", user) } if nil != user && err == nil { // if pass := userdao.VerifyLogin(userToken.Username, userToken.Password); pass { // fmt.Println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^") // fmt.Println("login success.") // fmt.Println(userToken) return user.ToUserToken(), nil } else { if err == nil { err = &base.LoginError{Message: "Username and password not matched."} } return nil, err } } return nil, &base.LoginError{Message: "User not login."} }
func (p *AccountChangePassword) OnSuccessFromChangePasswordForm() *exit.Exit { fmt.Printf("-------------- login form success -----------------\n") fmt.Println("Username ", p.User) // verify login userToken := service.User.RequireLogin(p.W, p.R) // verify login old password user, err := userdao.GetUserWithCredential(userToken.Username, p.User.Password) // p.User.Password is old password; if err != nil { // panic(err) p.FormError = "Error: Login failed!" + err.Error() return nil } else if user == nil { p.FormError = "Error: Login failed!" return nil } // update new password user.Password = p.NewPassword // set new password if _, err := service.User.UpdateUser(user); err != nil { p.FormError = "Error: Login failed!" + err.Error() return nil // panic(err) } return exit.Redirect("/") // _, err := service.User.Login(p.User.Username, p.User.Password, p.W, p.R) // if err != nil { // // error can't login, How to redirect to the current page and show errors. // p.FormError = "Error: Login failed!" // // TODO return to this // return nil // } else { // // service already set userToken to session and cookie. redirect if needed. // // TODO: why this not works. // p.FormMessage = "Login Success!" // return exit.Redirect("/") // } }
// Login accept username and password then verify them. // TODO actually I want to receive a hashed password, to reduse risk of .... // TODO: remove w, r in parameter. func (s *UserService) Login(username string, password string, w http.ResponseWriter, r *http.Request) (*model.UserToken, error) { // 1. verify username and password with db. // 2. if success, set it to session and cookie. // 3. if not , return error. // TEST: always return true. user, err := userdao.GetUserWithCredential(username, password) if nil != user && err == nil { userToken := user.ToUserToken() s.setToSession(w, r, userToken) s.setToCookie(w, userToken) return userToken, nil } else { if err == nil { err = &base.LoginError{Message: "Username and password not matched."} } return nil, err } }