Double call driver for widget

Topics: General
Mar 11, 2013 at 2:50 PM
Edited Mar 11, 2013 at 2:52 PM
Widget creates two user account.
A simple example:

Part
 public class AuthenticationPhpbbWidgetPart : ContentPart<AuthenticationPhpbbWidgetPartRecord>
    {
        public virtual string ConnectionstringMysql
        {
            get { return Record.ConnectionstringMysql; }
            set { Record.ConnectionstringMysql = value; }
        }

        public virtual string UserName
        {
            get { return Record.UserName; }
            set { Record.UserName = value; }
        }
        public virtual string Password
        {
            get { return Record.Password; }
            set { Record.Password = value; }
        }
        public virtual string Prefix
        {
            get { return Record.Prefix; }
            set { Record.Prefix = value; }
        }
        public virtual string PhpDataBaseName
        {
            get { return Record.PhpDataBaseName; }
            set { Record.PhpDataBaseName = value; }
        }
    }
PartRecord
public class AuthenticationPhpbbWidgetPartRecord : ContentPartRecord
    {
        public virtual string ConnectionstringMysql { get; set; }
        public virtual string UserName { get; set; }
        public virtual string Password { get; set; }
        public virtual string Prefix { get; set; }
        public virtual string PhpDataBaseName { get; set; }
    }
Driver
 public class AuthenticationPhpbbWidgetPartDriver : ContentPartDriver<AuthenticationPhpbbWidgetPart>
    {
        private readonly IOrchardServices _services;
        private readonly IMembershipService _membershipService;  

        public AuthenticationPhpbbWidgetPartDriver(IOrchardServices services, IMembershipService membershipService)
        {
            _services = services;
            _membershipService = membershipService; 
        }

        protected override DriverResult Display(AuthenticationPhpbbWidgetPart part, string displayType, dynamic shapeHelper)
        {
            var user = _membershipService.GetUser("testUser");
            if (user == null)
            {
                user = _membershipService.CreateUser(new CreateUserParams("testUser", "passwordUser", "testUser@gmail.com", null, null, false));
            }
            return ContentShape("Parts_authenticationPhpbbWidgetPart",
                                () => shapeHelper.Parts_authenticationPHPbbWidget(
                                    NameUser: "rrrr", // model.nameUser,
                                    IsAuthentication: true // model.isAuthentication
                                          ));
        }
}
Handler
 public class AuthenticationPHPbbWidgetHandler  : ContentHandler
    {       
        public AuthenticationPHPbbWidgetHandler(IRepository<AuthenticationPhpbbWidgetPartRecord> repository)
        {       
            Filters.Add(StorageFilter.For(repository));  
        }  
    }
Migration
 public int Create()
        {
            SchemaBuilder.CreateTable("AuthenticationPhpbbWidgetPartRecord", table => table
                                                                            .ContentPartRecord()
                                                                            .Column("ConnectionstringMYSQL", DbType.String)
                                                                            .Column("UserName", DbType.String)
                                                                            .Column("Password", DbType.String)
                                                                            .Column("Prefix", DbType.String)
                                                                            .Column("PHPDataBaseName", DbType.String)
                );

            ContentDefinitionManager.AlterPartDefinition(
                "AuthenticationPhpbbWidgetPart",
                builder => builder.Attachable());

            ContentDefinitionManager.AlterTypeDefinition(
                         "AuthenticationPhpbbWidgetFinal",
                         cfg => cfg
                                    .WithPart("AuthenticationPhpbbWidgetPart")
                                    .WithPart("CommonPart")
                                    .WithPart("WidgetPart")
                                    .WithSetting("Stereotype", "Widget")
             );
            return 1;
        }
Layout.cshtml
<div class="logOnPhp">
    @if (Model.LogOnPhp != null)
    {    
        @Zone(Model.LogOnPhp)  
    }
</div>
After starting the application creates two user.
Please help me to solve the problem.
Coordinator
Mar 11, 2013 at 5:45 PM
I don't understand why you would create a user in a Display method. Display is supposed to be side-effect-free.
Mar 12, 2013 at 7:13 AM
how to create a user without a controller without HTTPPOST?
The user_account creates in the background, without the user action.
Coordinator
Mar 12, 2013 at 8:27 AM
It's hard to give an answer if the question keeps changing. What is it exactly that you are trying to do?
Mar 12, 2013 at 11:50 AM
I want to make transparent authorization.
There is a forum of PHPbb, MySql base with users
When calling on a site of the user, it reads Phpbb (sid) cookies, after from MySql undertakes on sid email, nameUser and the same user in orchand is created. If such user already is in orchand, there is simply his authorization. Now everything works, but in the Orchand base two userAccount are created

Now rebuild widget, all ok.

Driver
public class AuthenticationPhpbbWidgetPartDriver : ContentPartDriver<AuthenticationPhpbbWidgetPart>
    {
        private readonly IOrchardServices _services; 
        public AuthenticationPhpbbWidgetPartDriver(IOrchardServices services) 
        {
            _services = services; 
        }

        protected override DriverResult Display(AuthenticationPhpbbWidgetPart part, string displayType, dynamic shapeHelper) {
            var user = _services.WorkContext.CurrentUser;
            bool isAuthentication =false;
            string userName = "";
            if (user!=null) {
                isAuthentication = true;
                userName = user.UserName;
            }        
            return ContentShape("Parts_authenticationPhpbbWidgetPart",
                                () => shapeHelper.Parts_authenticationPHPbbWidget(
                                    NameUser: userName, 
                                    IsAuthentication: isAuthentication 
                                          ));
        }
Service
 public interface IAuthenticationPhphbbService : IDependency
    {
      string LogOn();
    }
    public class AuthenticationPhphbbService : IAuthenticationPhphbbService
    {
        private readonly IOrchardServices _orchardServices;
        private readonly IMembershipService _membershipService;
        private readonly IAuthenticationService _authenticationService; 
        public ILogger Logger { get; set; }
        public Localizer T { get; set; }
        public AuthenticationPhphbbService(
                                 IMembershipService membershipService,
                                 IAuthenticationService authenticationService,
                                 IOrchardServices orchardServices)
        {
          
            _membershipService = membershipService;
            _authenticationService = authenticationService;
            _orchardServices = orchardServices;  
            Logger = NullLogger.Instance;
            T = NullLocalizer.Instance;
        }
        public string LogOn()
        {
            string phpbbSid = "";
            var pHPbbWidgetPart = _orchardServices.ContentManager.Query<AuthenticationPhpbbWidgetPart, AuthenticationPhpbbWidgetPartRecord>().Where(p => p.Id != null).List().FirstOrDefault();
            phpbbSid = LogOnPHPCookies(); 
            if (!string.IsNullOrWhiteSpace(phpbbSid))
            {
                GetUserPHPbb(pHPbbWidgetPart, phpbbSid);
            }
            var model = CreateLogOnPHPViewModel(); 
            return model.nameUser;
        }
        private string GetUserPHPbb(AuthenticationPhpbbWidgetPart authenticationPhpbbWidgetPart, string phpbbSid)
        {
            if (authenticationPhpbbWidgetPart != null)
            {
                string emailPhpFound = "";
                string userNameFound = "";
                string userPasswordFound = "";
                string ConnectionString = "server=" + authenticationPhpbbWidgetPart.ConnectionstringMysql + ";uid=" + authenticationPhpbbWidgetPart.UserName + ";password=" + authenticationPhpbbWidgetPart.Password + ";database=" + authenticationPhpbbWidgetPart.PhpDataBaseName + ";auto enlist=false;";
                try
                {
                    using (var connection = new MySqlConnection(ConnectionString))
                    {
                        using (var cmd = connection.CreateCommand())
                        {
                            connection.Open();
                            cmd.CommandText = "SELECT phpbb3_users.username, phpbb3_users.user_email, phpbb3_users.user_password FROM phpbb3_sessions INNER JOIN phpbb3_users  ON phpbb3_users.user_id = phpbb3_sessions.session_user_id Where phpbb3_users.username != 'Anonymous' and NOT EXISTS (Select * from phpbb3_banlist Where  phpbb3_banlist.ban_userid= phpbb3_users.user_id) and phpbb3_sessions.session_id='" + phpbbSid + "'";
                            using (var reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    emailPhpFound = reader.GetString(reader.GetOrdinal("user_email"));
                                    userNameFound = reader.GetString(reader.GetOrdinal("username"));
                                    userPasswordFound = reader.GetString(reader.GetOrdinal("user_password"));
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                      Logger.Information("Error connect or select to MySQL", DateTime.Now + " Exception: " + e.Message);
                }
                if (!String.IsNullOrEmpty(emailPhpFound))
                {
                    var user = _membershipService.GetUser(userNameFound);
                    if (user == null)
                    {
                        user = _membershipService.CreateUser(new CreateUserParams(userNameFound, userPasswordFound, emailPhpFound, null, null, false));
                       
                    }
                    if (_authenticationService.GetAuthenticatedUser() != user)
                    {
                        _authenticationService.SignIn(user, true);
                    } 
                }
            }
            return null;
        }
        private string LogOnPHPCookies()
        {
            HttpCookie phpbbCookie = HttpContext.Current.Request.Cookies["phpbb3_4addc_sid"] ?? new HttpCookie("noCookie");
            return phpbbCookie.Value;
        }
        private AuthenticationPhpbbViewModel CreateLogOnPHPViewModel()
        {
            AuthenticationPhpbbViewModel logOnPhpView = new AuthenticationPhpbbViewModel();
            var user = _orchardServices.WorkContext.CurrentUser;
            logOnPhpView.isAuthentication = false;
            if (user != null)
            {
                logOnPhpView.isAuthentication = true;
                logOnPhpView.nameUser = user.UserName;    
            }
            return logOnPhpView;
        }

    }
Controller
public class AuthenticationPhpbbJSON : Controller
    {
       private readonly IAuthenticationPhphbbService _authenticationPhphbbService;

       public AuthenticationPhpbbJSON(IAuthenticationPhphbbService authenticationPhphbbService) //, IOrchardServices services, IMembershipService membershipService)
        {  
            _authenticationPhphbbService = authenticationPhphbbService;
        }

        public ActionResult Index() {
            string name = "";
            JsonResult jj= new JsonResult();
            jj.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            name = _authenticationPhphbbService.LogOn();
            jj.Data = name;
            return jj;
        }
    }
cshtml
<script type="text/javascript">   
    $(function () { 
        $(document).ready(function() {
            if (@Model.IsAuthentication='False') {
                $.get('../AuthenticationPhpbbJSON/', function(nameUserPhp) {
                    if (nameUserPhp!=null && nameUserPhp !='') {
                      var nameUser = $('#nameUser');
                    nameUser.text(nameUserPhp);
                    $('#authPhpBB').css('display', '');
                    $('#authOrchard').css('display', 'none');
                    }
                });
            }
        }
        );
    }); 
</script>
<div class="right-item">
    @if (Model.IsAuthentication)
    {  
        @T("Welcome ") @Model.NameUser  
        <a href="~/LogOffPHP">@T("Log off")</a>         
    }
    else
    {
        <div id="authOrchard">
            <img src=@Href("~/Modules/authenticationPHPbb/Images/key.gif") height="16" width="16"><a
                href="http://www.content.magistral8.ru/forum/ucp.php?mode=login"><strong style="margin-left: 0;">@T("Please Log In")</strong></a>
        </div>
        <div id="authPhpBB" style="display: none;">
            @T("Welcome ")
            <label id="nameUser">
            </label>
            <a href="~/LogOffPHP">@T("Log off")</a>
        </div>       
    }
</div>
thanks for the help
Coordinator
Mar 13, 2013 at 12:15 AM
I'm confused, is your problem fixed?
Mar 13, 2013 at 6:19 AM
Problem fixed.
Thanks.