public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            base.OnAuthenticated(authService, session, tokens, authInfo);
            var appSettings         = authService.TryResolve <IAppSettings>();
            var userAuthRepo        = authService.TryResolve <IAuthRepository>();
            var userAuth            = userAuthRepo.GetUserAuth(session, tokens);
            var dbConnectionFactory = authService.TryResolve <IDbConnectionFactory>();

            foreach (var authTokens in session.ProviderOAuthAccess)
            {
                if (authTokens.Provider.ToLower() == "github")
                {
                    GithubProfileUrl = session.GetProfileUrl();
                }
                if (authTokens.Provider.ToLower() == "twitter")
                {
                    TwitterProfileUrl = session.GetProfileUrl();
                    if (appSettings.GetList("TwitterAdmins").Contains(session.UserName) && !session.HasRole(RoleNames.Admin, userAuthRepo))
                    {
                        userAuthRepo.AssignRoles(userAuth, roles: new[] { RoleNames.Admin });
                    }
                }

                ProfileUrl = GithubProfileUrl ?? TwitterProfileUrl;
                using (var db = dbConnectionFactory.OpenDbConnection())
                {
                    var userAuthInstance = db.Single <CustomUserAuth>(x => x.Id == this.UserAuthId.ToInt());
                    if (userAuthInstance != null)
                    {
                        userAuthInstance.DefaultProfileUrl = this.ProfileUrl;
                        db.Save(userAuthInstance);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public override void OnAuthenticated(IServiceBase authService, IAuthSession session,
                                             IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            base.OnAuthenticated(authService, session, tokens, authInfo);

            this.ProfileUrl64 = session.GetProfileUrl();
        }
Ejemplo n.º 3
0
        public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            base.OnAuthenticated(authService, session, tokens, authInfo);

            var jsv = authService.Request.Dto.Dump();

            "OnAuthenticated(): {0}".Print(jsv);

            this.ProfileUrl64 = session.GetProfileUrl();
        }
Ejemplo n.º 4
0
        public override void OnAuthenticated(IRequest req, IAuthSession session, IServiceBase authService,
                                             IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            var authRepo = HostContext.AppHost.GetAuthRepository(req);

            using (authRepo as IDisposable)
            {
                var userAuth = (AppUser)authRepo.GetUserAuth(session.UserAuthId);
                userAuth.ProfileUrl    = session.GetProfileUrl();
                userAuth.LastLoginIp   = req.UserHostAddress;
                userAuth.LastLoginDate = DateTime.UtcNow;
                authRepo.SaveUserAuth(userAuth);
            }
        }
Ejemplo n.º 5
0
        public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            base.OnAuthenticated(authService, session, tokens, authInfo);
            var appSettings  = authService.TryResolve <IAppSettings>();
            var userAuthRepo = authService.TryResolve <IAuthRepository>();
            var userAuth     = userAuthRepo.GetUserAuth(session, tokens);
            var dbFactory    = authService.TryResolve <IDbConnectionFactory>();
            var userId       = this.UserAuthId.ToInt();

            foreach (var authTokens in session.ProviderOAuthAccess)
            {
                if (authTokens.Provider.ToLower() == "github")
                {
                    if (authInfo != null && authInfo.TryGetValue("avatar_url", out var avatarUrl))
                    {
                        GithubProfileUrl = avatarUrl;
                    }
                }
                if (authTokens.Provider.ToLower() == "twitter")
                {
                    TwitterProfileUrl = session.GetProfileUrl();
                }

                ProfileUrl = GithubProfileUrl ?? TwitterProfileUrl;

                using (var db = dbFactory.OpenDbConnection())
                {
                    var userAuthInstance = db.Single <CustomUserAuth>(x => x.Id == userId);
                    if (userAuthInstance != null)
                    {
                        userAuthInstance.DefaultProfileUrl = this.ProfileUrl;
                        userAuthInstance.IpAddress         = authService.Request.UserHostAddress;

                        db.Update(userAuthInstance);
                    }

                    var userActivity = db.SingleById <UserActivity>(userAuth.Id);
                    if (userActivity == null)
                    {
                        db.Insert(new UserActivity
                        {
                            Id       = userAuth.Id,
                            UserName = session.UserName,
                            Created  = DateTime.UtcNow,
                            Modified = DateTime.UtcNow,
                        });
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public static JsonObject CreateJwtPayload(
            IAuthSession session, string issuer, TimeSpan expireIn, 
            IEnumerable<string> audiences=null,
            IEnumerable<string> roles=null,
            IEnumerable<string> permissions =null)
        {
            var now = DateTime.UtcNow;
            var jwtPayload = new JsonObject
            {
                {"iss", issuer},
                {"sub", session.UserAuthId},
                {"iat", now.ToUnixTime().ToString()},
                {"exp", now.Add(expireIn).ToUnixTime().ToString()},
            };

            jwtPayload.SetAudience(audiences?.ToList());

            if (!string.IsNullOrEmpty(session.Email))
                jwtPayload["email"] = session.Email;
            if (!string.IsNullOrEmpty(session.FirstName))
                jwtPayload["given_name"] = session.FirstName;
            if (!string.IsNullOrEmpty(session.LastName))
                jwtPayload["family_name"] = session.LastName;
            if (!string.IsNullOrEmpty(session.DisplayName))
                jwtPayload["name"] = session.DisplayName;

            if (!string.IsNullOrEmpty(session.UserName))
                jwtPayload["preferred_username"] = session.UserName;
            else if (!string.IsNullOrEmpty(session.UserAuthName) && !session.UserAuthName.Contains("@"))
                jwtPayload["preferred_username"] = session.UserAuthName;

            var profileUrl = session.GetProfileUrl();
            if (profileUrl != null && profileUrl != Svg.GetDataUri(Svg.Icons.DefaultProfile))
                jwtPayload["picture"] = profileUrl;

            var combinedRoles = new List<string>(session.Roles.Safe());
            var combinedPerms = new List<string>(session.Permissions.Safe());

            roles.Each(x => combinedRoles.AddIfNotExists(x));
            permissions.Each(x => combinedPerms.AddIfNotExists(x));

            if (combinedRoles.Count > 0)
                jwtPayload["roles"] = combinedRoles.ToJson();

            if (combinedPerms.Count > 0)
                jwtPayload["perms"] = combinedPerms.ToJson();

            return jwtPayload;
        }
Ejemplo n.º 7
0
    public override async Task OnAuthenticatedAsync(IRequest httpReq, IAuthSession session, IServiceBase authService,
                                                    IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default)
    {
        var authRepo = HostContext.AppHost.GetAuthRepositoryAsync(httpReq);

        using (authRepo as IDisposable)
        {
            var userAuth = (AppUser)await authRepo.GetUserAuthAsync(session.UserAuthId, token);

            userAuth.ProfileUrl    = session.GetProfileUrl();
            userAuth.LastLoginIp   = httpReq.UserHostAddress;
            userAuth.LastLoginDate = DateTime.UtcNow;
            await authRepo.SaveUserAuthAsync(userAuth, token);
        }
    }
Ejemplo n.º 8
0
        public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            base.OnAuthenticated(authService, session, tokens, authInfo);
            var profileUrl = session.GetProfileUrl();

            if (string.IsNullOrWhiteSpace(profileUrl) || profileUrl.EndsWithIgnoreCase("no-profile64.png"))
            {
                var userAuth = authService.TryResolve <IUserAuthRepository>().GetUserAuthByUserName(session.UserName);
                if (userAuth != null)
                {
                    profileUrl = userAuth.Meta?.GetValueOrDefault("picture");
                }
            }
            session.ProfileUrl = string.IsNullOrWhiteSpace(profileUrl) ? "/images/avatar2-bw.png" : profileUrl;
            authService.SaveSession(session);
        }
Ejemplo n.º 9
0
        public static JsonObject CreateJwtPayload(
            IAuthSession session, string issuer, TimeSpan expireIn, 
            string audience=null,
            IEnumerable<string> roles=null,
            IEnumerable<string> permissions =null)
        {
            var now = DateTime.UtcNow;
            var jwtPayload = new JsonObject
            {
                {"iss", issuer},
                {"sub", session.UserAuthId},
                {"iat", now.ToUnixTime().ToString()},
                {"exp", now.Add(expireIn).ToUnixTime().ToString()},
            };

            if (audience != null)
                jwtPayload["aud"] = audience;

            if (!string.IsNullOrEmpty(session.Email))
                jwtPayload["email"] = session.Email;
            if (!string.IsNullOrEmpty(session.FirstName))
                jwtPayload["given_name"] = session.FirstName;
            if (!string.IsNullOrEmpty(session.LastName))
                jwtPayload["family_name"] = session.LastName;
            if (!string.IsNullOrEmpty(session.DisplayName))
                jwtPayload["name"] = session.DisplayName;

            if (!string.IsNullOrEmpty(session.UserName))
                jwtPayload["preferred_username"] = session.UserName;
            else if (!string.IsNullOrEmpty(session.UserAuthName) && !session.UserAuthName.Contains("@"))
                jwtPayload["preferred_username"] = session.UserAuthName;

            var profileUrl = session.GetProfileUrl();
            if (profileUrl != null && profileUrl != AuthMetadataProvider.DefaultNoProfileImgUrl)
                jwtPayload["picture"] = profileUrl;

            var combinedRoles = new List<string>(session.Roles.Safe());
            var combinedPerms = new List<string>(session.Permissions.Safe());

            if (roles != null)
                combinedRoles.AddRange(roles);
            if (permissions != null)
                combinedPerms.AddRange(permissions);

            if (combinedRoles.Count > 0)
                jwtPayload["roles"] = combinedRoles.ToJson();

            if (combinedPerms.Count > 0)
                jwtPayload["perms"] = combinedPerms.ToJson();

            return jwtPayload;
        }
Ejemplo n.º 10
0
        public static JsonObject CreateJwtPayload(
            IAuthSession session, string issuer, TimeSpan expireIn,
            string audience                  = null,
            IEnumerable <string> roles       = null,
            IEnumerable <string> permissions = null)
        {
            var now        = DateTime.UtcNow;
            var jwtPayload = new JsonObject
            {
                { "iss", issuer },
                { "sub", session.UserAuthId },
                { "iat", now.ToUnixTime().ToString() },
                { "exp", now.Add(expireIn).ToUnixTime().ToString() },
            };

            if (audience != null)
            {
                jwtPayload["aud"] = audience;
            }

            if (!string.IsNullOrEmpty(session.Email))
            {
                jwtPayload["email"] = session.Email;
            }
            if (!string.IsNullOrEmpty(session.FirstName))
            {
                jwtPayload["given_name"] = session.FirstName;
            }
            if (!string.IsNullOrEmpty(session.LastName))
            {
                jwtPayload["family_name"] = session.LastName;
            }
            if (!string.IsNullOrEmpty(session.DisplayName))
            {
                jwtPayload["name"] = session.DisplayName;
            }

            if (!string.IsNullOrEmpty(session.UserName))
            {
                jwtPayload["preferred_username"] = session.UserName;
            }
            else if (!string.IsNullOrEmpty(session.UserAuthName) && !session.UserAuthName.Contains("@"))
            {
                jwtPayload["preferred_username"] = session.UserAuthName;
            }

            var profileUrl = session.GetProfileUrl();

            if (profileUrl != null && profileUrl != AuthMetadataProvider.DefaultNoProfileImgUrl)
            {
                jwtPayload["picture"] = profileUrl;
            }

            var combinedRoles = new List <string>(session.Roles.Safe());
            var combinedPerms = new List <string>(session.Permissions.Safe());

            if (roles != null)
            {
                combinedRoles.AddRange(roles);
            }
            if (permissions != null)
            {
                combinedPerms.AddRange(permissions);
            }

            if (combinedRoles.Count > 0)
            {
                jwtPayload["roles"] = combinedRoles.ToJson();
            }

            if (combinedPerms.Count > 0)
            {
                jwtPayload["perms"] = combinedPerms.ToJson();
            }

            return(jwtPayload);
        }
Ejemplo n.º 11
0
        public override Task ProcessRequestAsync(IRequest req, IResponse res, string operationName)
        {
            res.ContentType = MimeTypes.ServerSentEvents;
            res.AddHeader(HttpHeaders.CacheControl, "no-cache");
            res.KeepAlive = true;
            res.Flush();

            var          serverEvents = req.TryResolve <IServerEvents>();
            IAuthSession session      = req.GetSession();
            var          userAuthId   = session != null ? session.UserAuthId : null;
            var          anonUserId   = serverEvents.GetNextSequence("anonUser");
            var          userId       = userAuthId ?? ("-" + anonUserId);
            var          displayName  = session.GetSafeDisplayName()
                                        ?? "user" + anonUserId;

            var feature = HostContext.GetPlugin <ServerEventsFeature>();

            var now            = DateTime.UtcNow;
            var subscriptionId = SessionExtensions.CreateRandomSessionId();
            var subscription   = new EventSubscription(res)
            {
                CreatedAt       = now,
                LastPulseAt     = now,
                Channel         = req.QueryString["channel"] ?? EventSubscription.UnknownChannel,
                SubscriptionId  = subscriptionId,
                UserId          = userId,
                UserName        = session != null ? session.UserName : null,
                DisplayName     = displayName,
                SessionId       = req.GetPermanentSessionId(),
                IsAuthenticated = session != null && session.IsAuthenticated,
                Meta            =
                {
                    { "userId",                           userId                                                                 },
                    { "displayName",                      displayName                                                            },
                    { AuthMetadataProvider.ProfileUrlKey, session.GetProfileUrl() ?? AuthMetadataProvider.DefaultNoProfileImgUrl },
                }
            };

            if (feature.OnCreated != null)
            {
                feature.OnCreated(subscription, req);
            }

            var heartbeatUrl = req.ResolveAbsoluteUrl("~/".CombineWith(feature.HeartbeatPath))
                               .AddQueryParam("id", subscriptionId);
            var unRegisterUrl = req.ResolveAbsoluteUrl("~/".CombineWith(feature.UnRegisterPath))
                                .AddQueryParam("id", subscriptionId);
            var privateArgs = new Dictionary <string, string>(subscription.Meta)
            {
                { "id", subscriptionId },
                { "unRegisterUrl", unRegisterUrl },
                { "heartbeatUrl", heartbeatUrl },
                { "heartbeatIntervalMs", ((long)feature.HeartbeatInterval.TotalMilliseconds).ToString(CultureInfo.InvariantCulture) }
            };

            if (feature.OnConnect != null)
            {
                feature.OnConnect(subscription, privateArgs);
            }

            serverEvents.Register(subscription, privateArgs);

            var tcs = new TaskCompletionSource <bool>();

            subscription.OnDispose = _ =>
            {
                try
                {
                    res.EndHttpHandlerRequest(skipHeaders: true);
                }
                catch { }
                tcs.SetResult(true);
            };

            return(tcs.Task);
        }
Ejemplo n.º 12
0
        public static JsonObject CreateJwtPayload(
            IAuthSession session, string issuer, TimeSpan expireIn,
            IEnumerable <string> audiences   = null,
            IEnumerable <string> roles       = null,
            IEnumerable <string> permissions = null)
        {
            var now        = DateTime.UtcNow;
            var jwtPayload = new JsonObject
            {
                { "iss", issuer },
                { "sub", session.UserAuthId },
                { "iat", now.ToUnixTime().ToString() },
                { "exp", now.Add(expireIn).ToUnixTime().ToString() },
            };

            jwtPayload.SetAudience(audiences?.ToList());

            if (!string.IsNullOrEmpty(session.Email))
            {
                jwtPayload["email"] = session.Email;
            }
            if (!string.IsNullOrEmpty(session.FirstName))
            {
                jwtPayload["given_name"] = session.FirstName;
            }
            if (!string.IsNullOrEmpty(session.LastName))
            {
                jwtPayload["family_name"] = session.LastName;
            }
            if (!string.IsNullOrEmpty(session.DisplayName))
            {
                jwtPayload["name"] = session.DisplayName;
            }

            if (!string.IsNullOrEmpty(session.UserName))
            {
                jwtPayload["preferred_username"] = session.UserName;
            }
            else if (!string.IsNullOrEmpty(session.UserAuthName) && !session.UserAuthName.Contains("@"))
            {
                jwtPayload["preferred_username"] = session.UserAuthName;
            }

            var profileUrl = session.GetProfileUrl();

            if (profileUrl != null && profileUrl != Svg.GetDataUri(Svg.Icons.DefaultProfile))
            {
                if (profileUrl.Length <= MaxProfileUrlSize)
                {
                    jwtPayload["picture"] = profileUrl;
                }
                else
                {
                    LogManager.GetLogger(typeof(JwtAuthProvider)).Warn($"User '{session.UserAuthId}' ProfileUrl exceeds max JWT Cookie size, using default profile");
                    jwtPayload["picture"] = HostContext.GetPlugin <AuthFeature>()?.ProfileImages?.RewriteImageUri(profileUrl);
                }
            }

            var combinedRoles = new List <string>(session.Roles.Safe());
            var combinedPerms = new List <string>(session.Permissions.Safe());

            roles.Each(x => combinedRoles.AddIfNotExists(x));
            permissions.Each(x => combinedPerms.AddIfNotExists(x));

            if (combinedRoles.Count > 0)
            {
                jwtPayload["roles"] = combinedRoles.ToJson();
            }

            if (combinedPerms.Count > 0)
            {
                jwtPayload["perms"] = combinedPerms.ToJson();
            }

            return(jwtPayload);
        }