public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
        {
            string lLoginCookie = new Tuple<object, object>(model.AuthenticatedClient.GetHashCode(),
                DateTime.Now.GetHashCode()).GetHashCode().ToString();

            using (umfrageDB db = new umfrageDB())
            {
                string lAuthHash =
                    MD5.Create()
                        .ComputeHash(Encoding.UTF8.GetBytes(model.AuthenticatedClient.UserInformation.Id))
                        .ToHex(false);

                if ((from p in db.users
                    where p.AuthenticationId == lAuthHash
                    select p).Any())
                {
                    db.users.Where(user => user.AuthenticationId == lAuthHash)
                        .Set(user => user.Guid, lLoginCookie).Set(user => user.LastLogin, DateTime.Now)
                        .Update();
                }
                else
                {
                    user lUser = new user
                    {
                        AuthenticationId = lAuthHash,
                        Guid = lLoginCookie,
                        TimeCreated = DateTime.Now,
                        LastLogin = DateTime.Now
                    };
                    db.Insert(lUser);
                }
            }

            return nancyModule.Response.AsRedirect("/").WithCookie("id", lLoginCookie);
        }
        public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
        {
            var email = model.AuthenticatedClient.UserInformation.Email;
            User user = null;
            var documentStore = nancyModule.Context.Items["RavenDocumentStore"] as IDocumentStore;
            using(var session = documentStore.OpenSession())
            {
                user = session.Query<User>()
                              .FirstOrDefault(x => x.Email == email);

                if (user == null)
                {
                    user = new User
                    {
                        Email = email,
                        UserName = email,
                        Guid = Guid.NewGuid()
                    };

                    session.Store(user);
                    session.SaveChanges();
                }

            }

            return nancyModule.LoginAndRedirect(user.Guid, DateTime.UtcNow.AddDays(7), string.Format("/{0}", user.Id));
        }
 public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
 {
     switch((string)nancyModule.Context.Request.Query.providerkey)
     {
         case "google":
             var googleLinkedAccount = new GoogleLinkedAccount(nancyModule, model);
             return model.AuthenticatedClient.ToString() + googleLinkedAccount.Respond().ToString();
         case "facebook":
             return "Sorry, facebook is not yet supported. Check again later.";
         default:
             return "No valid authentication provider found!!!";
     }
 }
        public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
        {
            if (model.Exception != null) {
                return new RedirectResponse("/bouncercat");
            }

            var sessionKey = "Session_" + model.AuthenticatedClient.AccessToken.PublicToken;
            BlobCache.Secure.InsertObject(sessionKey, model.AuthenticatedClient, TimeSpan.FromDays(1)).First();

            BlobCache.Secure.GetOrFetchObject("build-user", () => Observable.Return(model.AuthenticatedClient));

            nancyModule.Session["User"] = sessionKey;
            return new RedirectResponse("/");
        }
        public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
        {
            Response response;

            if (model.ReturnUrl != null)
            {
                response = nancyModule.Response.AsRedirect("~" + model.ReturnUrl);
            }
            else
            {
                response = nancyModule.AsRedirectQueryStringOrDefault("~/");

                if (nancyModule.IsAuthenticated())
                {
                    response = nancyModule.AsRedirectQueryStringOrDefault("~/account/#identityProviders");
                }
            }

            if (model.Exception != null)
            {
                nancyModule.Request.AddAlertMessage("error", model.Exception.Message);
            }
            else
            {
                UserInformation information = model.AuthenticatedClient.UserInformation;
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, information.Id));
                claims.Add(new Claim(ClaimTypes.AuthenticationMethod, model.AuthenticatedClient.ProviderName));

                if (!String.IsNullOrEmpty(information.UserName))
                {
                    claims.Add(new Claim(ClaimTypes.Name, information.UserName));
                }

                if (!String.IsNullOrEmpty(information.Email))
                {
                    claims.Add(new Claim(ClaimTypes.Email, information.Email));
                }

                nancyModule.SignIn(claims);
            }

            return response;
        }
        /// <summary>
        /// Called when we receive a callback from a social provider
        /// </summary>
        public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
        {
            if (model.Exception == null)
            {
                var userInfo = model.AuthenticatedClient.UserInformation;
                var providerName = model.AuthenticatedClient.ProviderName;

                // See if we already know about this provider/id
                UserIdentity userIdentity = null;// ReadStore.UserIdentities.FindAllByProviderAndId(providerName, userInfo.Id).FirstOrDefault();

                // Deal with an unknown/already known social identity
                return userIdentity == null
                    ? HandleUnknownIdentity(nancyModule)
                    : HandleKnownIdentity(userIdentity, nancyModule, model.ReturnUrl);
            }

            // An error occured, we didn't get permission, etc...
            //nancyModule.AddAlertMessage("error", model.Exception.Message);

            // If a user was logged in, he got here from the linking page
            // If the user isn't logged in, he got here from the login page
            return nancyModule.Response.AsRedirect(nancyModule.IsAuthenticated() ? "~/account/identity" : "~/account/login");
        }
Example #7
0
        private dynamic AuthenticateCallback()
        {
            var providerKey = (string)Request.Query.providerkey;

            if (string.IsNullOrEmpty(providerKey))
            {
                throw new ArgumentException(
                          "ProviderKey value missing. You need to supply a valid provider key so we know where to redirect the user Eg. providerkey=google.");
            }

            var previousRedirectUrl = string.IsNullOrEmpty((string)Cache[SessionKeyRedirectToProviderUrl])
                                          ? "N.A."
                                          : (string)Cache[SessionKeyRedirectToProviderUrl];

            TraceSource.TraceInformation("Previous Redirect Url: " + previousRedirectUrl);

            #region Deserialize Tokens, etc.

            // Retrieve any (previously) serialized access token stuff. (eg. public/private keys and state).
            // TODO: Check if this is an access token or an auth token thingy-thing.
            TraceSource.TraceVerbose("Retrieving (local serializaed) AccessToken, State and RedirectToUrl.");
            var state         = Cache[SessionKeyState] as string;
            var redirectToUrl = Cache[SessionKeyRedirectToUrl] as string;

            #endregion

            // Lets now start to setup the view model.
            var model = new AuthenticateCallbackData();

            #region Retrieve the User Information

            try
            {
                // Which provider did we just authenticate with?
                var provider = GetAuthenticationProvider(providerKey);
                model.ProviderName = provider.Name;

                // Where do we return to, after we've authenticated?
                var callbackUri = GenerateCallbackUri(provider.Name);

                var queryString = new NameValueCollection();
                foreach (var key in Request.Query.Keys)
                {
                    queryString.Add(key, Request.Query[key]);
                }

                // Grab the user information.
                model.AuthenticatedClient = provider.AuthenticateClient(queryString, state, callbackUri);
            }
            catch (Exception exception)
            {
                TraceSource.TraceError(exception.Message);
                model.Exception = exception;
            }

            #endregion

            // Do we have an optional redirect resource? Usually a previous referer?
            if (redirectToUrl != null)
            {
                TraceSource.TraceVerbose("Found redirectToUrl: " + redirectToUrl);
                model.ReturnUrl = redirectToUrl;
            }

            // Finally! We can hand over the logic to the consumer to do whatever they want.
            TraceSource.TraceVerbose("About to execute your custom callback provider logic.");
            return(_callbackProvider.Process(this, model));
        }
        private dynamic AuthenticateCallback()
        {
            var providerKey = (string) Request.Query.providerKey;
            if (string.IsNullOrEmpty(providerKey))
            {
                throw new ArgumentException(
                    "ProviderKey value missing. You need to supply a valid provider key so we know where to redirect the user Eg. providerkey=google.");
            }

            var previousRedirectUrl = string.IsNullOrEmpty((string) Session[SessionKeyRedirectToProviderUrl])
                                          ? "N.A."
                                          : (string) Session[SessionKeyRedirectToProviderUrl];
            TraceSource.TraceInformation("Previous Redirect Url: " + previousRedirectUrl);

            #region Deserialize Tokens, etc.

            // Retrieve any (previously) serialized access token stuff. (eg. public/private keys and state).
            // TODO: Check if this is an access token or an auth token thingy-thing.
            TraceSource.TraceVerbose("Retrieving (local serializaed) AccessToken, State and RedirectToUrl.");
            var state = Session[SessionKeyState] as string;
            var redirectToUrl = Session[SessionKeyRedirectToUrl] as Uri;

            #endregion

            // Lets now start to setup the view model.
            var model = new AuthenticateCallbackData();

            #region Retrieve the User Information

            try
            {
                // Which provider did we just authenticate with?
                var provider = GetAuthenticationProvider(providerKey);

                // Where do we return to, after we've authenticated?
                var callbackUri = GenerateCallbackUri(provider.Name);

                var queryString = new NameValueCollection();
                foreach (var key in Request.Query.Keys)
                {
                    queryString.Add(key, Request.Query[key]);
                }

                // Grab the user information.
                model.AuthenticatedClient = provider.AuthenticateClient(queryString, state, callbackUri);
            }
            catch (Exception exception)
            {
                TraceSource.TraceError(exception.Message);
                model.Exception = exception;
            }

            #endregion

            // Do we have an optional redirect resource? Usually a previous referer?
            if (redirectToUrl != null)
            {
                TraceSource.TraceVerbose("Found redirectToUrl: " + redirectToUrl);
                model.ReturnUrl = redirectToUrl;
            }

            // Finally! We can hand over the logic to the consumer to do whatever they want.
            TraceSource.TraceVerbose("About to execute your custom callback provider logic.");
            return _callbackProvider.Process(this, model);
        }
Example #9
0
 public GoogleLinkedAccount(NancyModule nancyModule, AuthenticateCallbackData model)
 {
     this.model = model;
     this.nancyModule = nancyModule;
 }
 public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
 {
     return nancyModule.View["AuthenticateCallback", model];
 }
        public KeyRockModule(IAuthenticationCallbackProvider callbackProvider)
        {
            Before += context =>
            {
                if (Cache == null)
                {
                    Cache = new SessionCache(context.Request.Session);
                }

                return null;
            };

            _callbackProvider = callbackProvider;
            _authenticationProviderFactory = new AuthenticationProviderFactory();

            Get["/authenticate/keyrock"] = parameters =>
            {
                var providerKey = (string)Request.Query.providerkey;
                if (string.IsNullOrEmpty(providerKey))
                {
                    throw new ArgumentException(
                        "ProviderKey value missing. You need to supply a valid provider key so we know where to redirect the user Eg. providerkey=google.");
                }

                var previousRedirectUrl = string.IsNullOrEmpty((string)Cache[SessionKeyRedirectToProviderUrl])
                                              ? "N.A."
                                              : (string)Cache[SessionKeyRedirectToProviderUrl];

                #region Deserialize Tokens, etc.

                // Retrieve any (previously) serialized access token stuff. (eg. public/private keys and state).
                // TODO: Check if this is an access token or an auth token thingy-thing.
                var state = Cache[SessionKeyState] as string;
                var redirectToUrl = Cache[SessionKeyRedirectToUrl] as string;

                #endregion

                // Lets now start to setup the view model.
                var model = new AuthenticateCallbackData();

                #region Retrieve the User Information

                try
                {
                    // Which provider did we just authenticate with?
                    var provider = _authenticationProviderFactory.AuthenticationProviders["keyrock"];

                    // Where do we return to, after we've authenticated?
                    var callbackUri = GenerateCallbackUri(provider.Name);

                    var queryString = new NameValueCollection();
                    foreach (var key in Request.Query.Keys)
                    {
                        queryString.Add(key, Request.Query[key]);
                    }

                    // Grab the user information.
                    model.AuthenticatedClient = provider.AuthenticateClient(queryString, state, callbackUri);
                }
                catch (Exception exception)
                {
                    model.Exception = exception;
                }

                #endregion

                // Do we have an optional redirect resource? Usually a previous referer?
                if (redirectToUrl != null)
                {
                    model.ReturnUrl = redirectToUrl;
                }

                // Finally! We can hand over the logic to the consumer to do whatever they want.
                return _callbackProvider.Process(this, model);
            };

            Get["/authentication/redirect/keyrock"] = _ =>
            {
                var provider = _authenticationProviderFactory.AuthenticationProviders["keyrock"];

                //// Most providers don't need any pre-setup crap, to redirect to authenticate.
                //// But of course, there's always one - OpenId. We have no idea WHERE we want to
                //// redirect to, so we need to do a particular check here.
                //// Of course, any value here could be used for any other provider. But that would be weird.
                //// TODO: Confirm this is not a security threat / open to abuse in some way.
                //if (identifier != null)
                //{
                //    provider.AuthenticateRedirectionUrl = identifier;
                //}

                //// Where do we return to, after we've authenticated?
                var callbackUri = GenerateCallbackUri("keyrock");

                // Determine where we need to redirect to.
                var redirectToAuthenticateSettings = provider.RedirectToAuthenticate(callbackUri);

                // Remember any important information for after we've come back.
                Cache[SessionKeyState] = redirectToAuthenticateSettings.State;
                Cache[SessionKeyRedirectToUrl] = DetermineReturnUrl();
                Cache[SessionKeyRedirectToProviderUrl] = redirectToAuthenticateSettings.RedirectUri.AbsoluteUri;

                // Now redirect :)
                return Response.AsRedirect(redirectToAuthenticateSettings.RedirectUri.AbsoluteUri);
            };
        }
 public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
 {
     return nancyModule.Negotiate.WithView("AuthenticateCallback").WithModel(model);
 }
Example #13
0
 dynamic IAuthenticationCallbackProvider.Process(NancyModule nancyModule, AuthenticateCallbackData model)
 {
     throw new NotImplementedException();
 }