private User _doCreateAccount(StaplerRequest req, StaplerResponse rsp, String formView) throws ServletException, IOException { if(!allowsSignup()) throw HttpResponses.error(SC_UNAUTHORIZED,new Exception("User sign up is prohibited")); boolean firstUser = !hasSomeUser(); User u = createAccount(req, rsp, enableCaptcha, formView); if(u!=null) { if(firstUser) tryToMakeAdmin(u); // the first user should be admin, or else there's a risk of lock out loginAndTakeBack(req, rsp, u); } return u; }
/** * Creates an user account. Used for self-registration. */ @RequirePOST public User doCreateAccount(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { return _doCreateAccount(req, rsp, "signup.jelly"); }
/** * Creates a user account. Requires {@link Jenkins#ADMINISTER} */ @Restricted(NoExternalUse.class) public User createAccountByAdmin(StaplerRequest req, StaplerResponse rsp, String addUserView, String successView) throws IOException, ServletException { checkPermission(Jenkins.ADMINISTER); User u = createAccount(req, rsp, false, addUserView); if (u != null && successView != null) { rsp.sendRedirect(successView); } return u; }
@DataBoundConstructor public HudsonPrivateSecurityRealm(boolean allowsSignup, boolean enableCaptcha, CaptchaSupport captchaSupport) { this.disableSignup = !allowsSignup; this.enableCaptcha = enableCaptcha; setCaptchaSupport(captchaSupport); if(!allowsSignup && !hasSomeUser()) { // if Hudson is newly set up with the security realm and there's no user account created yet, // insert a filter that asks the user to create one try { PluginServletFilter.addFilter(CREATE_FIRST_USER_FILTER); } catch (ServletException e) { throw new AssertionError(e); // never happen because our Filter.init is no-op } } }
if(selfRegistration && !validateCaptcha(si.captcha)) si.errorMessage = "Text didn't match the word shown in the image"; final User user = createAccount(si.username,si.password1); user.addProperty(new Mailer.UserProperty(si.email)); user.setFullName(si.fullname); user.save(); if (notifyUser && StringUtils.isNotEmpty(si.email)) { notifyUser(si.username, si.email, si.fullname, si.password1);
/** * Creates a user account. Intended to be called from the setup wizard. * Note that this method does not check whether it is actually called from * the setup wizard. This requires the {@link Jenkins#ADMINISTER} permission. * * @param req the request to retrieve input data from * @return the created user account, never null * @throws AccountCreationFailedException if account creation failed due to invalid form input */ @Restricted(NoExternalUse.class) public User createAccountFromSetupWizard(StaplerRequest req) throws IOException, AccountCreationFailedException { checkPermission(Jenkins.ADMINISTER); SignupInfo si = validateAccountCreationForm(req, false); if (!si.errors.isEmpty()) { String messages = getErrorMessages(si); throw new AccountCreationFailedException(messages); } else { return createAccount(si); } }
if(selfRegistration && !validateCaptcha(si.captcha)) si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_TextNotMatchWordInImage(); si.fullname = si.username; if(isMailerPluginPresent() && (si.email==null || !si.email.contains("@"))) si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_InvalidEmailAddress(); User user = createAccount(si.username,si.password1); user.setFullName(si.fullname); if(isMailerPluginPresent()) { try {
@Override public Set<Attribute> describe() { final Set<Attribute> describe = super.describe(); describe.add(new MultivaluedAttribute<HudsonPrivateSecurityRealm, UserWithPassword>("users", UserWithPassword.class) .getter(target -> target.getAllUsers().stream() .map(u -> new UserWithPassword(u.getId(), null)) // password isn't actually stored, only hashed .collect(Collectors.toList())) .setter((target, value) -> { for (UserWithPassword user : value) { target.createAccount(user.id, user.password); } } )); return describe; }
@Override protected Details authenticate(String username, String password) throws AuthenticationException { Details u = loadUserByUsername(username); if (!u.isPasswordCorrect(password)) { String message; try { message = ResourceBundle.getBundle("org.acegisecurity.messages").getString("AbstractUserDetailsAuthenticationProvider.badCredentials"); } catch (MissingResourceException x) { message = "Bad credentials"; } throw new BadCredentialsException(message); } return u; }
/** * Lets the current user silently login as the given user and report back accordingly. */ @SuppressWarnings("ACL.impersonate") private void loginAndTakeBack(StaplerRequest req, StaplerResponse rsp, User u) throws ServletException, IOException { HttpSession session = req.getSession(false); if (session != null) { // avoid session fixation session.invalidate(); } req.getSession(true); // ... and let him login Authentication a = new UsernamePasswordAuthenticationToken(u.getId(),req.getParameter("password1")); a = this.getSecurityComponents().manager.authenticate(a); SecurityContextHolder.getContext().setAuthentication(a); SecurityListener.fireLoggedIn(u.getId()); // then back to top req.getView(this,"success.jelly").forward(req,rsp); }
/** * Creates a new account from a valid signup info. A signup info is valid if its {@link SignupInfo#errors} * field is empty. * * @param si the valid signup info to create an account from * @return a valid {@link User} object created from given signup info * @throws IllegalArgumentException if an invalid signup info is passed */ private User createAccount(SignupInfo si) throws IOException { if (!si.errors.isEmpty()) { String messages = getErrorMessages(si); throw new IllegalArgumentException("invalid signup info passed to createAccount(si): " + messages); } // register the user User user = createAccount(si.username, si.password1); user.setFullName(si.fullname); if (isMailerPluginPresent()) { try { // legacy hack. mail support has moved out to a separate plugin Class<?> up = Jenkins.getInstance().pluginManager.uberClassLoader.loadClass("hudson.tasks.Mailer$UserProperty"); Constructor<?> c = up.getDeclaredConstructor(String.class); user.addProperty((UserProperty) c.newInstance(si.email)); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } user.save(); return user; }
@Restricted(NoExternalUse.class) // Jelly public boolean getAllowsSignup() { return allowsSignup(); }
/** * Determines if the security settings seem to match the defaults. Here, we only * really care about and test for HudsonPrivateSecurityRealm and the user setup. * Other settings are irrelevant. */ /*package*/ boolean isUsingSecurityDefaults() { Jenkins j = Jenkins.get(); if (j.getSecurityRealm() instanceof HudsonPrivateSecurityRealm) { HudsonPrivateSecurityRealm securityRealm = (HudsonPrivateSecurityRealm)j.getSecurityRealm(); try { if(securityRealm.getAllUsers().size() == 1) { HudsonPrivateSecurityRealm.Details details = securityRealm.loadUserByUsername(SetupWizard.initialSetupAdminUserName); FilePath iapf = getInitialAdminPasswordFile(); if (iapf.exists()) { if (details.isPasswordCorrect(iapf.readToString().trim())) { return true; } } } } catch(UsernameNotFoundException | IOException | InterruptedException e) { return false; // Not initial security setup if no transitional admin user / password found } } return false; }
if(jenkins.getSecurityRealm() == null || jenkins.getSecurityRealm() == SecurityRealm.NO_AUTHENTICATION) { // this seems very fragile try (BulkChange bc = new BulkChange(jenkins)) { HudsonPrivateSecurityRealm securityRealm = new HudsonPrivateSecurityRealm(false, false, null); jenkins.setSecurityRealm(securityRealm); String randomUUID = UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ENGLISH); securityRealm.createAccount(SetupWizard.initialSetupAdminUserName, randomUUID);
/** * @param req the request to get the form data from (is also used for redirection) * @param rsp the response to use for forwarding if the creation fails * @param validateCaptcha whether to attempt to validate a captcha in the request * @param formView the view to redirect to if creation fails * * @return * null if failed. The browser is already redirected to retry by the time this method returns. * a valid {@link User} object if the user creation was successful. */ private User createAccount(StaplerRequest req, StaplerResponse rsp, boolean validateCaptcha, String formView) throws ServletException, IOException { SignupInfo si = validateAccountCreationForm(req, validateCaptcha); if (!si.errors.isEmpty()) { // failed. ask the user to try again. req.getView(this, formView).forward(req, rsp); return null; } return createAccount(si); }
if (validateCaptcha && !validateCaptcha(si.captcha)) { si.errors.put("captcha", Messages.HudsonPrivateSecurityRealm_CreateAccount_TextNotMatchWordInImage()); } else if(!containsOnlyAcceptableCharacters(si.username)) { if (ID_REGEX == null) { si.errors.put("username", Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameInvalidCharacters()); if (isMailerPluginPresent() && (si.email == null || !si.email.contains("@"))) { si.errors.put("email", Messages.HudsonPrivateSecurityRealm_CreateAccount_InvalidEmailAddress());
User admin = securityRealm.getUser(SetupWizard.initialSetupAdminUserName); try { if (admin != null) { User newUser = securityRealm.createAccountFromSetupWizard(req); if (admin != null) { admin = null; auth = securityRealm.getSecurityComponents().manager.authenticate(auth); SecurityContextHolder.getContext().setAuthentication(auth);
User admin = securityRealm.getUser(SetupWizard.initialSetupAdminUserName); try { if(admin != null) { User u = securityRealm.createAccountByAdmin(req, rsp, "/jenkins/install/SetupWizard/setupWizardFirstUser.jelly", null); if (u != null) { if(admin != null) { a = securityRealm.getSecurityComponents().manager.authenticate(a); SecurityContextHolder.getContext().setAuthentication(a); CrumbIssuer crumbIssuer = Jenkins.getInstance().getCrumbIssuer();
@DataBoundConstructor public HudsonPrivateSecurityRealm(boolean allowsSignup, boolean enableCaptcha, boolean notifyUser) { this.disableSignup = !allowsSignup; this.enableCaptcha = enableCaptcha; this.notifyUser = notifyUser; if(!allowsSignup && !hasSomeUser()) { // if Hudson is newly set up with the security realm and there's no user account created yet, // insert a filter that asks the user to create one try { PluginServletFilter.addFilter(CREATE_FIRST_USER_FILTER); } catch (ServletException e) { throw new AssertionError(e); // never happen because our Filter.init is no-op } } }
if(selfRegistration && !validateCaptcha(si.captcha)) si.errorMessage = "Text didn't match the word shown in the image"; final User user = createAccount(si.username,si.password1); user.addProperty(new Mailer.UserProperty(si.email)); user.setFullName(si.fullname); user.save(); if (notifyUser && StringUtils.isNotEmpty(si.email)) { notifyUser(si.username, si.email, si.fullname, si.password1);