Beispiel #1
0
// Store a new user in the repository. Validates if the given email looks like
// an email and is not yet taken by somebody. If these conditions have been
// met then the new user will be stored and a verification email will be sent
// to the new user.
func (s UserService) Register(email, password string) (User, *utils.GoAuthError) {
	emptyUser := User{}
	if !utils.ValidateEmail(email) {
		customErr := utils.NewGoAuthError(400, "Invalid email adres")
		return emptyUser, &customErr
	}

	user, err := s.repository.findByEmail(email)
	// Email was not yet taken.
	if err.Status == 404 {
		user = NewUser(email, password)

		// Validate if the ID is already taken or not.
		taken, err := s.repository.isTakenID(user.id)
		for taken {
			user.generateNewID()
			taken, err = s.repository.isTakenID(user.id)
			if err != nil {
				return emptyUser, err
			}
		}

		// Validate if the verification token is already taken
		taken, err = s.repository.isTakenToken(user.email.token)
		for taken {
			user.email.GenerateNewToken()
			taken, err = s.repository.isTakenToken(user.email.token)
			if err != nil {
				return emptyUser, err
			}
		}

		err = s.repository.saveUser(user)
		if err != nil {
			return emptyUser, err
		}

		// @TODO: send an verification email to the new user.

		return user, nil
	}

	// Some other error occured.
	if err != nil {
		return emptyUser, err
	}

	// User was found without any errors. Email is already taken.
	customErr := utils.NewGoAuthError(409, "Email is already taken")
	return emptyUser, &customErr
}
Beispiel #2
0
// Update the user
func (s UserService) Update(id string, data map[string]interface{}) *utils.GoAuthError {
	user, err := s.repository.findByID(id)
	if err != nil {
		return err
	}

	claims := make(map[Claim]interface{})
	for k, v := range data {
		if v != nil {
			if k == "email" {
				email, ok := v.(string)
				if ok && utils.ValidateEmail(email) {
					user.SetEmail(email)
				}
			} else {
				claims[Claim{name: k}] = v
			}
		}
	}

	return s.repository.saveUser(user)
}