Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package users
- import (
- "context"
- "database/sql"
- "unicode"
- "unicode/utf8"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
- "golang.org/x/crypto/bcrypt"
- "users/proto"
- )
- // ChangePassword changes the password of a specific user
- func (u *Users) ChangePassword(ctx context.Context, req *pbusers.ChangePasswordRequest) (*pbusers.ChangePasswordResponse, error) {
- rsp := &pbusers.ChangePasswordResponse{}
- // Check if the password meets the security requirements
- if utf8.RuneCountInString(req.Password) <= 9 {
- return rsp, status.Error(codes.InvalidArgument, "the new password didn't meet the security requirements: the password needs to be at least 10 characters long")
- }
- hasUppercase := false
- hasLowercase := false
- hasDigit := false
- for _, c := range req.Password {
- if unicode.IsDigit(c) {
- hasDigit = true
- }
- if unicode.IsUpper(c) {
- hasUppercase = true
- }
- if unicode.IsLower(c) {
- hasLowercase = true
- }
- }
- if !hasUppercase || !hasLowercase {
- return rsp, status.Error(codes.InvalidArgument, "the new password didn't meet the security requirements: the password needs to have at least one uppercase and one lowercase letter")
- }
- if !hasDigit {
- return rsp, status.Error(codes.InvalidArgument, "the new password didn't meet the security requirements: the password needs to have at least one digit")
- }
- type userStruct struct {
- ID string
- Email string
- Password string
- }
- user := userStruct{}
- err := u.DB.QueryRow("SELECT * FROM user WHERE id = ?", req.Id).Scan(
- &user.ID,
- &user.Email,
- &user.Password,
- )
- if err != nil {
- if err == sql.ErrNoRows {
- return rsp, status.Errorf(codes.NotFound, "user with id %s wasn't found in the DB", req.Id)
- }
- return rsp, status.Errorf(codes.Internal, "there was an error querying the DB: %v", err)
- }
- password, err := bcrypt.GenerateFromPassword([]byte(req.Password), 12)
- if err != nil {
- panic(err)
- }
- _, err = u.DB.Exec(`UPDATE user
- SET password = ?
- WHERE id = ?`, string(password[:]), user.ID)
- if err != nil {
- panic(err)
- }
- return rsp, nil
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement