Last active
December 5, 2022 12:09
-
-
Save ainsleyclark/1228056fb9a7662c71a350df1fdf4c99 to your computer and use it in GitHub Desktop.
Encryption
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
| // DefaultCost is the cost that will actually be set if a | |
| // cost below MinCost is passed into | |
| // GenerateFromPassword. | |
| var DefaultCost = bcrypt.DefaultCost | |
| // HashPassword gets the password in byte format and | |
| // generates a hashed password with the default cost | |
| // of 10. | |
| // Returns errors.INTERNAL if the bcrypt failed to generate from password. | |
| func HashPassword(password string) (string, error) { | |
| const op = "Encryption.HashPassword" | |
| bytePassword := []byte(password) | |
| hashedPassword, err := bcrypt.GenerateFromPassword(bytePassword, DefaultCost) | |
| if err != nil { | |
| return "", &errors.Error{Code: errors.INTERNAL, Message: "Error hashing password", Operation: op, Err: err} | |
| } | |
| return string(hashedPassword), err | |
| } | |
| // Login | |
| // | |
| // Authenticate compares the email & password for a match in the DB. | |
| // Returns errors.NOTFOUND if the user is not found. | |
| func (s *Store) Login(email, password string) (domain.User, error) { | |
| const op = "AuthStore.Login" | |
| user, err := s.userStore.FindByEmail(email) | |
| if err != nil { | |
| return domain.User{}, &errors.Error{Code: errors.NOTFOUND, Message: ErrLoginMsg, Operation: op, Err: err} | |
| } | |
| err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) | |
| if err != nil { | |
| return domain.User{}, &errors.Error{Code: errors.NOTFOUND, Message: ErrLoginMsg, Operation: op, Err: err} | |
| } | |
| err = s.userStore.UpdateToken(user.Token) | |
| if err != nil { | |
| return domain.User{}, err | |
| } | |
| return user, nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment