当前位置: 首页 > 面试题库 >

创建新用户时自动使用用户名和随机密码生成电子邮件

李疏珂
2023-03-14
问题内容

我创建了一个类NewUserEmail以在创建新用户时自动生成带有用户名和密码的电子邮件。我能够创建密码,但是每当尝试使用该密码登录时,它都不会登录。我无法生成我的邮件。请指导我,让我知道我的代码出了什么问题:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.jscript.ClasspathScriptLocation;
import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

public class NewUserEmail implements NodeServicePolicies.OnCreateNodePolicy {

    private Logger logger = Logger.getLogger(NewUserEmail.class);
    private PolicyComponent policyComponent;
    private NodeService nodeService;
    private PersonService personService;
    private ServiceRegistry serviceRegistry;
    protected String userName = null;
    protected String password = null;
    protected String email = null;
    protected String subject = null;
    protected String body = null;

    private static final String NEW_USER_EMAIL_TEMPLATE = "alfresco/module/demoact1-repo/template/new_user_email.ftl";
    private static final String EMAIL_FROM = "no-reply@eisenvault.com";

    public void init() {
        this.email = "";
        this.userName = "";
        this.password = "";
        this.subject = "New User Alfresco";
        this.body = "";
        this.policyComponent.bindClassBehaviour(
                QName.createQName(NamespaceService.ALFRESCO_URI, "onCreateNode"),
                ContentModel.TYPE_PERSON,
                new JavaBehaviour(this, "ReportUser", org.alfresco.repo.policy.JavaBehaviour.NotificationFrequency.EVERY_EVENT)
        );
    }

    public void onCreateNode(ChildAssociationRef childAssocRef) {
        if (logger.isInfoEnabled()) logger.info(" NewUserEmail Node create policy fired");
    }

    public void setNodeService(NodeService nodeService) {
        this.nodeService = nodeService;
    }

    public void setPolicyComponent(PolicyComponent policyComponent) {
        this.policyComponent = policyComponent;
    }

    public void setServiceRegistry(ServiceRegistry serviceRegistry) {
        this.serviceRegistry = serviceRegistry;
    }

    public String getSubject() {
        return this.subject;
    }

    public String getBody() {
        return this.body;
    }

    public String getEmail() {
        return this.email;
    }

    public String getUserName() {
        return this.userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    public void ReportUser(ChildAssociationRef childAssocRef) {
        NodeRef personRef = childAssocRef.getChildRef();
        this.userName = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_USERNAME);
        this.email = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_EMAIL);
        sendEmail();
    }


    public void sendEmail() throws AlfrescoRuntimeException {
        Map<String, Object> templateModel = new HashMap<String, Object>();
        if (getEmail() != null && getEmail() != "") {
            Set<NodeRef> result = serviceRegistry.getPersonService().getPeopleFilteredByProperty(ContentModel.PROP_EMAIL, getEmail(), 1);
            if (result.size() == 1) {
                changePassword(getUserName());
                ClasspathScriptLocation location = new ClasspathScriptLocation(NEW_USER_EMAIL_TEMPLATE);
                try {
                    if (location.getInputStream() != null) {
                        // Check that there is a template
                        templateModel.put("userName", getUserName());
                        templateModel.put("password", getPassword());
                        this.body = serviceRegistry.getTemplateService().processTemplate("freemarker", NEW_USER_EMAIL_TEMPLATE, templateModel);
                    }
                } catch (AlfrescoRuntimeException e) {
                    // If template isn't found, email is constructed "manually"
                    logger.error("Email Template not found " + NEW_USER_EMAIL_TEMPLATE);
                    this.body = "<html> <body> <p> A new User has been created.</p>" +
                            "<p>Hello, </p><p>Your username is " + getUserName() + " and your " +
                            "password is " + getPassword() + "</p> " +
                            "<p>We strongly advise you to change your password when you log in for the first time.</p>" +
                            "Regards</body> </html>";
                    //send();
                }
            }
        }
    }

    protected void send() {
        MimeMessagePreparator mailPreparer = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws MessagingException {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(getEmail());
                message.setSubject(getSubject());
                message.setText(getBody(), true);
                message.setFrom(EMAIL_FROM);
            }
        };
    }

    public void changePassword(String password) {
        AuthenticationUtil.setRunAsUserSystem();
        Set<NodeRef> result = serviceRegistry.getPersonService().getPeopleFilteredByProperty(ContentModel.PROP_EMAIL, getEmail(), 1);
        if (result.size() == 1) {
            Object[] userNodeRefs = result.toArray();
            NodeRef userNodeRef = (NodeRef) userNodeRefs[0];
            String username = (String) serviceRegistry.getNodeService().getProperty(userNodeRef, ContentModel.PROP_USERNAME);
            // Generate random password
            String newPassword = Password.generatePassword();
            char[] cadChars = new char[newPassword.length()];
            for (int i = 0; i < newPassword.length(); i++) {
                cadChars[i] = newPassword.charAt(i);
            }
            serviceRegistry.getAuthenticationService().setAuthentication(username, newPassword.toCharArray());
            setPassword(newPassword);
            System.out.println("Password is :" + newPassword);
        }
    }

}

问题答案:

以下是一个可行的解决方案。

资源/alfresco/extension/new-user-email-context.xml:

<?xml version='1.0' encoding='UTF-8'?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">    
    <bean id="newUserEmail" class="demo.NewUserEmail">
        <property name="policyComponent" ref="policyComponent"/>
        <property name="nodeService" ref="nodeService"/>
        <property name="personService" ref="personService"/>
        <property name="passwordGenerator" ref="passwordGenerator"/>
        <property name="authenticationService" ref="authenticationService"/>
    </bean>
</beans>

demo.NewUserEmail.java:

package demo;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.*;
import org.alfresco.repo.security.authentication.PasswordGenerator;
import org.alfresco.service.cmr.repository.*;
import org.alfresco.service.cmr.security.*;
import org.alfresco.util.PropertyCheck;
import org.springframework.beans.factory.InitializingBean;

public class NewUserEmail implements 
    NodeServicePolicies.OnCreateNodePolicy, InitializingBean {

    @Override
    public void onCreateNode(ChildAssociationRef childAssocRef) {
        notifyUser(childAssocRef);
    }

    private void notifyUser(ChildAssociationRef childAssocRef) {
        NodeRef personRef = childAssocRef.getChildRef();
        // get the user name
        String username = (String) this.nodeService.getProperty(
            personRef, ContentModel.PROP_USERNAME);
        // generate the new password (Alfresco's rules)
        String newPassword = passwordGenerator.generatePassword();
        // set the new password
        authenticationService.setAuthentication(username, newPassword.toCharArray());
        // send default notification to the user
        personService.notifyPerson(username, newPassword);
    }

    private PolicyComponent policyComponent;
    private NodeService nodeService;
    private PersonService personService;
    private PasswordGenerator passwordGenerator;
    private MutableAuthenticationService authenticationService;

    public void setPolicyComponent(PolicyComponent policyComponent) {
        this.policyComponent = policyComponent;
    }

    public void setNodeService(NodeService nodeService) {
        this.nodeService = nodeService;
    }

    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    public void setPasswordGenerator(PasswordGenerator passwordGenerator) {
        this.passwordGenerator = passwordGenerator;
    }

    public void setAuthenticationService(AuthenticationService authenticationService) {
        if (authenticationService instanceof MutableAuthenticationService) {
            this.authenticationService = (MutableAuthenticationService) authenticationService;
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        PropertyCheck.mandatory(this, "policyComponent", policyComponent);
        PropertyCheck.mandatory(this, "nodeService", nodeService);
        PropertyCheck.mandatory(this, "passwordGenerator", passwordGenerator);
        PropertyCheck.mandatory(this, "authenticationService", authenticationService);
        PropertyCheck.mandatory(this, "personService", personService);

        this.policyComponent.bindClassBehaviour(
                NodeServicePolicies.OnCreateNodePolicy.QNAME,
                ContentModel.TYPE_PERSON,
                new JavaBehaviour(this,
                        NodeServicePolicies.OnCreateNodePolicy.QNAME.getLocalName(),
                        Behaviour.NotificationFrequency.TRANSACTION_COMMIT
                )
        );
    }


}


 类似资料:
  • 问题内容: 根据Firebase网站,我正在使用以下代码创建新用户: 创建新用户时,如何在“身份验证”中添加显示名称和照片网址? 此链接显示从Auth中的身份提供者返回的受支持的用户数据。 问题答案: 您可以使用课程..检查此文档来更新您的个人资料。

  • 本文向大家介绍Shell创建用户并生成随机密码脚本分享,包括了Shell创建用户并生成随机密码脚本分享的使用技巧和注意事项,需要的朋友参考一下 创建随机数的方法: 在Linux中有一个设备/dev/urandom是用来产生随机数序列的。利用该设备我们可以根据在需要生成随机字符串。 比如我们要产生一个8位的字母和数字混合的随机密码,可以这样: 其实,linux已经提供有个系统环境变量了。 可能有疑问

  • 我正在尝试使用jmeter模拟在我的测试站点上创建的500个用户名/密码。主页有3个字段,用户名、电子邮件地址和密码。如何让jmeter自动填充这些字段?下一个问题是,jmeter是否可以转到下一页,例如填写信用信息?

  • 我正在尝试在Jenkins中配置电子邮件通知。但它显示了以下错误。。。在此处输入图像描述 我用管理员帐号试过了,然后用我自己的gmil帐号试过了 错误:: 发送电子邮件失败 javax.mail.身份验证失败异常: 535-5.7.8用户名和密码不接受。在535 5.7.8了解更多https://support.google.com/mail/?p=BadCredentialsx11sm87366

  • 我使用下面显示的简单电子邮件密码进行注册活动以在Firebase上创建新用户 创建帐户活动 公共类CreateCountActivity扩展了AppCompatActivity{ } 当用户输入信息时,它启动方法CreateAccount(),然后当任务成功时,它更新用户配置文件并设置显示名称并启动MainActivity。但它启动主活动,不显示用户名。 主要活动 谁能帮我解决这个问题,当用户退出