public static void AddAuthToken(this IAuthSession session, IAuthTokens tokens) { if (session.ProviderOAuthAccess == null) session.ProviderOAuthAccess = new List<IAuthTokens>(); session.ProviderOAuthAccess.Add(tokens); }
public IUserAuth GetUserAuth(IAuthSession authSession, IAuthTokens tokens) { if (!string.IsNullOrEmpty(authSession.UserAuthId)) { var userAuth = GetUserAuth(authSession.UserAuthId); if (userAuth != null) return userAuth; } if (!string.IsNullOrEmpty(authSession.UserAuthName)) { var userAuth = GetUserAuthByUserName(authSession.UserAuthName); if (userAuth != null) return userAuth; } if (tokens == null || string.IsNullOrEmpty(tokens.Provider) || string.IsNullOrEmpty(tokens.UserId)) return null; var oAuthProvider = Session.QueryOver<UserAuthDetails>() .Where(x => x.Provider == tokens.Provider) .And(x => x.UserId == tokens.UserId) .SingleOrDefault(); if (oAuthProvider != null) { return Session.QueryOver<UserAuthPersistenceDto>() .Where(x => x.Id == oAuthProvider.UserAuthId) .SingleOrDefault(); } return null; }
protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo) { if (authInfo.ContainsKey("user_id")) tokens.UserId = authInfo.GetValueOrDefault("user_id"); if (authInfo.ContainsKey("screen_name")) tokens.UserName = authInfo.GetValueOrDefault("screen_name"); try { if (tokens.UserId != null) { var json = AuthHttpGateway.DownloadTwitterUserInfo(tokens.UserId); var objs = JsonObject.ParseArray(json); if (objs.Count > 0) { var obj = objs[0]; tokens.DisplayName = obj.Get("name"); } } LoadUserOAuthProvider(userSession, tokens); } catch (Exception ex) { Log.Error("Could not retrieve twitter user info for '{0}'".Fmt(userSession.TwitterUserId), ex); } }
public IUserAuth GetUserAuth(IAuthSession authSession, IAuthTokens tokens) { if (!string.IsNullOrEmpty(authSession.UserAuthId)) { var userAuth = GetUserAuth(authSession.UserAuthId); if (userAuth != null) return userAuth; } if (!string.IsNullOrEmpty(authSession.UserAuthName)) { var userAuth = GetUserAuthByUserName(authSession.UserAuthName); if (userAuth != null) return userAuth; } if (tokens == null || string.IsNullOrEmpty(tokens.Provider) || string.IsNullOrEmpty(tokens.UserId)) return null; var nhSession = GetCurrentSessionFn(sessionFactory); var oAuthProvider = nhSession.QueryOver<UserAuthDetailsNHibernate>() .Where(x => x.Provider == tokens.Provider) .And(x => x.UserId == tokens.UserId) .SingleOrDefault(); if (oAuthProvider != null) { return nhSession.QueryOver<UserAuthNHibernate>() .Where(x => x.Id == oAuthProvider.UserAuthId) .SingleOrDefault(); } return null; }
public void LoadUserAuth(IAuthSession session, IAuthTokens tokens) { session.ThrowIfNull("session"); var userAuth = GetUserAuth(session, tokens); LoadUserAuth(session, (UserAuth)userAuth); }
public virtual void AddProfileUrl(IAuthTokens tokens, Dictionary<string, string> authInfo) { if (tokens == null || authInfo == null) return; var items = tokens.Items ?? (tokens.Items = new Dictionary<string, string>()); if (items.ContainsKey(ProfileUrlKey)) return; try { //Provide Fallback to retrieve avatar urls in-case built-in access fails if (tokens.Provider == FacebookAuthProvider.Name) { items[ProfileUrlKey] = GetRedirectUrlIfAny( $"http://avatars.io/facebook/{tokens.UserName}?size=medium"); } else if (tokens.Provider == TwitterAuthProvider.Name) { items[ProfileUrlKey] = GetRedirectUrlIfAny( $"http://avatars.io/twitter/{tokens.UserName}?size=medium"); } if (!items.ContainsKey(ProfileUrlKey) && !tokens.Email.IsNullOrEmpty()) items[ProfileUrlKey] = tokens.Email.ToGravatarUrl(size: 64); } catch (Exception ex) { Log.Error("Error AddProfileUrl to: {0}>{1}".Fmt(tokens.Provider, tokens.UserName), ex); } }
/// <summary> /// Saves the Auth Tokens for this request. Called in OnAuthenticated(). /// Overrideable, the default behaviour is to call IUserAuthRepository.CreateOrMergeAuthSession(). /// </summary> protected virtual void SaveUserAuth(IServiceBase authService, IAuthSession session, IAuthRepository authRepo, IAuthTokens tokens) { if (authRepo == null) return; if (tokens != null) { 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); } } authRepo.SaveUserAuth(session); var httpRes = authService.Request.Response as IHttpResponse; if (httpRes != null) { httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId); } OnSaveUserAuth(authService, session); }
public IUserAuth GetUserAuth(IAuthSession authSession, IAuthTokens tokens) { //if (!authSession.UserAuthId.IsNullOrEmpty()) //{ // var userAuth = GetUserAuth(authSession.UserAuthId); // if (userAuth != null) // { // return userAuth; // } //} if (!authSession.UserAuthName.IsNullOrEmpty()) { var userAuth = GetUserAuthByUserName(authSession.UserAuthName); if (userAuth != null) { return userAuth; } } if (tokens == null || tokens.Provider.IsNullOrEmpty() || tokens.UserId.IsNullOrEmpty()) { return null; } return null; }
/// <summary> /// Método que se ejecuta cuando se ha autenticado con éxito /// </summary> /// <param name="authService">Servicio que solicita la autenticación</param> /// <param name="session">Información de sesión</param> /// <param name="tokens">Tokets</param> /// <param name="authInfo">Información de autenticación</param> /// <returns></returns> public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo) { session.FirstName = _fullName; authService.SaveSession(session); return null; }
public void LoadUserAuth(IAuthSession session, IAuthTokens tokens) { if (session == null) throw new ArgumentNullException(nameof(session)); var userAuth = GetUserAuth(session, tokens); LoadUserAuth(session, (UserAuth)userAuth); }
/// <summary> /// The on-authenticated event handler. /// </summary> /// <param name="authService">The authentication service.</param> /// <param name="session">The authentication session.</param> /// <param name="tokens">The authentication tokens.</param> /// <param name="authInfo">The authentication information.</param> public override void OnAuthenticated( IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo) { base.OnAuthenticated(authService, session, tokens, authInfo); }
public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null) { if (request != null) { if (!LoginMatchesSession(session, request.UserName)) return false; } return tokens != null && !string.IsNullOrEmpty(tokens.AccessTokenSecret); }
public override void LoadUserOAuthProvider(IAuthSession authSession, IAuthTokens tokens) { var userSession = authSession as AuthUserSession; if (userSession == null) return; userSession.TwitterUserId = tokens.UserId ?? userSession.TwitterUserId; userSession.TwitterScreenName = tokens.UserName ?? userSession.TwitterScreenName; userSession.DisplayName = tokens.DisplayName ?? userSession.DisplayName; }
public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null) { if (request != null) { if (!LoginMatchesSession(session, request.UserName)) { return false; } } return !session.UserAuthName.IsNullOrEmpty(); }
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 == 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 using (var db = authService.TryResolve<IDbConnectionFactory>().Open()) db.Save(user); }
public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null) { if (request != null) { //if (!LoginMatchesSession(session, request.UserName)) //{ // return false; //} throw new NotImplementedException(); } return session != null && session.IsAuthenticated && !session.UserAuthName.IsNullOrEmpty(); }
public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo) { //Fill IAuthSession with data you want to retrieve in the app eg: session.FirstName = "some_firstname_from_db"; //... //Call base method to Save Session and fire Auth/Session callbacks: return base.OnAuthenticated(authService, session, tokens, authInfo); //Alternatively avoid built-in behavior and explicitly save session with //authService.SaveSession(session, SessionExpiry); //return null; }
public override ServiceStack.Web.IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo) { //Fill IAuthSession with data you want to retrieve in the app eg: session.FirstName = "FirstName"; session.LastName = "LastName"; session.DisplayName = "Display Name"; session.Email = "*****@*****.**"; session.IsAuthenticated = true; session.UserName = "******"; session.UserAuthId = "001"; //... //Important: You need to save the session! authService.SaveSession(session, SessionExpiry); return default(ServiceStack.Web.IHttpResult); }
protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo) { if (authInfo.ContainsKey("user_id")) tokens.UserId = authInfo.GetValueOrDefault("user_id"); if (authInfo.ContainsKey("screen_name")) tokens.UserName = authInfo.GetValueOrDefault("screen_name"); try { if (tokens.UserId != null) { var oauthToken = new OAuthAccessToken { OAuthProvider = this, AccessToken = tokens.AccessToken, AccessTokenSecret = tokens.AccessTokenSecret, }; var json = AuthHttpGateway.DownloadTwitterUserInfo(oauthToken, tokens.UserId); var objs = JsonObject.ParseArray(json); if (objs.Count > 0) { var obj = objs[0]; tokens.DisplayName = obj.Get("name"); string profileUrl; if (obj.TryGetValue("profile_image_url", out profileUrl)) tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl; if (SaveExtendedUserInfo) { obj.Each(x => authInfo[x.Key] = x.Value); } } } } catch (Exception ex) { Log.Error($"Could not retrieve twitter user info for '{userSession.TwitterUserId}'", ex); } LoadUserOAuthProvider(userSession, tokens); }
protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, System.Collections.Generic.Dictionary<string, string> authInfo) { 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"); LoadUserOAuthProvider(userSession, tokens); } catch (Exception ex) { Log.Error("Could not retrieve facebook user info for '{0}'".Fmt(tokens.DisplayName), ex); } }
public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo) { var userSession = session as AuthUserSession; if (userSession != null) { LoadUserAuthInfo(userSession, tokens, authInfo); } var authRepo = authService.TryResolve<IAuthRepository>(); if (authRepo != null) { if (tokens != null) { authInfo.ForEach((x, y) => tokens.Items[x] = y); session.UserAuthId = authRepo.CreateOrMergeAuthSession(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 failed = ValidateAccount(authService, authRepo, session, tokens); if (failed != null) return failed; } try { session.OnAuthenticated(authService, session, tokens, authInfo); } finally { authService.SaveSession(session, SessionExpiry); } return null; }
// 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); }
/// <summary> /// Get a UserAuth by its session. /// </summary> /// <param name="authSession">The auth session.</param> /// <param name="tokens">The tokens.</param> /// <returns>The <see cref="IUserAuth"/>.</returns> public IUserAuth GetUserAuth(IAuthSession authSession, IAuthTokens tokens) { // Try and get by its authentication id if (!string.IsNullOrEmpty(authSession.UserAuthId)) { var userAuth = this.GetUserAuth(authSession.UserAuthId); if (userAuth != null) { return userAuth; } } // Try and get by its user auth name if (!string.IsNullOrEmpty(authSession.UserAuthName)) { var userAuth = this.GetUserAuthByUserName(authSession.UserAuthName); if (userAuth != null) { return userAuth; } } // Check for null OAuth session tokens if (tokens == null || string.IsNullOrEmpty(tokens.Provider) || string.IsNullOrEmpty(tokens.UserId)) { return null; } // Try and get from the OAuth table var oauthProvider = this.GetUserAuthDetailsByProvider(tokens.UserId, tokens.Provider); return oauthProvider != null ? this.GetUserAuth(oauthProvider.UserAuthId) : null; }
protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, System.Collections.Generic.Dictionary<string, string> authInfo) { 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"); if (SaveExtendedUserInfo) { obj.Each(x => authInfo[x.Key] = x.Value); } json = AuthHttpGateway.DownloadFacebookUserInfo(tokens.AccessTokenSecret, "picture"); obj = JsonObject.Parse(json); var picture = obj.Object("picture"); var data = picture != null ? picture.Object("data") : null; if (data != null) { string profileUrl; if (data.TryGetValue("url", out profileUrl)) tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl; } } catch (Exception ex) { Log.Error("Could not retrieve facebook user info for '{0}'".Fmt(tokens.DisplayName), ex); } LoadUserOAuthProvider(userSession, tokens); }
protected virtual bool IsAccountLocked(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens=null) { if (userAuth == null) return false; return userAuth.LockedDate != null; }
public async Task <IUserAuthDetails> CreateOrMergeAuthSessionAsync(IAuthSession authSession, IAuthTokens tokens, CancellationToken token = default) { var userAuth = await GetUserAuthAsync(authSession, tokens, token) ?? typeof(TUserAuth).CreateInstance <TUserAuth>(); using var session = documentStore.OpenAsyncSession(); var authDetails = await session .Query <UserAuth_By_UserAuthDetails.Result, UserAuth_By_UserAuthDetails>() .Customize(x => x.WaitForNonStaleResults()) .Where(q => q.Provider == tokens.Provider && q.UserId == tokens.UserId) .OfType <TUserAuthDetails>() .FirstOrDefaultAsync(token).ConfigAwait(); if (authDetails == null) { authDetails = typeof(TUserAuthDetails).CreateInstance <TUserAuthDetails>(); authDetails.Provider = tokens.Provider; authDetails.UserId = tokens.UserId; } authDetails.PopulateMissing(tokens); userAuth.PopulateMissingExtended(authDetails); userAuth.ModifiedDate = DateTime.UtcNow; if (userAuth.CreatedDate == default) { userAuth.CreatedDate = userAuth.ModifiedDate; } await session.StoreAsync(userAuth, token); UpdateIntKey(userAuth); await session.SaveChangesAsync(token); var key = GetKey(userAuth); authDetails.UserAuthId = userAuth.Id; // Partial FK int Id authDetails.RefIdStr = key; // FK if (authDetails.CreatedDate == default) { authDetails.CreatedDate = userAuth.ModifiedDate; } authDetails.ModifiedDate = userAuth.ModifiedDate; await session.StoreAsync(authDetails, token); await session.SaveChangesAsync(token); return(authDetails); }
protected override async Task LoadUserAuthInfoAsync(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default) { try { tokens.UserId = authInfo.Get("id"); tokens.UserName = authInfo.Get("id") ?? authInfo.Get("username"); tokens.DisplayName = authInfo.Get("name"); tokens.FirstName = authInfo.Get("first_name"); tokens.LastName = authInfo.Get("last_name"); tokens.Email = authInfo.Get("email"); if (RetrieveUserPicture) { var json = await AuthHttpGateway.DownloadFacebookUserInfoAsync(tokens.AccessTokenSecret, new[] { "picture" }, token).ConfigAwait(); var obj = JsonObject.Parse(json); var picture = obj.Object("picture"); var data = picture?.Object("data"); if (data != null) { if (data.TryGetValue("url", out var profileUrl)) { tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl.SanitizeOAuthUrl(); if (string.IsNullOrEmpty(userSession.ProfileUrl)) { userSession.ProfileUrl = profileUrl.SanitizeOAuthUrl(); } } } } userSession.UserAuthName = tokens.Email; } catch (Exception ex) { Log.Error($"Could not retrieve facebook user info for '{tokens.DisplayName}'", ex); } LoadUserOAuthProvider(userSession, tokens); }
public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo) { session.FirstName = "Ryan"; return(base.OnAuthenticated(authService, session, tokens, authInfo)); }
public virtual bool IsAccountLocked(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null) { if (AccountLockedValidator != null) { return(AccountLockedValidator(authRepo, userAuth, tokens)); } return(userAuth?.LockedDate != null); }
protected virtual bool EmailAlreadyExists(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null) { if (tokens != null && tokens.Email != null) { var userWithEmail = authRepo.GetUserAuthByUserName(tokens.Email); if (userWithEmail == null) { return(false); } var isAnotherUser = userAuth == null || (userAuth.Id != userWithEmail.Id); return(isAnotherUser); } return(false); }
public override ServiceStack.Web.IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo) { return(base.OnAuthenticated(authService, session, tokens, authInfo)); }
protected virtual void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo) { }
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); LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo); } var hasTokens = tokens != null && authInfo != null; if (hasTokens) { authInfo.ForEach((x, y) => tokens.Items[x] = y); } var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request); using (authRepo as IDisposable) { if (CustomValidationFilter != null) { var ctx = new AuthContext { Request = authService.Request, Service = authService, AuthProvider = this, Session = session, AuthTokens = tokens, AuthInfo = authInfo, AuthRepository = authRepo, }; var response = CustomValidationFilter(ctx); if (response != null) { authService.RemoveSession(); return(response); } } if (authRepo != null) { var failed = ValidateAccount(authService, authRepo, session, tokens); if (failed != null) { authService.RemoveSession(); return(failed); } if (hasTokens) { var authDetails = authRepo.CreateOrMergeAuthSession(session, tokens); session.UserAuthId = authDetails.UserAuthId.ToString(); var firstTimeAuthenticated = authDetails.CreatedDate == authDetails.ModifiedDate; if (firstTimeAuthenticated) { session.OnRegistered(authService.Request, session, authService); AuthEvents.OnRegistered(authService.Request, session, authService); } } authRepo.LoadUserAuth(session, tokens); foreach (var oAuthToken in session.GetAuthTokens()) { var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider); var userAuthProvider = authProvider as OAuthProvider; userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken); } var httpRes = authService.Request.Response as IHttpResponse; if (session.UserAuthId != 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); AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo); } finally { this.SaveSession(authService, session, SessionExpiry); } return(null); }
public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null) { return(session.FromToken && session.IsAuthenticated); }
protected virtual async Task <object> AuthenticateWithAccessTokenAsync(IServiceBase authService, IAuthSession session, IAuthTokens tokens, string accessToken, CancellationToken token = default) { tokens.AccessTokenSecret = accessToken; var json = AuthHttpGateway.DownloadFacebookUserInfo(accessToken, Fields); var authInfo = JsonObject.Parse(json); session.IsAuthenticated = true; return(await OnAuthenticatedAsync(authService, session, tokens, authInfo, token).ConfigAwait()); }
public static bool IsAuthorizedSafe(this IAuthProvider authProvider, IAuthSession session, IAuthTokens tokens) { return(authProvider != null && authProvider.IsAuthorized(session, tokens)); }
protected virtual IHttpResult ValidateAccount(IServiceBase authService, IAuthRepository authRepo, IAuthSession session, IAuthTokens tokens) { var userAuth = authRepo.GetUserAuth(session, tokens); var authFeature = HostContext.GetPlugin <AuthFeature>(); if (authFeature != null && authFeature.ValidateUniqueUserNames && UserNameAlreadyExists(authRepo, userAuth, tokens)) { return(authService.Redirect(FailedRedirectUrlFilter(this, GetReferrerUrl(authService, session).SetParam("f", "UserNameAlreadyExists")))); } if (authFeature != null && authFeature.ValidateUniqueEmails && EmailAlreadyExists(authRepo, userAuth, tokens)) { return(authService.Redirect(FailedRedirectUrlFilter(this, GetReferrerUrl(authService, session).SetParam("f", "EmailAlreadyExists")))); } if (IsAccountLocked(authRepo, userAuth, tokens)) { return(authService.Redirect(FailedRedirectUrlFilter(this, GetReferrerUrl(authService, session).SetParam("f", "AccountLocked")))); } return(null); }
protected virtual bool IsAccountLocked(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null) { return(userAuth?.LockedDate != null); }
public static bool IsAuthorizedSafe(this IAuthProvider authProvider, IAuthSession session, IAuthTokens tokens) { return authProvider != null && authProvider.IsAuthorized(session, tokens); }
/// <summary> /// Saves the Auth Tokens for this request. Called in OnAuthenticated(). /// Overrideable, the default behaviour is to call IUserAuthRepository.CreateOrMergeAuthSession(). /// </summary> protected virtual void SaveUserAuth(IServiceBase authService, IAuthSession session, IAuthRepository authRepo, IAuthTokens tokens) { if (authRepo == null) { return; } if (tokens != null) { session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens).UserAuthId.ToString(); } authRepo.LoadUserAuth(session, tokens); foreach (var oAuthToken in session.GetAuthTokens()) { var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider); var userAuthProvider = authProvider as OAuthProvider; userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken); } authRepo.SaveUserAuth(session); var httpRes = authService.Request.Response as IHttpResponse; httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId); OnSaveUserAuth(authService, session); }
public override void LoadUserOAuthProvider(IAuthSession authSession, IAuthTokens tokens) { var userSession = authSession as AuthUserSession; if (userSession == null) return; userSession.FacebookUserId = tokens.UserId ?? userSession.FacebookUserId; userSession.FacebookUserName = tokens.UserName ?? userSession.FacebookUserName; userSession.DisplayName = tokens.DisplayName ?? userSession.DisplayName; userSession.FirstName = tokens.FirstName ?? userSession.FirstName; userSession.LastName = tokens.LastName ?? userSession.LastName; userSession.PrimaryEmail = tokens.Email ?? userSession.PrimaryEmail ?? userSession.Email; }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo) { var userSession = session as AuthUserSession; if (userSession != null) { LoadUserAuthInfo(userSession, tokens, authInfo); } var authRepo = authService.TryResolve <IAuthRepository>(); if (authRepo != null) { if (tokens != null) { authInfo.ForEach((x, y) => tokens.Items[x] = y); session.UserAuthId = authRepo.CreateOrMergeAuthSession(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); } } } try { session.OnAuthenticated(authService, session, tokens, authInfo); } finally { authService.SaveSession(session, SessionExpiry); } }
public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null) { throw new NotImplementedException(); }
public override async Task <object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default) { IAuthTokens tokens = Init(authService, ref session, request); IRequest httpRequest = authService.Request; string error = httpRequest.QueryString["error"]; bool hasError = !error.IsNullOrEmpty(); if (hasError) { Log.Error($"Odnoklassniki error callback. {httpRequest.QueryString}"); return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", error)))); } string code = httpRequest.QueryString["code"]; bool isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { string preAuthUrl = $"{PreAuthUrl}?client_id={ApplicationId}&redirect_uri={CallbackUrl.UrlEncode()}&response_type=code&layout=m"; await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait(); return(authService.Redirect(PreAuthUrlFilter(this, preAuthUrl))); } try { string payload = $"client_id={ApplicationId}&client_secret={SecretKey}&code={code}&redirect_uri={CallbackUrl.UrlEncode()}&grant_type=authorization_code"; string contents = await AccessTokenUrlFilter(this, AccessTokenUrl).PostToUrlAsync(payload, "*/*", RequestFilter).ConfigAwait(); var authInfo = JsonObject.Parse(contents); //ok.ru does not throw exception, but returns error property in JSON response string accessTokenError = authInfo.Get("error"); if (!accessTokenError.IsNullOrEmpty()) { Log.Error($"Odnoklassniki access_token error callback. {authInfo}"); return(authService.Redirect(session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))); } tokens.AccessTokenSecret = authInfo.Get("access_token"); tokens.UserId = authInfo.Get("user_id"); session.IsAuthenticated = true; return(await OnAuthenticatedAsync(authService, session, tokens, authInfo.ToDictionary(), token).ConfigAwait() ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); } catch (WebException webException) { //just in case it starts throwing exceptions HttpStatusCode statusCode = ((HttpWebResponse)webException.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed")))); } } return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown")))); }
protected virtual object AuthenticateWithAccessToken(IServiceBase authService, IAuthSession session, IAuthTokens tokens, string accessToken) { tokens.AccessTokenSecret = accessToken; var json = AuthHttpGateway.DownloadFacebookUserInfo(accessToken, Fields); var authInfo = JsonObject.Parse(json); session.IsAuthenticated = true; return(OnAuthenticated(authService, session, tokens, authInfo)); }
protected override async Task LoadUserAuthInfoAsync(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default) { try { //sig = md5( request_params_composed_string + md5(access_token + application_secret_key) ) string innerSignature = Encoding.UTF8.GetBytes(tokens.AccessTokenSecret + ConsumerSecret).ToMd5Hash(); string signature = Encoding.UTF8.GetBytes($"application_key={PublicKey}" + innerSignature).ToMd5Hash(); string payload = $"access_token={tokens.AccessTokenSecret}&sig={signature}&application_key={PublicKey}"; string json = await "http://api.odnoklassniki.ru/api/users/getCurrentUser".PostToUrlAsync(payload, "*/*", RequestFilter).ConfigAwait(); JsonObject obj = JsonObject.Parse(json); if (!obj.Get("error").IsNullOrEmpty()) { Log.Error($"Could not retrieve Odnoklassniki user info for '{tokens.DisplayName}', Response:{json}"); return; } //response fields info: http://apiok.ru/wiki/display/api/users.getCurrentUser+ru var location = JsonObject.Parse(obj.GetUnescaped("location")); tokens.UserId = obj.Get("uid"); tokens.DisplayName = obj.Get("name"); tokens.FirstName = obj.Get("first_name"); tokens.LastName = obj.Get("last_name"); tokens.BirthDateRaw = obj.Get("birthday"); tokens.Language = obj.Get("locale"); tokens.Country = location.Get("countryCode"); tokens.City = location.Get("city"); tokens.Gender = obj.Get("gender"); if (SaveExtendedUserInfo) { obj.Each(x => authInfo[x.Key] = x.Value); } } catch (Exception ex) { Log.Error($"Could not retrieve Odnoklassniki user info for '{tokens.DisplayName}'", ex); } LoadUserOAuthProvider(userSession, tokens); }
public static void PopulateMissing(this IUserAuthDetails instance, IAuthTokens tokens, bool overwriteReserved = false) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } if (tokens == null) { throw new ArgumentNullException(nameof(tokens)); } if (!tokens.UserId.IsNullOrEmpty()) { instance.UserId = tokens.UserId; } if (!tokens.RefreshToken.IsNullOrEmpty()) { instance.RefreshToken = tokens.RefreshToken; } if (tokens.RefreshTokenExpiry.HasValue) { instance.RefreshTokenExpiry = tokens.RefreshTokenExpiry; } if (!tokens.RequestToken.IsNullOrEmpty()) { instance.RequestToken = tokens.RequestToken; } if (!tokens.RequestTokenSecret.IsNullOrEmpty()) { instance.RequestTokenSecret = tokens.RequestTokenSecret; } if (!tokens.AccessToken.IsNullOrEmpty()) { instance.AccessToken = tokens.AccessToken; } if (!tokens.AccessTokenSecret.IsNullOrEmpty()) { instance.AccessTokenSecret = tokens.AccessTokenSecret; } if (tokens.Items != null) { if (instance.Items == null) { instance.Items = new Dictionary <string, string>(); } foreach (var entry in tokens.Items) { instance.Items[entry.Key] = entry.Value; } } PopulateMissingExtended(instance, tokens, overwriteReserved); }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, System.Collections.Generic.Dictionary <string, string> authInfo) { "OnAuthenticated()".Print(); }
public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo) { session.AuthProvider = Provider; if (session is AuthUserSession userSession) { LoadUserAuthInfo(userSession, tokens, authInfo); HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo); LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo); } var hasTokens = tokens != null && authInfo != null; if (hasTokens && SaveExtendedUserInfo) { if (tokens.Items == null) { tokens.Items = new Dictionary <string, string>(); } foreach (var entry in authInfo) { if (ExcludeAuthInfoItems.Contains(entry.Key)) { continue; } tokens.Items[entry.Key] = entry.Value; } } if (session is IAuthSessionExtended authSession) { var failed = authSession.Validate(authService, session, tokens, authInfo) ?? AuthEvents.Validate(authService, session, tokens, authInfo); if (failed != null) { authService.RemoveSession(); return(failed); } } var authRepo = GetAuthRepository(authService.Request); using (authRepo as IDisposable) { if (CustomValidationFilter != null) { var ctx = new AuthContext { Request = authService.Request, Service = authService, AuthProviderSync = this, Session = session, AuthTokens = tokens, AuthInfo = authInfo, AuthRepository = authRepo, }; var response = CustomValidationFilter(ctx); if (response != null) { authService.RemoveSession(); return(response); } } if (authRepo != null) { var failed = ValidateAccount(authService, authRepo, session, tokens); if (failed != null) { authService.RemoveSession(); return(failed); } if (hasTokens) { var authDetails = authRepo.CreateOrMergeAuthSession(session, tokens); session.UserAuthId = authDetails.UserAuthId.ToString(); var firstTimeAuthenticated = authDetails.CreatedDate == authDetails.ModifiedDate; if (firstTimeAuthenticated) { session.OnRegistered(authService.Request, session, authService); AuthEvents.OnRegistered(authService.Request, session, authService); } } authRepo.LoadUserAuth(session, tokens); foreach (var oAuthToken in session.GetAuthTokens()) { var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider); var userAuthProvider = authProvider as OAuthProvider; userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken); } var httpRes = authService.Request.Response as IHttpResponse; if (session.UserAuthId != 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); AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo); } finally { #pragma warning disable 618 this.SaveSession(authService, session, SessionExpiry); #pragma warning restore 618 authService.Request.Items[Keywords.DidAuthenticate] = true; } return(null); }
public void LoadUserAuth(IAuthSession session, IAuthTokens tokens) { throw new NotImplementedException(); }
public virtual void LoadUserOAuthProvider(IAuthSession userSession, IAuthTokens tokens) { }
public IUserAuthDetails CreateOrMergeAuthSession(IAuthSession authSession, IAuthTokens tokens) { throw new NotImplementedException(); }
protected virtual bool EmailAlreadyExists(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null) { if (tokens != null && tokens.Email != null) { var userWithEmail = authRepo.GetUserAuthByUserName(tokens.Email); if (userWithEmail == null) return false; var isAnotherUser = userAuth == null || (userAuth.Id != userWithEmail.Id); return isAnotherUser; } return false; }
protected virtual bool UserNameAlreadyExists(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null) { if (tokens?.UserName != null) { var userWithUserName = authRepo.GetUserAuthByUserName(tokens.UserName); if (userWithUserName == null) { return(false); } var isAnotherUser = userAuth == null || (userAuth.Id != userWithUserName.Id); return(isAnotherUser); } return(false); }
protected virtual IHttpResult ValidateAccount(IServiceBase authService, IAuthRepository authRepo, IAuthSession session, IAuthTokens tokens) { var userAuth = authRepo.GetUserAuth(session, tokens); var authFeature = HostContext.GetPlugin<AuthFeature>(); if (authFeature != null && authFeature.ValidateUniqueUserNames && UserNameAlreadyExists(authRepo, userAuth, tokens)) { return authService.Redirect(FailedRedirectUrlFilter(this, GetReferrerUrl(authService, session).SetParam("f", "UserNameAlreadyExists"))); } if (authFeature != null && authFeature.ValidateUniqueEmails && EmailAlreadyExists(authRepo, userAuth, tokens)) { return authService.Redirect(FailedRedirectUrlFilter(this, GetReferrerUrl(authService, session).SetParam("f", "EmailAlreadyExists"))); } if (IsAccountLocked(authRepo, userAuth, tokens)) { return authService.Redirect(FailedRedirectUrlFilter(this, GetReferrerUrl(authService, session).SetParam("f", "AccountLocked"))); } return null; }
/// <summary> /// Override to return User chosen username or Email for this AuthProvider /// </summary> protected virtual string GetUserAuthName(IAuthTokens tokens, Dictionary <string, string> authInfo) => tokens.Email;
public virtual void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo) {}
protected virtual object AuthenticateWithAccessToken(IServiceBase authService, IAuthSession session, IAuthTokens tokens, string accessToken) { tokens.AccessToken = accessToken; var authInfo = this.CreateAuthInfo(accessToken); session.IsAuthenticated = true; return(OnAuthenticated(authService, session, tokens, authInfo)); }
public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null) { return(session != null && session.IsAuthenticated && !session.UserAuthName.IsNullOrEmpty()); }
public abstract bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null);