Welcome Guest! To enable all features please Login or Register.
2 Pages<12
Options
View
Go to last post Go to first unread
Offline Mikael  
#16 Posted : Tuesday, February 24, 2015 9:53:36 AM(UTC)
Mikael


Rank: YAF Forumling

Reputation:

Joined: 2/24/2015(UTC)
Posts: 3
France

Hello,
I try to integrate a forum in a existing .net MVC website.
For now I don't want to merge the authentication. I use the MVC authentication for the website and the default YAF authentication on the forum.
I followed this tutorial : https://github.com/YAFNE...ting-ASP.NET-Application
My problem is that it seems I can log in (I enter my login and my password and I haven't error message), but when I am redirected on the homepage I'm not connected.
Do you have an idea to solve this problem ?
Offline mattharper  
#17 Posted : Sunday, October 11, 2015 1:27:08 PM(UTC)
mattharper


Rank: YAF Forumling

Reputation:

Joined: 10/11/2015(UTC)
Posts: 1

Was thanked: 1 time(s) in 1 post(s)
I cannot thank you enough for posting this. I have struggled with this for the past week. I understood perfectly well how MVC membership and profiles work. The part that I was missing was simply that I don't need to utilize the Forms Auth for YAF. This was driving me insane. Genius to try the cookie name in existing Startup.Auth for MVC. I was a bout to manually maintain a sych between the two since I wasted so much time on this.

I am going to add a little more code here for anyone else coming to this post.

If you have the the default account controller from the MVC Template from VS.NET (AccountController.cs), here are the changes you need to make to it.

1. Add the references.
Quote:

using YAF.Utils;
using YAF.Core;
using System.Web.Security;
using YAF.Providers.Membership;
using System.Data;


2. Alter Register
Quote:

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"Wink;

//mjh -- Persist the user in the YAF forums as well.
CreateYAFUser(user.UserName, model.Password, model.Email);

return RedirectToAction("Index", "Secure"Wink;
}
AddErrors(result);
}

// If we got this far, something failed, redisplay form
return View(model);
}


3: ExternalLoginConfirmation
Quote:

// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage"Wink;
}

if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure"Wink;
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
CreateYAFUser(user.UserName, user.PasswordHash, model.Email);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}

ViewBag.ReturnUrl = returnUrl;
return View(model);
}


4. Add CreateYAFUser (I added mine to AccountController as static. Put it where ever you want.)
Quote:

#region YAF User Sync with MVC Membership

private static void CreateYAFUser(string sUserName, string sPassword, string email)
{
if (!UserMembershipHelper.UserExists(sUserName, email))
{

YafMembershipProvider mb = (YafMembershipProvider)Membership.Providers["YafMembershipProvider"];
int? forumUserID = 0;

if (!mb.ValidateUser(sUserName, sPassword))
{
MembershipCreateStatus status;
MembershipUser forumUser = mb.CreateUser(sUserName, sUserName, sUserName, "question", "answer", true, null, out status);
// create the user in the YAF DB as well as sync roles...
forumUserID = RoleMembershipHelper.CreateForumUser(forumUser, 1);

RoleMembershipHelper.SetupUserRoles(1, sUserName);
RoleMembershipHelper.AddUserToRole(sUserName, "Registered"Wink;

// create empty profile just so they have one
YafUserProfile userProfile = YafUserProfile.GetProfile(sUserName);
userProfile.Homepage = "fwd.com";

// setup their inital profile information
userProfile.Save();
}
else
{
DataTable results = (DataTable)YAF.Classes.Data.LegacyDb.UserFind(1, false, sUserName, sUserName, sUserName, null, null);
//DataTable results = YAF.Classes.Data.DB.UserFind(1, false, sUserName, sUserName);
if (results.Rows.Count > 0)
{
forumUserID = (int)results.Rows[0]["UserID"];
}
}
}
}

#endregion



5. Fix login and register links in YAF or remove them completely.
Quote:

Use something like this depending on your particular site structure for the YAF Links

https://localhost:44300/Account/VerifyCode/?provider=matt&returnUrl=%2Fforum%2FForum.aspx&rememberMe=true
and inside VerifyCode do a redirect to returnURL


Thanks Again!
thanks 1 user thanked mattharper for this useful post.
wanzelbin on 8/25/2017(UTC)
Offline marcelocabrera  
#18 Posted : Saturday, February 27, 2016 8:06:58 PM(UTC)
marcelocabrera


Rank: YAF Forumling

Reputation:

Joined: 2/27/2016(UTC)
Posts: 3
United States
Location: New York

HI Jumping in late on this....

I followed your example and it always seems to find the user as an existing user, in other words:

if (!UserMembershipHelper.UserExists(sUserName, email))

always returns true, so I think it is looking in the MVC 5 indentity tables, not on the YAF user tables, how do I know the static class YAF.Core.UserMembershipHelper is using the right tables?

Thanks,
MC
Offline clubnp  
#19 Posted : Saturday, April 16, 2016 3:23:29 PM(UTC)
clubnp


Rank: YAF Forumling

Reputation:

Joined: 4/16/2016(UTC)
Posts: 1
United States

Hate to necro this thread, but I think its pretty relevant and useful if someone has the answer...
I'm a fairly experienced web forms programmer, currently learning MVC and wanted to implemented YAF into a site.

In the above post user's mention this line:
DataTable results = (DataTable)YAF.Classes.Data.LegacyDb.UserFind(1, false, sUserName, sUserName, sUserName, null, null);

But LegacyDb.UserFind no longer exists in the current source code. It looks like the current code is using some sort of (I'm guessing) dependency injection?? I'm not really sure how to do what I need in this scenario. Is there an alternative to the code above??

Thanks! Smile

Edit: It feels kind of hackish, but looking at the old code something like this might work:

Code:

else
				{
                    DataTable results = UserFind(1, false, sUserName, sUserName, sUserName, null, null);
					//DataTable results = YAF.Classes.Data.DB.UserFind(1, false, sUserName, sUserName);
					if (results.Rows.Count > 0)
					{
						forumUserID = (int)results.Rows[0]["UserID"];
					}
				}
			}
		}

		public static DataTable UserFind(int boardID,bool filter, [NotNull] string userName, [NotNull] string email, [NotNull] string displayName, [NotNull] object notificationType, [NotNull] object dailyDigest)
        {		
            using (var cmd = DbHelpers.GetCommand("user_find"))		
            {		
                cmd.CommandType = CommandType.StoredProcedure;		
		
                cmd.Parameters.AddWithValue("BoardID", boardID);		
                cmd.Parameters.AddWithValue("Filter", filter);		
                cmd.Parameters.AddWithValue("UserName", userName);		
                cmd.Parameters.AddWithValue("Email", email);		
                cmd.Parameters.AddWithValue("DisplayName", displayName);		
                cmd.Parameters.AddWithValue("NotificationType", notificationType);		
                cmd.Parameters.AddWithValue("DailyDigest", dailyDigest);

				return LegacyDb.DbAccess.GetData(cmd);	
            }		
        }



Edit 2: Now that I look at it... what's the point of the else statement? Debugging?

Edited by user Saturday, April 16, 2016 3:48:46 PM(UTC)  | Reason: Not specified

Rss Feed  Atom Feed
Users browsing this topic
2 Pages<12
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Notification

Icon
Error