Click here to Skip to main content
15,885,767 members
Articles / Desktop Programming / XAML

A Sample Silverlight 4 Application Using MEF, MVVM, and WCF RIA Services - Part 1

Rate me:
Please Sign up or sign in to vote.
4.84/5 (108 votes)
7 Jul 2011CPOL9 min read 2.1M   30.9K   298  
Part 1 of a series describing the creation of a Silverlight business application using MEF, MVVM Light, and WCF RIA Services.

namespace IssueVision.Data.Web
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Data;
    using System.Linq;
    using System.ServiceModel.DomainServices.Server;
    using System.ServiceModel.DomainServices.EntityFramework;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server.ApplicationServices;
    using System.Web;
    using System.Web.Security;    

    [EnableClientAccess()]
    public class AuthenticationService : LinqToEntitiesDomainService<IssueVisionEntities>, IAuthentication<LoginUser>
    {
        #region "Private Data"
        private static LoginUser DefaultUser = new LoginUser()
        {
            Name = String.Empty,
            Password = String.Empty,
            Roles = new List<string>()
        };
        #endregion "Private Data"

        #region "IAuthentication<LoginUser> Interface implementation"
        /// <summary>
        /// Get the user information for the currently login user
        /// </summary>
        /// <returns></returns>
        [Query(IsComposable = false)]
        public LoginUser GetUser()
        {
            if ((this.ServiceContext != null) &&
                (this.ServiceContext.User != null) &&
                this.ServiceContext.User.Identity.IsAuthenticated)
            {
                return this.GetUserByName(this.ServiceContext.User.Identity.Name);
            }
            return AuthenticationService.DefaultUser;
        }

        /// <summary>
        /// Not implemented.
        /// </summary>
        /// <param name="user"></param>
        [Update]
        public void UpdateUser(LoginUser user)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Validate and login
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="isPersistent"></param>
        /// <param name="customData"></param>
        /// <returns></returns>
        public LoginUser Login(string userName, string password, bool isPersistent, string customData)
        {
            try
            {
                string userData;

                if (this.ValidateUser(userName, password, customData, out userData))
                {
                    // if IsPersistent is true, will keep logged in for up to a week (or until you logout)
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        /* version */ 1, 
                        userName,
                        DateTime.Now, DateTime.Now.AddDays(7),
                        isPersistent,
                        userData,
                        FormsAuthentication.FormsCookiePath);

                    string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                    if (ticket.IsPersistent)
                    {
                        authCookie.Expires = ticket.Expiration;
                    }

                    HttpContextBase httpContext = (HttpContextBase)ServiceContext.GetService(typeof(HttpContextBase));
                    httpContext.Response.Cookies.Add(authCookie);

                    return this.GetUserByName(userName);
                }
                return AuthenticationService.DefaultUser;
            }
            catch (Exception ex)
            {
                Exception actualException = ex;
                while (actualException.InnerException != null)
                {
                    actualException = actualException.InnerException;
                }
                throw actualException;
            }
        }

        /// <summary>
        /// Logout
        /// </summary>
        /// <returns></returns>
        public LoginUser Logout()
        {
            FormsAuthentication.SignOut();
            return AuthenticationService.DefaultUser;
        }
        #endregion "IAuthentication<LoginUser> Interface implementation"

        #region "Private Methods"
        /// <summary>
        /// Get user by user name
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        private LoginUser GetUserByName(string userName)
        {
            User foundUser = this.ObjectContext.Users.FirstOrDefault(u => u.Name == userName);

            if (foundUser != null)
            {
                return new LoginUser()
                {
                    Name = foundUser.Name,
                    PasswordHash = foundUser.PasswordHash,
                    PasswordSalt = foundUser.PasswordSalt,
                    UserType = foundUser.UserType,
                    ProfileReset = foundUser.ProfileReset
                };
            }
            else
                return null;
        }

        /// <summary>
        /// Validate user with password
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private bool ValidateUser(string username, string password, string customData, out string userData)
        {
            userData = null;

            LoginUser foundUser = this.GetUserByName(username);

            if (foundUser != null)
            {
                // generate password hash
                string passwordHash = HashHelper.ComputeSaltedHash(password, foundUser.PasswordSalt);

                if (string.Equals(passwordHash, foundUser.PasswordHash, StringComparison.Ordinal))
                {
                    userData = foundUser.UserType;
                    return true;
                }
                else
                    return false;
            }
            else
                return false;
        }
        #endregion "Private Methods"
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Weidong has been an information system professional since 1990. He has a Master's degree in Computer Science, and is currently a MCSD .NET

Comments and Discussions