当前位置: 首页>>代码示例>>C#>>正文


C# IServiceBase.TryResolve方法代码示例

本文整理汇总了C#中IServiceBase.TryResolve方法的典型用法代码示例。如果您正苦于以下问题:C# IServiceBase.TryResolve方法的具体用法?C# IServiceBase.TryResolve怎么用?C# IServiceBase.TryResolve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IServiceBase的用法示例。


在下文中一共展示了IServiceBase.TryResolve方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TryAuthenticate

        public virtual bool TryAuthenticate(IServiceBase authService, string userName, string password)
        {
            var authRepo = authService.TryResolve<IAuthRepository>();
            if (authRepo == null) {
                Log.WarnFormat("Tried to authenticate without a registered IUserAuthRepository");
                return false;
            }

            var session = authService.GetSession();
            var digestInfo = authService.Request.GetDigestAuth();
            IUserAuth userAuth;
            if (authRepo.TryAuthenticate(digestInfo, PrivateKey, NonceTimeOut, session.Sequence, out userAuth)) {

                var holdSessionId = session.Id;
                session.PopulateWith(userAuth); //overwrites session.Id
                session.Id = holdSessionId;
                session.IsAuthenticated = true;
                session.Sequence = digestInfo["nc"];
                session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture);
                session.ProviderOAuthAccess = authRepo.GetUserAuthDetails(session.UserAuthId)
                    .ConvertAll(x => (IAuthTokens) x);

                return true;
            }
            return false;
        }
开发者ID:jin29neci,项目名称:ServiceStack,代码行数:26,代码来源:DigestAuthProvider.cs

示例2: TryAuthenticate

        public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
        {
            var authRepo = authService.TryResolve<IAuthRepository>().AsUserAuthRepository(authService.GetResolver());

            var session = authService.GetSession();
            IUserAuth userAuth;
            if (authRepo.TryAuthenticate(userName, password, out userAuth))
            {
                if (IsAccountLocked(authRepo, userAuth))
                    return false;
                // throw new AuthenticationException("This account has been locked");

                var holdSessionId = session.Id;
                session.PopulateWith(userAuth); //overwrites session.Id
                session.Id = holdSessionId;
                session.IsAuthenticated = true;
                session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture);
                session.ProviderOAuthAccess = authRepo.GetUserAuthDetails(session.UserAuthId)
                    .ConvertAll(x => (IAuthTokens)x);

                return true;
            }

            return false;
        }
开发者ID:aaronzoe,项目名称:Klkl,代码行数:25,代码来源:CustomCredentialsAuthProvider.cs

示例3: OnAuthenticated

        public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            base.OnAuthenticated(authService, session, tokens, authInfo);

            //Populate all matching fields from this session to your own custom User table
            var user = session.ConvertTo<User>();
            user.Id = int.Parse(session.UserAuthId);
            user.GravatarImageUrl64 = !session.Email.IsNullOrEmpty()
                ? CreateGravatarUrl(session.Email, 64)
                : null;

            foreach (var authToken in session.ProviderOAuthAccess)
            {
                if (authToken.Provider == FacebookAuthProvider.Name)
                {
                    user.FacebookName = authToken.DisplayName;
                    user.FacebookFirstName = authToken.FirstName;
                    user.FacebookLastName = authToken.LastName;
                    user.FacebookEmail = authToken.Email;
                }
                else if (authToken.Provider == TwitterAuthProvider.Name)
                {
                    user.TwitterName = user.DisplayName = authToken.UserName;
                }
                else if (authToken.Provider == YahooOpenIdOAuthProvider.Name)
                {
                    user.YahooUserId = authToken.UserId;
                    user.YahooFullName = authToken.FullName;
                    user.YahooEmail = authToken.Email;
                }
            }

            var userAuthRepo = authService.TryResolve<IAuthRepository>();
            if (AppHost.AppConfig.AdminUserNames.Contains(session.UserAuthName)
                && !session.HasRole(RoleNames.Admin, userAuthRepo))
            {
                var userAuth = userAuthRepo.GetUserAuth(session, tokens);
                userAuthRepo.AssignRoles(userAuth, roles: new[] { RoleNames.Admin });
            }

            //Resolve the DbFactory from the IOC and persist the user info
            using (var db = authService.TryResolve<IDbConnectionFactory>().Open())
            {
                db.Save(user);
            }
        }
开发者ID:ServiceStackApps,项目名称:SocialBootstrapApi,代码行数:46,代码来源:CustomUserSession.cs

示例4: OnAuthenticated

        public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            // Note:
            // `session.UserAuthName` is already set to the user's user name.
            // we use `session.UserName` for the user's secret unique id.

            var usersRepo = authService.TryResolve<IUsersRepository>();
            var user = usersRepo.GetOrCreateUser(session.UserAuthName);
            session.UserName = user.UserId;
            authService.SaveSession(session);
        }
开发者ID:eteeselink,项目名称:sioux_tech_radar,代码行数:11,代码来源:SiouxAuthProvider.cs

示例5: OnAuthenticated

        public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            base.OnAuthenticated(authService, session, tokens, authInfo);

            //Populate all matching fields from this session to your own custom User table
            var user = session.TranslateTo<User>();
            user.Id = int.Parse(session.UserAuthId);
            user.GravatarImageUrl64 = !session.Email.IsNullOrEmpty()
                ? CreateGravatarUrl(session.Email, 64)
                : null;

            foreach (var authToken in session.ProviderOAuthAccess)
            {
                if (authToken.Provider == FacebookAuthProvider.Name)
                {
                    user.FacebookName = authToken.DisplayName;
                    user.FacebookFirstName = authToken.FirstName;
                    user.FacebookLastName = authToken.LastName;
                    user.FacebookEmail = authToken.Email;
                }
                else if (authToken.Provider == TwitterAuthProvider.Name)
                {
                    user.TwitterName = authToken.DisplayName;
                }
                else if (authToken.Provider == GoogleOpenIdOAuthProvider.Name)
                {
                    user.GoogleUserId = authToken.UserId;
                    user.GoogleFullName = authToken.FullName;
                    user.GoogleEmail = authToken.Email;
                }
                else if (authToken.Provider == YahooOpenIdOAuthProvider.Name)
                {
                    user.YahooUserId = authToken.UserId;
                    user.YahooFullName = authToken.FullName;
                    user.YahooEmail = authToken.Email;
                }
            }

            if (AppHost.AppConfig.AdminUserNames.Contains(session.UserAuthName)
                && !session.HasRole(RoleNames.Admin))
            {
                using (var assignRoles = authService.ResolveService<AssignRolesService>())
                {
                    assignRoles.Post(new AssignRoles {
                        UserName = session.UserAuthName,
                        Roles = { RoleNames.Admin }
                    });
                }
            }

            //Resolve the DbFactory from the IOC and persist the user info
            authService.TryResolve<IDbConnectionFactory>().Run(db => db.Save(user));
        }
开发者ID:amirk999,项目名称:SocialBootstrapApi,代码行数:53,代码来源:CustomUserSession.cs

示例6: OnAuthenticated

        // public SecureUserService UserService { get; set; }
        // internal List<Message> Messages { get; set; }
        public override void OnAuthenticated(
            IServiceBase authService, 
            IAuthSession session,
            IAuthTokens tokens, 
            Dictionary<string, string> authInfo)
        {
            base.OnAuthenticated(authService, session, tokens, authInfo);
            SteamId = Steam.rgxSteamProfile.Match(session.ProviderOAuthAccess[0].UserId).Groups[1].Value;
            Task<IEnumerable<SteamGame>> ownedAppsTask = Task.Factory.StartNew(() => Steam.GetOwnedApps(SteamId));
            Task<Player> playerTask = Task.Factory.StartNew(() => Steam.GetSteamProfile(SteamId));
            var userService = authService.TryResolve<SecureUserService>();
            CurrentUser = (User)userService.Get(new GetSecureUser(SteamId));
            SteamProfile = playerTask.Result;
            if (CurrentUser == null)
            {
                DateTime steamAge = DateTime.UtcNow.Subtract(new TimeSpan(180, 0, 0, 0));
                if (SteamProfile.TimeCreated > steamAge)
                {
                    // Min account age and game check.
                    // TODO: Redirect to a page explaining they cannot use Play it Forward at this time.
                }

                throw new Exception(
                    "Play it forward is in a closed invite only beta. You do not have access at this time.");

                // Invite only check.
                // TODO: Redirect to a page explaining they cannot use Play it Forward at this time.
            }

            OwnedApps = ownedAppsTask.Result;
            if (SteamProfile == null || OwnedApps == null)
            {
                throw new Exception("Private profile on first login not allowed.");
            }

            CurrentUser.Avatar = SteamProfile.Avatar;
            LastLogin = DateTime.UtcNow;
            authService.SaveSession(session);
            FormsAuthentication.SetAuthCookie(CurrentUser.SteamId.ToString(), true);
        }
开发者ID:robertbaker,项目名称:PlayItForward,代码行数:42,代码来源:SteamUserSession.cs

示例7: OnAuthenticated

        public virtual void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var userSession = session as AuthUserSession;
            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
            }

            var authRepo = authService.TryResolve<IUserAuthRepository>();
            if (authRepo != null)
            {
                if (tokens != null)
                {
                    authInfo.ForEach((x, y) => tokens.Items[x] = y);
                }
                SaveUserAuth(authService, userSession, authRepo, tokens);
            }

            OnSaveUserAuth(authService, session);
            authService.SaveSession(session, SessionExpiry);
            session.OnAuthenticated(authService, session, tokens, authInfo);
        }
开发者ID:MikeWarriner,项目名称:ServiceStack,代码行数:22,代码来源:AuthProvider.cs

示例8: TryAuthenticate

        public virtual bool TryAuthenticate(IServiceBase oAuthService, string userName, string password)
        {
            var authRepo = oAuthService.TryResolve<IUserAuthRepository>();
            if (authRepo == null)
            {
                Log.WarnFormat("Tried to authenticate without a registered IUserAuthRepository");
                return false;
            }

            string useUserName = null;
            if (authRepo.TryAuthenticate(userName, password, out useUserName))
            {
                this.UserName = userName;
                authRepo.LoadUserAuth(this, null);

                OnAuthenticatedCredentials(oAuthService, userName);
                return true;
            }
            return false;
        }
开发者ID:austinvernsonger,项目名称:ServiceStack,代码行数:20,代码来源:AuthUserSession.cs

示例9: OnAuthenticatedCredentials

        public virtual void OnAuthenticatedCredentials(IServiceBase oAuthService, string userName)
        {
            var provider = oAuthService.TryResolve<IUserAuthRepository>();
            if (provider != null)
            {
                provider.SaveUserAuth(this);
            }

            OnSaveUserAuth(oAuthService, this.UserAuthId);
        }
开发者ID:austinvernsonger,项目名称:ServiceStack,代码行数:10,代码来源:AuthUserSession.cs

示例10: OnAuthenticated

        public virtual void OnAuthenticated(IServiceBase oAuthService, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var provider = tokens.Provider;
            var authProvider = oAuthService.TryResolve<IUserAuthRepository>();
            if (authProvider != null)
                authProvider.LoadUserAuth(this, tokens);

            if (provider == TwitterAuthConfig.Name)
            {
                if (authInfo.ContainsKey("user_id"))
                    tokens.UserId = this.TwitterUserId = authInfo.GetValueOrDefault("user_id");

                if (authInfo.ContainsKey("screen_name"))
                    tokens.UserName = this.TwitterScreenName = authInfo.GetValueOrDefault("screen_name");

                try
                {
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(this.TwitterUserId);
                    var obj = JsonObject.Parse(json);
                    tokens.DisplayName = obj.Get("name");
                    this.DisplayName = tokens.DisplayName ?? this.DisplayName;
                }
                catch (Exception ex)
                {
                    Log.Error("Could not retrieve twitter user info for '{0}'".Fmt(TwitterUserId), ex);
                }
            }
            else if (provider == FacebookAuthConfig.Name)
            {
                try
                {
                    var json = AuthHttpGateway.DownloadFacebookUserInfo(tokens.AccessTokenSecret);
                    var obj = JsonObject.Parse(json);
                    tokens.UserId = obj.Get("id");
                    tokens.UserName = obj.Get("username");
                    tokens.DisplayName = obj.Get("name");
                    tokens.FirstName = obj.Get("first_name");
                    tokens.LastName = obj.Get("last_name");
                    tokens.Email = obj.Get("email");

                    this.FacebookUserId = tokens.UserId ?? this.FacebookUserId;
                    this.FacebookUserName = tokens.UserName ?? this.FacebookUserName;
                    this.DisplayName = tokens.DisplayName ?? this.DisplayName;
                    this.FirstName = tokens.FirstName ?? this.FirstName;
                    this.LastName = tokens.LastName ?? this.LastName;
                    this.Email = tokens.Email ?? this.Email;
                }
                catch (Exception ex)
                {
                    Log.Error("Could not retrieve facebook user info for '{0}'".Fmt(tokens.DisplayName), ex);
                }
            }

            authInfo.ForEach((x, y) => tokens.Items[x] = y);

            SaveUserAuth(oAuthService.TryResolve<IUserAuthRepository>(), tokens);
            OnSaveUserAuth(oAuthService, this.UserAuthId);
        }
开发者ID:austinvernsonger,项目名称:ServiceStack,代码行数:58,代码来源:AuthUserSession.cs

示例11: OnAuthenticated

        public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            //Fill the IAuthSession with data which you want to retrieve in the app eg:
            //Resolve the DbFactory from the IOC and persist the user info
            var DbFactory = authService.TryResolve<IDbConnectionFactory>();
            var user = session.TranslateTo<User>();
            TimeSpan sessionExpiry = TimeSpan.FromDays(7 * 2); //2 weeks

            user.UserAuthId = int.Parse(session.UserAuthId);
            if (string.IsNullOrEmpty(user.UserName))
                user.UserName = user.Id.ToString();

            foreach (var authToken in session.ProviderOAuthAccess)
            {
                if (authToken.Provider == FacebookAuthProvider.Name)
                {
                    user.UserName = "fb-" + authToken.UserName.Replace("_", "-");
                    user.DisplayName = authToken.DisplayName;
                    user.FacebookName = authToken.DisplayName;
                    user.FacebookFirstName = authToken.FirstName;
                    user.FacebookLastName = authToken.LastName;
                    user.FacebookEmail = authToken.Email;
                    user.ProfileUrl = "http://www.facebook.com/" + authToken.UserName;
                    user.AvatarUrl = "http://graph.facebook.com/" + authToken.UserName + "/picture";
                }
                else if (authToken.Provider == TwitterAuthProvider.Name)
                {
                    user.UserName = "tw-" + authToken.UserName.Replace("_", "-");
                    user.TwitterName = authToken.DisplayName;
                    user.ProfileUrl = "https://twitter.com/" + authToken.UserName;

                    TwitterHelper twHelper = new TwitterHelper(authToken.AccessToken, authToken.AccessTokenSecret);
                    Twitterizer.TwitterUser twUser = twHelper.GetUser(authToken.UserName);
                    if (twUser != null)
                    {
                        user.AvatarUrl = twUser.ProfileImageLocation;
                        user.DisplayName = twUser.Name;
                    }
                }
            }

            var DbUser = DbFactory.Run(repo => repo.Select<User>(u => u.UserName == user.UserName));
            if (DbUser.Count == 0)
            {
                user.ApiKey = Guid.NewGuid().ToString().Replace("-", "");

                if (string.IsNullOrEmpty(user.UserName))
                    user.UserName = session.UserAuthName;
                if (string.IsNullOrEmpty(user.DisplayName))
                    user.DisplayName = session.DisplayName;
                if (string.IsNullOrEmpty(user.AvatarUrl))
                    user.AvatarUrl = "/Content/Images/avatar.jpg";
                if (string.IsNullOrEmpty(user.ProfileUrl))
                    user.ProfileUrl = "/Users/View/" + user.UserAuthId.ToString();

                DbFactory.Run(repo => repo.Insert<User>(user));
            }
            else
            {
                var u = DbUser[0];
                if (!string.IsNullOrEmpty(user.DisplayName))
                    u.DisplayName = user.DisplayName;
                if (!string.IsNullOrEmpty(user.AvatarUrl))
                    u.AvatarUrl = user.AvatarUrl;
                if (!string.IsNullOrEmpty(user.ProfileUrl))
                    u.ProfileUrl = user.ProfileUrl;

                DbFactory.Run(repo => repo.Update<User>(u));
            }

            var userAuth = DbFactory.Run(repo => repo.Select<UserAuth>(u => u.Id == user.UserAuthId && u.UserName == null));
            if (userAuth.Count > 0)
            {
                // A username is required in the UserAuth table so that a 
                // user can log in using the /auth/credentials endpoint:
                userAuth[0].UserName = user.UserName;
                DbFactory.Run(dbCmd => dbCmd.Save(userAuth[0]));
            }

            //Important: You need to save the session!
            session.UserName = user.UserName;
            authService.SaveSession(session, sessionExpiry);
        }
开发者ID:voxon2,项目名称:Razor.ServiceStack-On-Azure,代码行数:83,代码来源:CustomUserSession.cs

示例12: OnAuthenticated

        public virtual void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var userSession = session as AuthUserSession;
            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
            }

            var authRepo = authService.TryResolve<IUserAuthRepository>();
            if (authRepo != null)
            {
                if (tokens != null)
                {
                    authInfo.ForEach((x, y) => tokens.Items[x] = y);
                    session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens);
                }
                //SaveUserAuth(authService, userSession, authRepo, tokens);

                authRepo.LoadUserAuth(session, tokens);

                foreach (var oAuthToken in session.ProviderOAuthAccess)
                {
                    var authProvider = AuthService.GetAuthProvider(oAuthToken.Provider);
                    if (authProvider == null) continue;
                    var userAuthProvider = authProvider as OAuthProvider;
                    if (userAuthProvider != null)
                    {
                        userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
                    }
                }

                var httpRes = authService.RequestContext.Get<IHttpResponse>();
                if (httpRes != null)
                {
                    httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
                }

            }

            //OnSaveUserAuth(authService, session);
            authService.SaveSession(session, SessionExpiry);
            session.OnAuthenticated(authService, session, tokens, authInfo);
        }
开发者ID:half-evil,项目名称:ServiceStack,代码行数:43,代码来源:AuthProvider.cs

示例13: TryAuthenticate

        /// <summary>
        /// Is user allowed to use service.
        /// </summary>
        /// <param name="authService"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
        {
            GXAmiUser user;
            OrmLiteConnectionFactory f = authService.TryResolve<IDbConnectionFactory>() as OrmLiteConnectionFactory;                                    
            //Connection factory is null when we are configure server at first time.
            if (f == null || f.ConnectionString == null)
            {
                return true;
            }
            try
            {
                using (IDbConnection Db = f.OpenDbConnection())
                {
                    lock (Db)
                    {
                        if (!GuruxAMI.Service.GXManagementService.IsDatabaseCreated(Db))
                        {
#if !SS4
                            string[] items = RestPath.GetPathPartsForMatching(authService.RequestContext.PathInfo);
#else
                        string[] items = RestPath.GetPathPartsForMatching(authService.Request.PathInfo);
#endif
                            string target = items[items.Length - 1];
                            if (string.Compare(target, typeof(GXIsDatabaseCreatedRequest).Name, true) == 0 ||
                                string.Compare(target, typeof(GXCreateTablesRequest).Name, true) == 0 ||
                                string.Compare(target, typeof(GXDropTablesRequest).Name, true) == 0)
                            {
                                user = new GXAmiUser("gurux", "gurux", UserAccessRights.SuperAdmin);
                                user.Id = 1;
                                InitUser(authService, user);
                                return true;
                            }
                            return false;
                        }
                        List<GXAmiUser> users = Db.Select<GXAmiUser>(q => q.Name == userName && q.Password == password);
                        if (users.Count != 1)
                        {
                            //If known DC try to get new tasks, add new task, mark task claimed or add device exception.
                            Guid guid;
#if !SS4
                            string[] items = RestPath.GetPathPartsForMatching(authService.RequestContext.PathInfo);
#else
                        string[] items = RestPath.GetPathPartsForMatching(authService.Request.PathInfo);
#endif
                            string target = items[items.Length - 1];
                            if (items != null && items.Length != 0)
                            {
                                if (string.Compare(target, typeof(GXEventsRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXEventsRegisterRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXEventsUnregisterRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTaskDeleteRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTasksRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTaskUpdateRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTasksClaimRequest).Name, true) == 0 ||                                    
                                    string.Compare(target, typeof(GXTraceLevelRequest).Name, true) == 0)
                                {
                                    //If DC register first time and starts to listen events.
                                    if (IsGuid(userName, out guid))
                                    {
                                        //If known DC wants to listen events.
                                        List<GXAmiDataCollector> list = Db.Select<GXAmiDataCollector>(p => p.Guid == guid);
                                        if (list.Count == 1)
                                        {
                                            IAuthSession s = authService.GetSession(false);
                                            s.Id = userName;
                                            s.UserAuthId = Guid.NewGuid().ToString();
                                            s.UserName = userName;
                                            s.IsAuthenticated = true;
                                            s.Roles = new List<string>();
                                            s.Roles.Add("0");
                                            return true;
                                        }
                                        return false;
                                    }
                                    return false;
                                }
                                else if (string.Compare(target, typeof(GXDataCollectorUpdateRequest).Name, true) == 0 &&
                                    IsGuid(userName, out guid))
                                {
                                    if (guid == Guid.Empty)
                                    {
                                        /* TODO:
                                        IAuthSession s = authService.GetSession(false);
                                        s.Id = userName;
                                        s.UserAuthId = Guid.NewGuid().ToString();
                                        s.UserName = userName;
                                        s.IsAuthenticated = true;
                                        s.Roles = new List<string>();
                                        s.Roles.Add("0");
                                         * */
                                        return true;
                                    }
                                    //If DC updates itself.
//.........这里部分代码省略.........
开发者ID:jomolinare,项目名称:GuruxAMI.Server,代码行数:101,代码来源:GXBasicAuthProvider.cs

示例14: OnAuthenticated

        public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            base.OnAuthenticated(authService, session, tokens, authInfo);
            CustomFoo = "SOMETHING CUSTOM";

            //if (session.Email == null)
            //{
            //    session.Email = session.Email ?? tokens.Email;
            //    session.UserAuthName = session.UserAuthName ?? session.Email;
            //    session.UserName = session.UserName ?? session.Email;

            //    using (var db = authService.TryResolve<IDbConnectionFactory>().Open())
            //    {
            //        int userAuthId = Convert.ToInt32(session.UserAuthId);

            //        var userAuth = db.Select<UserAuth>(ua => ua.Id == userAuthId).FirstOrDefault();
            //        if (userAuth != null && (userAuth.Email == null || userAuth.UserName == null))
            //        {
            //            userAuth.Email = userAuth.Email ?? session.Email;
            //            userAuth.UserName = userAuth.UserName ?? session.Email;
            //            db.Update<UserAuth>(userAuth);
            //        }
            //    }
            //}
            //else if (session.UserAuthName == null)
            //{
            //    session.UserAuthName = session.Email;
            //}

            //session.Email = session.Email ?? tokens.Email;
            //session.UserAuthName = session.UserAuthName ?? session.Email;
            //session.UserName = session.UserName ?? session.Email;

            //Populate all matching fields from this session to your own custom User table
            var user = session.TranslateTo<User>();
            //user.Id = int.Parse(session.UserAuthId);

            foreach (var authToken in session.ProviderOAuthAccess)
            {
                if (authToken.Provider == FacebookAuthProvider.Name)
                {
                    user.FacebookName = authToken.DisplayName;
                    user.FacebookFirstName = authToken.FirstName;
                    user.FacebookLastName = authToken.LastName;
                    user.FacebookEmail = authToken.Email;

                    user.Email = authToken.Email;
                    user.FirstName = authToken.FirstName;
                    user.LastName = authToken.LastName;
                }
                //else if (authToken.Provider == TwitterAuthProvider.Name)
                //{
                //    user.TwitterName = authToken.DisplayName;
                //}
                //else if (authToken.Provider == GoogleOpenIdOAuthProvider.Name)
                //{
                //    user.GoogleUserId = authToken.UserId;
                //    user.GoogleFullName = authToken.FullName;
                //    user.GoogleEmail = authToken.Email;
                //}
                //else if (authToken.Provider == YahooOpenIdOAuthProvider.Name)
                //{
                //    user.YahooUserId = authToken.UserId;
                //    user.YahooFullName = authToken.FullName;
                //    user.YahooEmail = authToken.Email;
                //}
            }

            //if (AppHost.AppConfig.AdminUserNames.Contains(session.Email)
            //    && !session.HasRole(RoleNames.Admin))
            //{
            //    using (var assignRoles = authService.ResolveService<AssignRolesService>())
            //    {
            //        assignRoles.Post(new AssignRoles
            //        {
            //            UserName = session.UserAuthName,
            //            Roles = { RoleNames.Admin }
            //        });
            //    }
            //}

            //Resolve the DbFactory from the IOC and persist the user info
            //authService.TryResolve<IDbConnectionFactory>().Run(db => db.Save(user));
            using (var db = authService.TryResolve<IDbConnectionFactory>().Open())
            {
                //Update (if exists) or insert populated data into 'User'
                var existingUser = db.Select<User>(u => u.Email == user.Email).FirstOrDefault();
                if (existingUser != null)
                {
                    user.Id = existingUser.Id;
                }
                else
                {
                    user.CreatedAt = DateTime.Now;
                }

                db.Save(user);
            }
        }
开发者ID:peter-dangelo,项目名称:ServiceStackMVC,代码行数:99,代码来源:CustomUserSession.cs

示例15: OnAuthenticated

        public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var userSession = session as AuthUserSession;
            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
                HostContext.TryResolve<IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);

                if (LoadUserAuthFilter != null)
                {
                    LoadUserAuthFilter(userSession, tokens, authInfo);
                }
            }

            var hasTokens = tokens != null && authInfo != null;
            if (hasTokens)
            {
                authInfo.ForEach((x, y) => tokens.Items[x] = y);
            }

            var authRepo = authService.TryResolve<IAuthRepository>();
            if (authRepo != null)
            {
                var failed = ValidateAccount(authService, authRepo, session, tokens);
                if (failed != null)
                    return failed;

                if (hasTokens)
                {
                    session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens);
                }

                authRepo.LoadUserAuth(session, tokens);

                foreach (var oAuthToken in session.ProviderOAuthAccess)
                {
                    var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                    if (authProvider == null) continue;
                    var userAuthProvider = authProvider as OAuthProvider;
                    if (userAuthProvider != null)
                    {
                        userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
                    }
                }

                var httpRes = authService.Request.Response as IHttpResponse;
                if (session.UserAuthId != null && httpRes != null)
                {
                    httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
                }
            }
            else
            {
                if (hasTokens)
                {
                    session.UserAuthId = CreateOrMergeAuthSession(session, tokens);
                }
            }

            try
            {
                session.IsAuthenticated = true;
                session.OnAuthenticated(authService, session, tokens, authInfo);
            }
            finally
            {
                authService.SaveSession(session, SessionExpiry);
            }

            return null;
        }
开发者ID:Krave-n,项目名称:ServiceStack,代码行数:71,代码来源:AuthProvider.cs


注:本文中的IServiceBase.TryResolve方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。