github.com/olivierlemoal/gophish@v0.9.0/auth/auth.go (about) 1 package auth 2 3 import ( 4 "errors" 5 "net/http" 6 7 ctx "github.com/gophish/gophish/context" 8 "github.com/gophish/gophish/models" 9 "golang.org/x/crypto/bcrypt" 10 ) 11 12 // ErrInvalidPassword is thrown when a user provides an incorrect password. 13 var ErrInvalidPassword = errors.New("Invalid Password") 14 15 // ErrPasswordMismatch is thrown when a user provides a blank password to the register 16 // or change password functions 17 var ErrPasswordMismatch = errors.New("Password cannot be blank") 18 19 // ErrEmptyPassword is thrown when a user provides a blank password to the register 20 // or change password functions 21 var ErrEmptyPassword = errors.New("No password provided") 22 23 // Login attempts to login the user given a request. 24 func Login(r *http.Request) (bool, models.User, error) { 25 username, password := r.FormValue("username"), r.FormValue("password") 26 u, err := models.GetUserByUsername(username) 27 if err != nil { 28 return false, models.User{}, err 29 } 30 //If we've made it here, we should have a valid user stored in u 31 //Let's check the password 32 err = bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte(password)) 33 if err != nil { 34 return false, models.User{}, ErrInvalidPassword 35 } 36 return true, u, nil 37 } 38 39 // ChangePassword verifies the current password provided in the request and, 40 // if it's valid, changes the password for the authenticated user. 41 func ChangePassword(r *http.Request) error { 42 u := ctx.Get(r, "user").(models.User) 43 currentPw := r.FormValue("current_password") 44 newPassword := r.FormValue("new_password") 45 confirmPassword := r.FormValue("confirm_new_password") 46 // Check the current password 47 err := bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte(currentPw)) 48 if err != nil { 49 return ErrInvalidPassword 50 } 51 // Check that the new password isn't blank 52 if newPassword == "" { 53 return ErrEmptyPassword 54 } 55 // Check that new passwords match 56 if newPassword != confirmPassword { 57 return ErrPasswordMismatch 58 } 59 // Generate the new hash 60 h, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost) 61 if err != nil { 62 return err 63 } 64 u.Hash = string(h) 65 if err = models.PutUser(&u); err != nil { 66 return err 67 } 68 return nil 69 }