How to require Username Password and CompanyId on WebSecurity.Login in MVC 4 application using Simple membership

StackOverflow https://stackoverflow.com/questions/20074175

Question

I need to implement login for users that require not only Username and Password , but also CompanyId. The username is unique only for a company so there could be many occurrences of a username with a different companyId as a record. I tried to extend my current simple membership provider, but i guess that is not working for me(How to make WebSecurity.Login to login using username or email?). My UserProfile table looks like this

[Table("UserProfile")]
public partial class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int  CompanyId { get; set; }

Can i validate user by userId and password. I need to make something like this:

public class ExtendedSimpleMembershipProvider : SimpleMembershipProvider
{
    public override bool ValidateUser(string username, string password, int companyId)
    {
            int userId = GetUserId(username, companyId);
            return SomehowValidateUser(userId, password);
    }

    private int GetUserId(string username, int companyId)
    {

        var userId = (from users
                      in context.UserProfile
                      where (users.UserName.ToLower() == username) || (users.CompanyId == companyId)
                      select users.UserId).First();
        return userId;
    }
}

How would that work ?

Was it helpful?

Solution 2

It worked out this way :

    public static bool ValidateUser(string username, string password, string companyName)
    {
        int companyId = MyRepository.GetCompanyIdByName(companyName);

        int? userId = companyId == 0 ? null : MyRepository.GetUserId(username, companyId);

        if (userId.HasValue && userId.Value != 0)
        {
            var userKey = username + "@" + companyName.ToLower();
            return WebSecurity.Login(userKey, password);
        }
        else
        {
            return false;
        }
    }

OTHER TIPS

If you're asking how to validate the userID and password once you've validated the username and companyId, try exposing the WebSecurity class directly.

public override bool ValidateUser(string username, string password, int companyId)
{
    // DEV NOTE: change your GetUserId() return to int?
    int? userId = GetUserId(username, companyId);
    if (userID.HasValue())
        return WebSecurity.Login(username, password);
    else
        return false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top