public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
        {
            Response response = nancyModule.Response.AsRedirect("~/");

            if (nancyModule.IsAuthenticated())
            {
                response = nancyModule.Response.AsRedirect("~/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;
        }
        public NancyModule BuildModule(NancyModule module, NancyContext context)
        {
            context.NegotiationContext = new NegotiationContext
            {
                ModuleName = module.GetModuleName(),
                ModulePath = module.ModulePath,
            };

            module.Context = context;
            module.Response = this.responseFormatterFactory.Create(context);
            module.ViewFactory = this.viewFactory;
            module.ModelBinderLocator = this.modelBinderLocator;
            module.ValidatorLocator = this.validatorLocator;
            context.Items.Add(Conventions.RavenSession, this.ravenSessionProvider.GetSession());

            module.After.AddItemToStartOfPipeline(ctx =>
            {
                var session =
                    ctx.Items[Conventions.RavenSession] as IDocumentSession;

                if (session == null)
                {
                    return;
                }

                session.SaveChanges();
                session.Dispose();
            });
            return module;
        }
        public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
        {
            if (model.AuthenticatedClient == null)
            {
                model.AuthenticatedClient = new AuthenticatedClient("github")
                    {
                        AccessToken = "123",
                        AccessTokenExpiresOn = DateTime.MinValue,
                        UserInformation =
                            new UserInformation()
                                {
                                    Email = "*****@*****.**",
                                    Gender = GenderType.Unknown,
                                    Id = "123",
                                    Locale = "en-GB",
                                    Name = "Jonathan Channon",
                                    Picture =
                                        "https://secure.gravatar.com/avatar/62e4df82d52221751142c68ee5d2ae0b?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png",
                                    UserName = "******"
                                }
                    };
            }

            if (!githubUserRepository.UserRegistered(model.AuthenticatedClient.AccessToken))
            {
                githubUserRepository.AddOAuthToken(model.AuthenticatedClient.AccessToken, model.AuthenticatedClient.UserInformation.Email, model.AuthenticatedClient.UserInformation.UserName);
            }

            var githubUser = model.AuthenticatedClient.UserInformation.UserName;
            return nancyModule.Response.AsRedirect("/repos/#" + githubUser, RedirectResponse.RedirectType.Temporary);


        }
        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));
        }
 private static void CreateNegotiationContext(NancyModule module, NancyContext context)
 {
     context.NegotiationContext = new NegotiationContext
     {
         ModuleName = module.GetModuleName(),
         ModulePath = module.ModulePath,
     };
 }
		private void WireRoutesByVerb(RegistrationContext context, string verb, NancyModule.RouteBuilder nancyRoutes)
		{
			var dispatches = context.RouteTable.GetRoutesForVerb(verb).Select(
				route => new KeyValuePair<Route, Delegate>(route, this.CreateRouteDispatch(context, route))).ToArray();

			WireSyncRoutes(nancyRoutes, dispatches);
			WireAsyncRoutes(nancyRoutes, dispatches);
		}
 private static void CreateNegotiationContext(NancyModule module, NancyContext context)
 {
     // TODO - not sure if this should be here or not, but it'll do for now :)
     context.NegotiationContext = new NegotiationContext
                                      {
                                          ModuleName = module.GetModuleName(),
                                          ModulePath = module.ModulePath,
                                      };
 }
        public dynamic OnRedirectToAuthenticationProviderError(NancyModule nancyModule, string errorMessage)
        {
            var model = new IndexViewModel
            {
                ErrorMessage = errorMessage
            };

            return nancyModule.View["index", model];
        }
        public dynamic OnRedirectToAuthenticationProviderError(NancyModule nancyModule, string errorMessage)
        {
            var model = new IndexViewModel
                        {
                            ErrorMessage = errorMessage
                        };

            return nancyModule.Negotiate.WithView("login").WithModel(model);
        }
Example #11
0
        public static Path GetPath(NancyModule module, dynamic parameters, Raven.Client.IDocumentSession session)
        {
            var pathId = String.Format("{0}/{1}", module.ModulePath, parameters.id.Value as string);

            pathId = pathId.Replace("api/", "");

            var path = session.Load<Path>(pathId);

            return path;
        }
        public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
        {
            AuthenticatedUser user = null;
            unitOfWork.DoInTransaction(() =>
             user = userMapper.MapUser(model.AuthenticatedClient)
            );

            string token = tokeniser.CreateToken(user.UserName, user.Id);

            return new {Token = token};
        }
        public dynamic OnRedirectToAuthenticationProviderError(NancyModule nancyModule, string errorMessage)
        {
            return null;

            //when we redirect
            //we take the key/secret, pass info to google, get a token url
            //then redirect to the login page using that information
            //if that request is bung, we throw the OnRedirectToAuthenticationProviderError
            //with the info
            //once that stuff is working, it should never break
            //unless you change something, or the provider changes something
        }
        /// <summary>
        /// Builds a fully configured <see cref="NancyModule"/> instance, based upon the provided <paramref name="module"/>.
        /// </summary>
        /// <param name="module">The <see cref="NancyModule"/> that shoule be configured.</param>
        /// <param name="context">The current request context.</param>
        /// <returns>A fully configured <see cref="NancyModule"/> instance.</returns>
        public NancyModule BuildModule(NancyModule module, NancyContext context)
        {
            CreateNegotiationContext(module, context);

            module.Context = context;
            module.Response = _responseFormatterFactory.Create(context);
            module.ViewFactory = _viewFactory;
            module.ModelBinderLocator = _modelBinderLocator;
            module.ValidatorLocator = _validatorLocator;

            return module;
        }
 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!!!";
     }
 }
        private static Response HandleFacebookOAuthDialogErrorInternal(NancyModule module, string appId, string redirectUri = null, string scope = null, string state = null, IDictionary<string, object> parameters = null, string queryStringsToDrop = QueryStringsToDrop)
        {
            var request = module.Context.Request;
            if (request.Query.error.HasValue && request.Query.error_description.HasValue)
            {
                dynamic model = new ExpandoObject();
                model.error = request.Query.error.Value;
                model.error_description = request.Query.error_description.Value;
                model.facebook_login_url = module.Context.FacebookLoginUrl(appId, redirectUri, scope, state, parameters, queryStringsToDrop);
                return module.View["FacebookLoginError", model];
            }

            return null;
        }
        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 NancyModule BuildModule(NancyModule module, NancyContext context)
        {
            module.Context = context;
            module.Response = this.responseFormatterFactory.Create(context);
            module.ViewFactory = this.viewFactory;
            module.ModelBinderLocator = this.modelBinderLocator;
            module.ValidatorLocator = this.validatorLocator;

            if (module is RavenModule)
            {
                context.Items.Add("RavenSession", _ravenSessionProvider.GetSession());
            }

            return module;
        }
        /// <summary>
        /// Builds a fully configured <see cref="NancyModule"/> instance, based upon the provided <paramref name="module"/>.
        /// </summary>
        /// <param name="module">The <see cref="NancyModule"/> that shoule be configured.</param>
        /// <param name="context">The current request context.</param>
        /// <returns>A fully configured <see cref="NancyModule"/> instance.</returns>
        public NancyModule BuildModule(NancyModule module, NancyContext context)
        {
            module.Context = context;
            module.Response = this.responseFormatter;
            module.ViewFactory = this.viewFactory;
            module.ModelBinderLocator = this.modelBinderLocator;

            var subscribe = module as ISubscribeModuleEvents;

            if(subscribe != null)
            {
                subscribe.ModuleCreated();
            }

            return module;
        }
        private static Response DropFacebookQueryStringsInternal(NancyModule module, string queryStringsToDrop = QueryStringsToDrop)
        {
            var request = module.Context.Request;
            if (!string.IsNullOrEmpty(request.Headers.Referrer))
            {
                var referralUri = new Uri(request.Headers.Referrer);
                if (referralUri.Host == "apps.facebook.com" || referralUri.Host == "apps.beta.facebook.com")
                {
                    string newUrl;
                    if (FacebookNancyExtensions.DropQueryStrings(request.Headers.Referrer, out newUrl, queryStringsToDrop))
                        return new FacebookAppRedirectResponse(newUrl);
                }
            }

            return null;
        }
		public void RegisterServiceInto(NancyModule module, Type serviceType)
		{
			RegistrationContext context = new RegistrationContext
				{
					Module = module,
					ServiceType = serviceType,
					RouteTable = this.routeTableBuilder.ForService(serviceType).Build()
				};

			this.WireRoutesByVerb(context, "GET", module.Get);
			this.WireRoutesByVerb(context, "PUT", module.Put);
			this.WireRoutesByVerb(context, "POST", module.Post);
			this.WireRoutesByVerb(context, "DELETE", module.Delete);
			this.WireRoutesByVerb(context, "PATCH", module.Patch);
			this.WireRoutesByVerb(context, "OPTIONS", module.Options);
		}
Example #22
0
        public NancyModule BuildModule(NancyModule module, NancyContext context)
        {
            module.Context = context;
            module.Response = this.responseFormatter;
            module.ViewFactory = this.viewFactory;
            module.ModelBinderLocator = this.modelBinderLocator;
            context.Items.Add("RavenStore", _ravenSessionProvider.GetDocumentStore());
            context.Items.Add("RavenSession", _ravenSessionProvider.GetSession());
            module.After.AddItemToStartOfPipeline(ctx =>
            {
                var session =
                    ctx.Items["RavenSession"] as IDocumentSession;
                session.SaveChanges();
                session.Dispose();
            });

            module.After.AddItemToEndOfPipeline(PrepareJsonp);
            return module;
        }
Example #23
0
        public Action<Stream> RenderView(NancyModule module, string viewName, dynamic model)
        {
            if (module == null)
            {
                throw new ArgumentNullException("module", "The value of the module parameter cannot be null.");
            }

            if (viewName == null && model == null)
            {
                throw new ArgumentException("viewName and model parameters cannot both be null.");
            }

            if (model == null && viewName.Length == 0)
            {
                throw new ArgumentException("The viewName parameter cannot be empty when the model parameters is null.");
            }

            var actualViewName =
                viewName ?? GetViewNameFromModel(model);

            return GetRenderedView(actualViewName, model);
        }
Example #24
0
        public static dynamic AddResolution(NancyModule module, dynamic parameters, IDocumentSession session, User user, string comment)
        {
            Path path = GetPath(module, parameters as DynamicDictionary, session);
            if (path == null)
                return null;

            if (path.SubscribedUsers == null)
                path.SubscribedUsers = new List<string>();

            var isSubscribed = path.SubscribedUsers.SingleOrDefault(x => x == user.Id);
            if (isSubscribed == null)
                path.SubscribedUsers.Add(user.Id);

            var goalId = parameters.goalId.Value as string;
            var resolution = parameters.resolution.Value as string;

            var goal = path.Goals.SingleOrDefault(x => x.Id == goalId);

            var enumResolution = Resolution.OnCourse;
            if (resolution == "astray")
                enumResolution = Resolution.Astray;

            var achievement = new Achievement
            {
                Id = Guid.NewGuid().ToString(),
                Comment = comment,
                User = user,
                DateCreated = DateTime.UtcNow,
                Resolution = enumResolution
            };

            path.LastUpdated = DateTime.UtcNow;
            goal.Achievements.Add(achievement);

            //session.Store(goal);
            session.Store(path);

            return new { Achievement = achievement, Goal = goal };
        }
        public NancyModule BuildModule(NancyModule module, NancyContext context)
        {
            module.Context = context;
            module.Response = this.responseFormatterFactory.Create(context);
            module.ViewFactory = this.viewFactory;
            module.ModelBinderLocator = this.modelBinderLocator;
            module.ValidatorLocator = this.validatorLocator;

            if (module is DinnerParty.Modules.PersistModule)
            {
                context.Items.Add("RavenSession", _ravenSessionProvider.GetSession());
                //module.After.AddItemToStartOfPipeline(ctx =>
                //{
                //    var session =
                //        ctx.Items["RavenSession"] as IDocumentSession;
                //    session.SaveChanges();
                //    session.Dispose();
                //});
            }

            return module;
        }
        /// <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 #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ViewRenderer"/> class.
 /// </summary>
 /// <param name="module">The <see cref="NancyModule"/> instance that is rendering the view.</param>
 public ViewRenderer(NancyModule module)
 {
     this.module = module;
 }
Example #28
0
 public static IInvoiceAutoNumberGenerator InvoiceAutoNumberGenerator(this Nancy.NancyModule mod)
 {
     return(ObjectFactory.GetInstance <IInvoiceAutoNumberGenerator>());
 }
 public SampleJsonProcessor(NancyModule module, IWebhookSettings settings)
 {
     _module = module;
     this.HardcodedSecretToken = settings.SecretToken;
 }
 public dynamic OnRedirectToAuthenticationProviderError(NancyModule nancyModule, string errorMessage)
 {
     throw new NotImplementedException();
 }
Example #31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RouteBuilder"/> class.
 /// </summary>
 /// <param name="method">The HTTP request method that the route should be available for.</param>
 /// <param name="module"></param>
 public RouteCollecter(string method, NancyModule module)
 {
     this.method = method;
     this.module = module;
 }
Example #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ViewRenderer"/> class.
 /// </summary>
 /// <param name="module">The <see cref="NancyModule"/> instance that is rendering the view.</param>
 public ViewRenderer(NancyModule module)
 {
     this.module = module;
 }
Example #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RouteBuilder"/> class.
 /// </summary>
 /// <param name="method">The HTTP request method that the route should be available for.</param>
 /// <param name="parentModule">The <see cref="NancyModule"/> that the route is being configured for.</param>
 public RouteBuilder(string method, NancyModule parentModule)
 {
     this.method = method;
     this.parentModule = parentModule;
 }
Example #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RouteBuilder"/> class.
 /// </summary>
 /// <param name="method">The HTTP request method that the route should be available for.</param>
 /// <param name="parentModule">The <see cref="INancyModule"/> that the route is being configured for.</param>
 public RouteBuilder(string method, NancyModule parentModule)
 {
     this.method       = method;
     this.parentModule = parentModule;
 }