view Agendas/trunk/src/Agendas.Web/Controllers/AccountController.cs @ 96:1eb5a0e531bf

Funcionamiento con cuenta interna y con cuenta de twitter, falta unificar usuarios Estructura de aspnetdb dentro de base de datos de altnet hispano, se debe ejecutar: C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe para crear dicha estructura, de todas formas el objetivo seria tener una tabla de usuario y password interna, no parecería ser necesaria toda la estructura de aspnetdb
author Nelo@Kenia.neluz.int
date Sat, 04 Jun 2011 19:37:02 -0300
parents db4b1e2cae49
children 1ee5711256db
line wrap: on
line source

using System;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using AltNetHispano.Agendas.Domain;
using AltNetHispano.Agendas.Factories;
using AltNetHispano.Agendas.Twitter;
using AltNetHispano.Agendas.Web.Models;
using AltNetHispano.Agendas.Web.Services;

namespace AltNetHispano.Agendas.Web.Controllers
{
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
				if (MembershipService.ValidateUser(model.UserName, model.Password))
				{
					var personaService = AgendaFactory.GetPersonaService();
					if (personaService.Validate(IdentityProviderEnum.BuiltIn, model.UserName))
					{
						FormsService.SignIn(Identification.Map[(int)IdentityProviderEnum.BuiltIn] + model.UserName, model.RememberMe);
						if (Url.IsLocalUrl(returnUrl))
							return Redirect(returnUrl);
						return RedirectToAction("Index", "Home");
					}
				}
            	ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }

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

		public ActionResult TwitterLogOn()
		{
			var oAuth = new OAuthTwitter();

			if (Request["oauth_token"] == null)
			{
				//Redirect the user to Twitter for authorization.
				//Using oauth_callback for local testing.
				var action = Url.Action("TwitterLogOn");
				var url = Request.Url.Scheme + "://" + Request.Url.Host +
				          (Request.Url.Port != 80 ? ":" + Request.Url.Port : string.Empty) + action;

				oAuth.CallBackUrl = url;
				Response.Redirect(oAuth.AuthorizationLinkGet());
			}
			else
			{
				//Get the access token and secret.
				oAuth.AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]);
				if (oAuth.TokenSecret.Length > 0)
				{
					//We now have the credentials, so make a call to the Twitter API.
					const string url = "http://twitter.com/account/verify_credentials.xml";
					string xml = oAuth.OAuthWebRequest(OAuthTwitter.Method.GET, url, String.Empty);

					var username = GetXmlContent(xml, "screen_name");
					var nombre = GetXmlContent(xml, "name");

					var personaService = AgendaFactory.GetPersonaService();
					if (personaService.Validate(IdentityProviderEnum.Twitter, username, nombre))
					{
						FormsService.SignIn(Identification.Map[(int)IdentityProviderEnum.Twitter]+username, false);
						return RedirectToAction("Index", "Home");
					}
					ModelState.AddModelError("", "The user name or password provided is incorrect.");


					//POST Test
					//url = "http://twitter.com/statuses/update.xml";
					//xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, "status=" + oAuth.UrlEncode("Hello @swhitley - Testing the .NET oAuth API"));
					//apiResponse.InnerHtml = Server.HtmlEncode(xml);
				}
			}

			return RedirectToAction("LogOn");
		}

    	private static string GetXmlContent(string xml, string tagName)
    	{
    		var tagStart = "<" + tagName + ">";
    		var tagEnd = "</" + tagName + ">";

    		var start = xml.IndexOf(tagStart)+tagStart.Length;
			if (start>tagStart.Length)
			{
				var end = xml.IndexOf(tagEnd, start);
				if (end>0)
				{
					return xml.Substring(start, end - start);
				}
			}
    		return string.Empty;
    	}

    	// **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
					var personaService = AgendaFactory.GetPersonaService();
					if (personaService.Validate(IdentityProviderEnum.BuiltIn, model.UserName, model.Nombre))
					{
						FormsService.SignIn(Identification.Map[(int)IdentityProviderEnum.BuiltIn] + model.UserName, false);
						return RedirectToAction("Index", "Home");
					}
                }
                ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}