public object Post(ThematicAppAddToCommunityRequestTep request)
        {
            IfyWebContext context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            context.Open();
            context.LogInfo(this, string.Format("/community/{{domain}}/apps POST domain='{0}', appurl='{1}'", request.Domain, request.AppUrl));
            if (string.IsNullOrEmpty(request.AppUrl))
            {
                throw new Exception("Invalid Application Url");
            }

            var domain = ThematicCommunity.FromIdentifier(context, request.Domain);

            if (!domain.CanUserManage(context.UserId))
            {
                throw new UnauthorizedAccessException("Action only allowed to manager of the domain");
            }

            var app = domain.GetThematicApplication();
            var res = new RemoteResource(context);

            res.Location = request.AppUrl;
            app.AddResourceItem(res);

            context.Close();
            return(new WebResponseBool(true));
        }
 public override void EndExternalSession(IfyWebContext context, HttpRequest request, HttpResponse response)
 {
     base.EndExternalSession(context, request, response);
     HttpContext.Current.Session["t2apikey"]       = null;
     HttpContext.Current.Session["t2loading"]      = null;
     HttpContext.Current.Session["t2profileError"] = null;
 }
Example #3
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>Returns the existing user with the specified username or creates that user with default account settings.</summary>
        /// <param name="context">The execution environment context.</param>
        /// <param name="username">The username.</param>
        /// <param name="authenticationType">The used authentication type. This parameter can be null. If specified, the username is looked for only among the external usernames of the specified authentication type, otherwise among the web portal's own usernames.</param>
        /// <returns>The User instance. New users are not stored in the database, this must be done by the calling code.</returns>
        public static User GetOrCreate(IfyContext context, string username, AuthenticationType authenticationType)
        {
            User     result   = null;
            Activity activity = null;
            int      userId   = GetUserId(context, username, authenticationType);

            if (userId != 0)
            {
                var oldAccessLevel = context.AccessLevel;
                context.AccessLevel = EntityAccessLevel.Administrator;
                result = FromId(context, userId);
                context.AccessLevel = oldAccessLevel;
                return(result);
            }
            else
            {
                IfyWebContext webContext = context as IfyWebContext;
                result                 = User.GetInstance(context);
                result.Username        = username;
                result.AccountStatus   = (authenticationType == null ? webContext == null ? AccountStatusType.Deactivated : webContext.DefaultAccountStatus : authenticationType.GetDefaultAccountStatus());
                result.Level           = UserLevel.User;
                result.TimeZone        = "UTC";
                result.IsNormalAccount = true;
                AuthenticationType authType;
                authType = IfyWebContext.GetAuthenticationType(typeof(PasswordAuthenticationType));
                result.PasswordAuthenticationAllowed = (authType != null && authType.NormalAccountRule == RuleApplicationType.Always);
                authType = IfyWebContext.GetAuthenticationType(typeof(PasswordAuthenticationType));
                result.SessionlessRequestsAllowed = (authType != null && authType.NormalAccountRule == RuleApplicationType.Always);

                activity = new Activity(context, result, EntityOperationType.Create);
                activity.Store();

                return(result);
            }
        }
Example #4
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>Obtains the user information from the X509 certificate in the current HTTP request.</summary>
        /// <param name="context">The execution environment context.</param>
        /// <param name="request">The current HttpRequest to analyse.</param>
        /// <param name="strict">If set to <c>true</c> the method should never return null but throws always an exception even if the authentication type does not apply.</param>
        /// <returns>An instance of User representing the user profile information or <c>null</c> if no such information is available.</returns>
        public override User GetUserProfile(IfyWebContext context, HttpRequest request, bool strict)
        {
            if (request == null || request.ClientCertificate == null)
            {
                if (strict)
                {
                    throw new ArgumentNullException("request", "Missing client certificate information");
                }
                return(null);
            }

            int userId = context.GetQueryIntegerValue(String.Format("SELECT id FROM usr AS t WHERE t.cert_subject={0};", StringUtils.EscapeSql(request.ClientCertificate.Subject)));

            if (userId == 0)
            {
                /*if (false CreateUserIfDoesNotExistFromSpeficConfiguration) {
                 *  User user = User.GetInstance(context);
                 * } else */if (strict)
                {
                    throw new UnauthorizedAccessException("User not found");
                }
                return(null);
            }
            else
            {
                return(User.ForceFromId(context, userId));
            }
        }
Example #5
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>Does nothing or throws an exception (method is not applicable to this authentication type).</summary>
        /// <returns><c>null</c> if strict is <c>false</c>.</returns>
        /// <param name="context">The execution environment context.</param>
        /// <param name="request">The current HttpRequest to analyse.</param>
        /// <param name="strict">If set to <c>true</c> the method throws an exception since the user identity is not obtained from an HTTP request.</param>
        public override User GetUserProfile(IfyWebContext context, HttpRequest request, bool strict)
        {
            if (strict)
            {
                throw new InvalidOperationException("Token authentication not possible without explicit initiation");
            }
            return(null);
        }
Example #6
0
        //---------------------------------------------------------------------------------------------------------------------

        public static void WriteGenericInformation(IfyWebContext webContext)
        {
            XmlWriter xmlWriter = webContext.StartXmlResponse();

            xmlWriter.WriteStartElement("provider");
            xmlWriter.WriteElementString("caption", "Sign in with an OpenID");
            xmlWriter.WriteElementString("inputCaption", "Full OpenID");
            xmlWriter.WriteEndElement(); // </provider>
        }
Example #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Terradue.Tep.WebServer.WebUserTep"/> class.
        /// </summary>
        /// <param name="entity">Entity.</param>
        public WebUserTep(IfyWebContext context, UserTep entity, bool umsso = false) : base(entity)
        {
            if (umsso)
            {
                AuthenticationType umssoauthType = IfyWebContext.GetAuthenticationType(typeof(UmssoAuthenticationType));
                var umssoUser = umssoauthType.GetUserProfile(context, HttpContext.Current.Request, false);
                if (umssoUser != null)
                {
                    this.UmssoEmail = umssoUser.Email;
                }
            }

            //only current user can know the api key
            if (context.UserId == entity.Id)
            {
                this.ApiKey         = entity.ApiKey;
                this.T2ProfileError = HttpContext.Current.Session["t2profileError"] as string;
                if ((string.IsNullOrEmpty(entity.Affiliation) || string.IsNullOrEmpty(entity.Country) || string.IsNullOrEmpty(entity.FirstName) || string.IsNullOrEmpty(entity.LastName)))
                {
                    this.T2ProfileError += (string.IsNullOrEmpty(this.T2ProfileError) ? "" : "\n") + "Profile not complete";
                }
                this.T2ApiKey = entity.GetSessionApiKey();
            }

            if (context.UserId == entity.Id || context.UserLevel == UserLevel.Administrator)
            {
                this.T2Username = entity.TerradueCloudUsername;
                if (context.GetConfigBooleanValue("accounting-enabled"))
                {
                    this.Balance = entity.GetAccountingBalance();
                }
                this.Roles = GetUserCommunityRoles(context, entity);
                if (context.UserLevel == UserLevel.Administrator)
                {
                    if (entity.RegistrationDate == DateTime.MinValue)
                    {
                        entity.LoadRegistrationInfo();
                    }
                    this.RegistrationDate = entity.RegistrationDate;
                }
            }
            else
            {
                this.Email         = null;
                this.Affiliation   = null;
                this.Level         = 0;
                this.AccountStatus = 0;
                this.DomainId      = null;
            }
        }
Example #8
0
        /// <summary>
        /// This method allows user to request the confirmation email
        /// </summary>
        /// <param name="request">Request.</param>
        public object Post(SendUserEmailConfirmationEmail request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                context.LogInfo(this, string.Format("/user/emailconfirm POST"));
                context.LogError(this, string.Format("Email already confirmed for user {0}", context.Username));
                return(new HttpError(System.Net.HttpStatusCode.BadRequest, new InvalidOperationException("Account does not require email confirmation")));
            } catch (PendingActivationException) {
                context.LogDebug(this, string.Format("Pending activation for user {0}", context.Username));
                AuthenticationType umssoauthType = IfyWebContext.GetAuthenticationType(typeof(UmssoAuthenticationType));
                var umssoUser = umssoauthType.GetUserProfile(context, HttpContext.Current.Request, false);
                if (umssoUser == null)
                {
                    context.LogError(this, string.Format("User not logged in UMSSO"));
                    return(new HttpError(System.Net.HttpStatusCode.BadRequest, new UnauthorizedAccessException("Not logged in UM-SSO")));
                }

                if (Request.Headers["Umsso-Person-Email"] != umssoUser.Email)
                {
                    umssoUser.Email = Request.Headers["Umsso-Person-Email"];
                    umssoUser.Store();
                    context.LogError(this, string.Format("Confirmation email and UM-SSO email do not match"));
                }

                string emailFrom = context.GetConfigValue("MailSenderAddress");
                string subject   = context.GetConfigValue("RegistrationMailSubject");
                subject = subject.Replace("$(SITENAME)", context.GetConfigValue("SiteName"));

                string confirmUrl = context.GetConfigValue("EmailConfirmationUrl").Replace("$(BASEURL)", context.GetConfigValue("BaseUrl")).Replace("$(TOKEN)", umssoUser.ActivationToken);
                string body       = context.GetConfigValue("RegistrationMailBody");
                body = body.Replace("$(USERNAME)", umssoUser.Username);
                body = body.Replace("$(SITENAME)", context.GetConfigValue("SiteName"));
                body = body.Replace("$(ACTIVATIONURL)", confirmUrl);

                context.SendMail(emailFrom, umssoUser.Email, subject, body);

                return(new HttpResult(new EmailConfirmationMessage()
                {
                    Status = "sent", Email = umssoUser.Email
                }));
            }
        }
Example #9
0
        public object Put(UpdateBulkUsersProfileFromRemoteTep request)
        {
            IfyWebContext context = TepWebContext.GetWebContext(PagePrivileges.AdminOnly);

            try {
                context.Open();
                context.LogInfo(this, string.Format("/users/profile PUT Ids='{0}'", string.Join(",", request.Identifiers)));

                foreach (var identifier in request.Identifiers)
                {
                    try
                    {
                        var usr = UserTep.FromIdentifier(context, identifier);
                        usr.LoadProfileFromRemote();
                    }catch (Exception e) {
                        context.LogError(this, e.Message + " - " + e.StackTrace);
                    }
                }

                try{
                    var portalname = string.Format("{0} Portal", context.GetConfigValue("SiteNameShort"));
                    var subject    = context.GetConfigValue("EmailBulkActionSubject");
                    subject = subject.Replace("$(SITENAME)", portalname);
                    var body = context.GetConfigValue("EmailBulkActionBody");
                    body = body.Replace("$(ADMIN)", context.Username);
                    body = body.Replace("$(ACTION)", "User remote profile load");
                    body = body.Replace("$(IDENTIFIERS)", string.Join(",", request.Identifiers));
                    context.SendMail(context.GetConfigValue("SmtpUsername"), context.GetConfigValue("SmtpUsername"), subject, body);
                } catch (Exception e) {
                    context.LogError(this, e.Message + " - " + e.StackTrace);
                }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message + " - " + e.StackTrace);
                context.Close();
                throw e;
            }

            return(true);
        }
Example #10
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>Authenticates the user via the specified username and password.</summary>
        /// <returns>An instance of User representing the authenticated user if the authentication was successful.</returns>
        /// <param name="context">The execution environment context.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// \xrefitem uml "UML" "UML Diagram"
        public User AuthenticateUser(IfyWebContext context, string username, string password)
        {
            if (!IsEnabled)
            {
                throw new InvalidOperationException("Password authentication is not enabled");
            }

            if (username == null || password == null)
            {
                throw new ArgumentNullException("Username and/or password missing", "emptyLogin");
            }

            User user = User.GetInstance(context);

            user.Username = username;
            user.Load();

            if (!user.PasswordAuthenticationAllowed)
            {
                throw new UnauthorizedAccessException("This user account cannot be accessed with a password");
            }

            bool correctPassword = user.CheckPassword(password);

            if (!correctPassword)
            {
                user.FailedLogins++;
                if (MaxFailedLogins != 0 && user.FailedLogins > MaxFailedLogins)
                {
                    user.AccountStatus = AccountStatusType.Deactivated;
                }
                user.Store();
                throw new UnauthorizedAccessException("Wrong username or password");
            }
            user.PasswordExpired = (PasswordExpireTime > 0 && user.LastPasswordChangeTime.AddSeconds(PasswordExpireTime) < context.Now);

            context.StartSession(this, user, false);

            return(user);
        }
Example #11
0
        public object Put(UpdateBulkUsersLevelTep request)
        {
            IfyWebContext context = TepWebContext.GetWebContext(PagePrivileges.AdminOnly);

            try {
                context.Open();
                context.LogInfo(this, string.Format("/users/level PUT Ids='{0}',level='{1}'", string.Join(",", request.Identifiers), request.Level));

                string ids = "";
                foreach (var id in request.Identifiers)
                {
                    ids += string.Format("'{0}',", id);
                }
                ids = ids.TrimEnd(',');
                string sql = string.Format("UPDATE usr SET level='{0}' WHERE username IN ({1});", request.Level, ids);
                context.Execute(sql);

                try{
                    var portalname = string.Format("{0} Portal", context.GetConfigValue("SiteNameShort"));
                    var subject    = context.GetConfigValue("EmailBulkActionSubject");
                    subject = subject.Replace("$(SITENAME)", portalname);
                    var body = context.GetConfigValue("EmailBulkActionBody");
                    body = body.Replace("$(ADMIN)", context.Username);
                    body = body.Replace("$(ACTION)", "User level update");
                    body = body.Replace("$(IDENTIFIERS)", string.Join(",", request.Identifiers));
                    context.SendMail(context.GetConfigValue("SmtpUsername"), context.GetConfigValue("SmtpUsername"), subject, body);
                } catch (Exception e) {
                    context.LogError(this, e.Message + " - " + e.StackTrace);
                }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message + " - " + e.StackTrace);
                context.Close();
                throw e;
            }

            return(true);
        }
Example #12
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>Authenticates the user via the specified username and password.</summary>
        /// <returns>An instance of User representing the authenticated user if the authentication was successful.</returns>
        /// <param name="context">The execution environment context.</param>
        /// <param name="token">The secret token (e.g. a UUID a user received via e-mail).</param>
        /// <summary>
        /// \xrefitem uml "UML" "UML Diagram"
        public User AuthenticateUser(IfyWebContext context, string token)
        {
            User user = User.FromActivationToken(context, token);

            if (user.AccountStatus == AccountStatusType.Enabled)
            {
                throw new InvalidOperationException("Account already enabled");
            }

            if (user.AccountStatus == AccountStatusType.PendingActivation || user.AccountStatus == AccountStatusType.PasswordReset || user.FailedLogins != 0)
            {
                user.AccountStatus          = AccountStatusType.Enabled;
                user.NeedsEmailConfirmation = false;
                user.FailedLogins           = 0;
                user.Store();
                context.SetUserInformation(this, user);
            }

            context.StartSession(this, user, false);

            return(user);
        }
Example #13
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>Obtains the user information from the current HTTP request.</summary>
        /// <param name="context">The execution environment context.</param>
        /// <param name="request">The current HttpRequest to analyse.</param>
        /// <param name="strict">If set to <c>true</c> the method should never return null but throws always an exception even if the authentication type does not apply.</param>
        /// <returns>An instance of User representing the user profile information or <c>null</c> if no such information is available.</returns>
        public override User GetUserProfile(IfyWebContext context, HttpRequest request, bool strict)
        {
            if (!IsEnabled)
            {
                throw new InvalidOperationException("Sessionless requests are not allowed");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request", "Missing request information");
            }

            string username = GetUsername(request);

            if (username == null)
            {
                if (strict)
                {
                    throw new ArgumentNullException("No user account specified");
                }
                return(null);
            }

            string remoteHost = request.ServerVariables["REMOTE_HOST"];

            if (remoteHost != null && Array.IndexOf(context.TrustedHosts, remoteHost) != -1)
            {
                throw new UnauthorizedAccessException(String.Format("You are not connecting from a trusted host ({0})", remoteHost));
            }

            User user = User.FromString(context, username);

            if (!user.SessionlessRequestsAllowed)
            {
                throw new InvalidOperationException("Sessionless requests are not allowed");
            }

            return(user);
        }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Terradue.Tep.WebServer.WebUserTep"/> class.
        /// </summary>
        /// <param name="entity">Entity.</param>
        public WebUserProfileTep(IfyWebContext context, UserTep entity) : base(context, entity)
        {
            try{
                var github = Terradue.Github.GithubProfile.FromId(context, this.Id);
                this.Github   = github.Name;
                this.Gravatar = entity.GetAvatar();
            }catch (Exception) {}
            if (String.IsNullOrEmpty(this.Gravatar))
            {
                this.Gravatar = string.Format("http://www.gravatar.com/avatar/{0}", HashEmailForGravatar(string.IsNullOrEmpty(this.Email) ? "" : this.Email));
            }
            DateTime timef = entity.GetFirstLoginDate();

            this.FirstLoginDate = (timef == DateTime.MinValue ? null : timef.ToString("U"));
            DateTime timel = entity.GetLastLoginDate();

            this.LastLoginDate = (timel == DateTime.MinValue ? null : timel.ToString("U"));

            context.AccessLevel = EntityAccessLevel.Administrator;
            EntityList <WpsJob> jobs = new EntityList <WpsJob>(context);

            jobs.UserId         = this.Id;
            jobs.ItemVisibility = EntityItemVisibility.OwnedOnly;
            jobs.Load();
            CreatedJobs = jobs.Count;

            EntityList <DataPackage> dp = new EntityList <DataPackage>(context);

            dp.UserId         = this.Id;
            dp.ItemVisibility = EntityItemVisibility.OwnedOnly;
            dp.Load();
            CreatedDataPackages = dp.Count;

            var dpdefault = DataPackage.GetTemporaryForUser(context, entity);

            DefaultDataPackageItems = dpdefault.Items.Count;
        }
 public override void EndExternalSession(IfyWebContext context, HttpRequest request, HttpResponse response)
 {
     Client.RevokeSessionCookies();
 }
Example #16
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>Sends a mail to a user.</summary>
        /// \ingroup Authorisation
        public bool SendMail(UserMailType type, bool forAuthenticatedUser)
        {
            IfyWebContext webContext = context as IfyWebContext; // TODO: replace

            string smtpHostname         = context.GetConfigValue("SmtpHostname");
            string smtpUsername         = context.GetConfigValue("SmtpUsername");
            string smtpPassword         = context.GetConfigValue("SmtpPassword");
            int    smtpPort             = context.GetConfigIntegerValue("SmtpPort");
            bool   smtpSsl              = context.GetConfigBooleanValue("SmtpSSL");
            string mailSenderAddress    = context.GetConfigValue("MailSenderAddress");
            string mailSender           = context.GetConfigValue("MailSender");
            string emailConfirmationUrl = context.GetConfigValue("EmailConfirmationUrl");

            if (String.IsNullOrEmpty(emailConfirmationUrl))
            {
                emailConfirmationUrl = String.Format(webContext.AccountRootUrl == null ? "{4}?_request={2}&key={3}" : "{0}{1}/{2}?key={3}",
                                                     webContext.BaseUrl,
                                                     webContext.AccountRootUrl,
                                                     type == UserMailType.Registration ? "activate" : "recover",
                                                     ActivationToken,
                                                     webContext.ScriptUrl
                                                     );
            }

            if (mailSender == null)
            {
                mailSender = mailSenderAddress;
            }

            if (smtpHostname == null || mailSenderAddress == null)
            {
                string errorMessage;
                if (type == UserMailType.Registration && !forAuthenticatedUser)
                {
                    errorMessage = "Your account could not be created due to a server misconfiguration (registration mail cannot be sent)";
                }
                else
                {
                    errorMessage = "Mail cannot be sent, missing values in SMTP account configuration (hostname or sender address)" + (context.UserLevel < UserLevel.Administrator ? ", this is a site administration issue" : String.Empty);
                }
                throw new Exception(errorMessage);
            }

            Load();

            string subject = null, body = null;
            bool   html = false;

            switch (type)
            {
            case UserMailType.Registration:
                subject = context.GetConfigValue("RegistrationMailSubject");
                body    = context.GetConfigValue("RegistrationMailBody");
                html    = context.GetConfigBooleanValue("RegistrationMailHtml");
                if (subject == null)
                {
                    subject = "Accout registration";
                }
                if (body == null)
                {
                    body = String.Format("Dear sir/madam,\n\nThank you for registering on {0}.\n\nYour username is: {1}\n\nBest regards,\nThe team of {0}\n\nP.S. Please do not reply to this mail, it has been generated automatically. If you think you received this mail by mistake, please ignore it.", context.GetConfigValue("SiteName"), Username);
                }
                break;

            case UserMailType.PasswordReset:
                subject = context.GetConfigValue("PasswordResetMailSubject");
                body    = context.GetConfigValue("PasswordResetMailBody");
                html    = context.GetConfigBooleanValue("PasswordResetMailHtml");
                if (subject == null)
                {
                    subject = "Password reset";
                }
                if (body == null)
                {
                    body = String.Format("Dear sir/madam,\n\nYour password for your user account on {0} has been changed.\n\nYour username is: {1}\n\nBest regards,\nThe team of {0}\n\nP.S. Please do not reply to this mail, it has been generated automatically. If you think you received this mail by mistake, please take into account that your password has changed.", context.GetConfigValue("SiteName"), Username);
                }
                break;

            case UserMailType.EmailChanged:
                subject = context.GetConfigValue("EmailChangedMailSubject");
                body    = context.GetConfigValue("EmailChangedMailBody");
                html    = context.GetConfigBooleanValue("EmailChangedMailHtml");
                if (subject == null)
                {
                    subject = "E-mail changed";
                }
                if (body == null)
                {
                    body = String.Format("Dear sir/madam,\n\nYou changed your e-mail address linked to your user account on {0}.\n\nPlease confirm the email by clicking on the following link:\n{1}\n\nBest regards,\nThe team of {0}\n\nP.S. Please do not reply to this mail, it has been generated automatically. If you think you received this mail by mistake, please take into account that your e-mail address has changed.", context.GetConfigValue("SiteName"), ActivationToken);
                }
                break;
            }

            var baseurl = webContext.GetConfigValue("BaseUrl");

            // activationToken also used here to avoid endless nested replacements
            subject = subject.Replace("$(SITENAME)", context.SiteName);
            body    = body.Replace(@"\n", Environment.NewLine);
            body    = body.Replace("$(", "$" + ActivationToken + "(");
            body    = body.Replace("$" + ActivationToken + "(USERCAPTION)", Caption);
            body    = body.Replace("$" + ActivationToken + "(USERNAME)", Username);
            body    = body.Replace("$" + ActivationToken + "(SITENAME)", context.SiteName);
            body    = body.Replace("$" + ActivationToken + "(SITEURL)", baseurl);
            body    = body.Replace("$" + ActivationToken + "(ACTIVATIONURL)", emailConfirmationUrl.Replace("$(BASEURL)", baseurl).Replace("$(TOKEN)", ActivationToken));
            if (body.Contains("$" + ActivationToken + "(SERVICES)"))
            {
                body = body.Replace("$" + ActivationToken + "(SERVICES)", GetUserAccessibleResourcesString(Service.GetInstance(context), html));
            }
            if (body.Contains("$" + ActivationToken + "(SERIES)"))
            {
                body = body.Replace("$" + ActivationToken + "(SERIES)", GetUserAccessibleResourcesString(Series.GetInstance(context), html));
            }

            MailMessage message = new MailMessage();

            message.From = new MailAddress(mailSenderAddress, mailSender);
            message.To.Add(new MailAddress(Email, Email));
            message.Subject = subject;

            if (html)
            {
                AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, new System.Net.Mime.ContentType("text/html"));
                message.AlternateViews.Add(alternate);
            }
            else
            {
                message.Body = body;
            }

            SmtpClient client = new SmtpClient(smtpHostname);

            // Add credentials if the SMTP server requires them.
            if (string.IsNullOrEmpty(smtpUsername))
            {
                smtpUsername                 = null;
                client.Credentials           = null;
                client.UseDefaultCredentials = false;
            }
            else if (smtpUsername != null)
            {
                client.Credentials = new NetworkCredential(smtpUsername, smtpPassword);
            }
            if (smtpPassword == String.Empty)
            {
                smtpPassword = null;
            }

            if (smtpPort > 0)
            {
                client.Port = smtpPort;
            }

            client.EnableSsl      = smtpSsl;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            try {
                client.Send(message);
            } catch (Exception e) {
                if (e.Message.Contains("CDO.Message") || e.Message.Contains("535"))
                {
                    context.AddError("Mail could not be sent, this is a site administration issue (probably caused by an invalid SMTP hostname or wrong SMTP server credentials)");
                }
                else
                {
                    context.AddError("Mail could not be sent, this is a site administration issue: " + e.Message);
                }
                throw;
            }
            return(true);
        }
Example #17
0
        //---------------------------------------------------------------------------------------------------------------------

        public static void WriteGenericSignInForm(IfyWebContext webContext, bool assign)
        {
        }
Example #18
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>Terminates the user's session with the external identity provider.</summary>
        /// <param name="context">The execution environment context.</param>
        /// <param name="request">The current HttpRequest for reference.</param>
        /// <param name="response">The current HttpResponse for reference.</param>
        /// \xrefitem uml "UML" "UML Diagram"
        /// <remarks>This method is called from <see cref="Terradue.Portal.IfyWebContext.EndSession"/> if the authentication type uses external identity providers.</remarks>
        public virtual void EndExternalSession(IfyWebContext context, HttpRequest request, HttpResponse response)
        {
        }
        public override User GetUserProfile(IfyWebContext context, HttpRequest request = null, bool strict = false)
        {
            NewUserCreated = false;

            UserTep            usr      = null;
            AuthenticationType authType = IfyWebContext.GetAuthenticationType(typeof(TepLdapAuthenticationType));

            var tokenrefresh = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-refresh"));
            var tokenaccess  = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-access"));

            context.LogDebug(this, string.Format("GetUserProfile -- tokenrefresh = {0} ; tokenaccess = {1}", tokenrefresh.Value, tokenaccess.Value));

            if (!string.IsNullOrEmpty(tokenrefresh.Value) && DateTime.UtcNow > tokenaccess.Expire)
            {
                // refresh the token
                try {
                    var tokenresponse = client.RefreshToken(tokenrefresh.Value);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-access"), tokenresponse.access_token, tokenaccess.Username, tokenresponse.expires_in);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-refresh"), tokenresponse.refresh_token, tokenrefresh.Username);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-id"), tokenresponse.id_token, tokenrefresh.Username, tokenresponse.expires_in);
                    tokenaccess = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-access"));
                    context.LogDebug(this, string.Format("GetUserProfile - refresh -- tokenrefresh = {0} ; tokenaccess = {1}", tokenrefresh.Value, tokenaccess.Value));
                } catch (Exception) {
                    return(null);
                }
            }

            if (!string.IsNullOrEmpty(tokenaccess.Value))
            {
                OauthUserInfoResponse usrInfo = client.GetUserInfo(tokenaccess.Value);

                context.LogDebug(this, string.Format("GetUserProfile -- usrInfo"));

                if (usrInfo == null)
                {
                    return(null);
                }

                context.LogDebug(this, string.Format("GetUserProfile -- usrInfo = {0}", usrInfo.sub));

                //Check if association auth / username exists
                int  userId = User.GetUserId(context, usrInfo.sub, authType);
                bool userHasAuthAssociated = userId != 0;

                //user has ldap auth associated to his account
                if (userHasAuthAssociated)
                {
                    //User exists, we load it
                    usr = UserTep.FromId(context, userId);
                    //test if TerradueCloudUsername was set
                    if (string.IsNullOrEmpty(usr.TerradueCloudUsername))
                    {
                        usr.LoadCloudUsername();
                        if (string.IsNullOrEmpty(usr.TerradueCloudUsername))
                        {
                            usr.TerradueCloudUsername = usrInfo.sub;
                            usr.StoreCloudUsername();
                        }
                    }

                    //update user infos
                    if (!string.IsNullOrEmpty(usrInfo.given_name))
                    {
                        usr.FirstName = usrInfo.given_name;
                    }
                    if (!string.IsNullOrEmpty(usrInfo.family_name))
                    {
                        usr.LastName = usrInfo.family_name;
                    }
                    if (!string.IsNullOrEmpty(usrInfo.zoneinfo))
                    {
                        usr.TimeZone = usrInfo.zoneinfo;
                    }
                    if (!string.IsNullOrEmpty(usrInfo.locale))
                    {
                        usr.Language = usrInfo.locale;
                    }

                    return(usr);
                }

                if (string.IsNullOrEmpty(usrInfo.email))
                {
                    throw new Exception("Null email returned by the Oauth mechanism, please contact support.");
                }

                //user does not have ldap auth associated to his account
                try {
                    //check if a user with the same email exists
                    usr = UserTep.FromEmail(context, usrInfo.email);

                    //user with the same email exists but not yet associated to ldap auth
                    usr.LinkToAuthenticationProvider(authType, usrInfo.sub);

                    return(usr);
                    //TODO: what about if user Cloud username is different ? force to new one ?
                } catch (Exception e) {
                    context.LogError(this, e.Message);
                }

                //user with this email does not exist, we should create it
                usr       = (UserTep)User.GetOrCreate(context, usrInfo.sub, authType);
                usr.Level = UserCreationDefaultLevel;

                //update user infos
                if (!string.IsNullOrEmpty(usrInfo.given_name))
                {
                    usr.FirstName = usrInfo.given_name;
                }
                if (!string.IsNullOrEmpty(usrInfo.family_name))
                {
                    usr.LastName = usrInfo.family_name;
                }
                if (!string.IsNullOrEmpty(usrInfo.email) && (TrustEmail || usrInfo.email_verifier))
                {
                    usr.Email = usrInfo.email;
                }
                if (!string.IsNullOrEmpty(usrInfo.zoneinfo))
                {
                    usr.TimeZone = usrInfo.zoneinfo;
                }
                if (!string.IsNullOrEmpty(usrInfo.locale))
                {
                    usr.Language = usrInfo.locale;
                }

                if (usr.Id == 0)
                {
                    usr.AccessLevel = EntityAccessLevel.Administrator;
                    NewUserCreated  = true;
                }

                usr.Store();

                usr.LinkToAuthenticationProvider(authType, usrInfo.sub);

                usr.TerradueCloudUsername = usrInfo.sub;
                usr.StoreCloudUsername();

                return(usr);
            }
            else
            {
            }

            context.LogDebug(this, string.Format("GetUserProfile -- return null"));

            return(null);
        }
Example #20
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>In a derived class, obtains the user information from the current HTTP request's URL, headers or content.</summary>
        /// <param name="context">The execution environment context.</param>
        /// <param name="request">The current HttpRequest to analyse.</param>
        /// <param name="strict">If set to <c>true</c> the method should never return null but throws always an exception even if the authentication type does not apply.</param>
        /// <returns>An instance of User representing the user profile information or <c>null</c> if no such information is available.</returns>
        /// <remarks>
        ///     This method works only in an HTTP context, i.e. within a web application. It is called by <see cref="Terradue.Portal.IfyWebContext"/> when the current request is not yet authenticated with this web server, i.e. with the first contact.
        ///     The method returns a <see cref="Terradue.Portal.User"/> instance that is either an existing user (if recognised from the request information) or a new user where all properties are filled with the available information from the request.
        ///     For users that do not yet exist, the method should also specify whether a new user is created automatically and with what status by setting the <see cref="Terradue.Portal.User.AccountStatus"/> property.
        ///     If <c>strict</c> is set to <c>false<c>, the method should return <c>null</c> if the authentication type does not apply. A failed authentication with one authentication type is not a fatal error in this case. The calling method may try several authentication types and normally only one actually recognizes the user.
        ///     If <c>strict</c> is set to <c>true</c>, the method should always throw an exception to inform the calling method about the specific problem.
        ///     The calling IfyWebContext then deals with the further processing of the request, including the user creation or authentication (or rejection of the request).
        /// </remarks>
        /// \xrefitem uml "UML" "UML Diagram"
        public abstract User GetUserProfile(IfyWebContext context, HttpRequest request, bool strict);
Example #21
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>In a derived class, checks whether a session corresponding to the current web server session exists on the external identity provider.</summary>
        /// <remarks>
        ///     This method works only in an HTTP context, i.e. within a web application. It is called by <see cref="Terradue.Portal.IfyWebContext"/> when the current request is authenticated with this web server in order to determine whether this is also the case with the external identity provider.
        ///     The user might have authenticated with the portal, but in the meantime he might have signed from the identity provider.
        ///     If the user has no longer a session with the identity provider, his session with this web server should be closed too. This is taken care of by the calling IfyWebContext.
        ///     For derived classes without external identity provider, this method is not applicable and should always return <c>true</c>.
        /// </remarks>
        /// <param name="context">The execution environment context.</param>
        /// <param name="request">The current HttpRequest to analyse.</param>
        /// <returns><c>true</c> if there is still a session, <c>false</c> otherwise.</returns>
        /// \xrefitem uml "UML" "UML Diagram"
        public abstract bool IsExternalSessionActive(IfyWebContext context, HttpRequest request);
Example #22
0
        public object Get(ThematicAppCurrentUserSearchRequestTep request)
        {
            IfyWebContext context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);

            context.Open();
            context.LogInfo(this, string.Format("/user/current/apps/search GET"));

            IOpenSearchResultCollection result;
            OpenSearchEngine            ose = MasterCatalogue.OpenSearchEngine;
            var  httpRequest  = HttpContext.Current.Request;
            Type responseType = OpenSearchFactory.ResolveTypeFromRequest(httpRequest.QueryString, httpRequest.Headers, ose);
            List <Terradue.OpenSearch.IOpenSearchable> osentities = new List <Terradue.OpenSearch.IOpenSearchable>();
            var settings = MasterCatalogue.OpenSearchFactorySettings;
            OpenSearchableFactorySettings specsettings = (OpenSearchableFactorySettings)settings.Clone();

            UserTep user = null;

            if (context.UserId != 0)
            {
                user = UserTep.FromId(context, context.UserId);
                if (request.cache)
                {
                    var domain = user.GetPrivateDomain();
                    EntityList <ThematicApplicationCached> appsCached = new EntityList <ThematicApplicationCached>(context);
                    appsCached.SetFilter("DomainId", domain.Id);
                    appsCached.AddSort("LastUpdate", SortDirection.Descending);

                    result = ose.Query(appsCached, Request.QueryString, responseType);
                    OpenSearchFactory.ReplaceOpenSearchDescriptionLinks(appsCached, result);
                }
                else
                {
                    //get user private thematic app
                    var apikey   = user.GetSessionApiKey();
                    var t2userid = user.TerradueCloudUsername;
                    if (!string.IsNullOrEmpty(apikey))
                    {
                        specsettings.Credentials = new System.Net.NetworkCredential(t2userid, apikey);
                    }
                    var app = user.GetPrivateThematicApp();
                    if (app != null)
                    {
                        foreach (var item in app.Items)
                        {
                            if (!string.IsNullOrEmpty(item.Location))
                            {
                                try {
                                    var sgOs = OpenSearchFactory.FindOpenSearchable(specsettings, new OpenSearchUrl(item.Location));
                                    osentities.Add(sgOs);
                                    context.LogDebug(this, string.Format("Apps search -- Add '{0}'", item.Location));
                                } catch (Exception e) {
                                    context.LogError(this, e.Message, e);
                                }
                            }
                        }
                    }
                    MultiGenericOpenSearchable multiOSE = new MultiGenericOpenSearchable(osentities, specsettings);
                    result = ose.Query(multiOSE, Request.QueryString, responseType);
                }
            }
            else
            {
                result = ose.Query(new MultiGenericOpenSearchable(osentities, specsettings), Request.QueryString, responseType);
            }

            string sresult = result.SerializeToString();

            //replace usernames in apps
            if (user != null)
            {
                try {
                    sresult = sresult.Replace("${USERNAME}", user.Username);
                    sresult = sresult.Replace("${T2USERNAME}", user.TerradueCloudUsername);
                    sresult = sresult.Replace("${T2APIKEY}", user.GetSessionApiKey());
                } catch (Exception e) {
                    context.LogError(this, e.Message, e);
                }
            }

            context.Close();

            return(new HttpResult(sresult, result.ContentType));
        }
Example #23
0
        /// <summary>
        /// Get the specified request.
        /// </summary>
        /// <param name="request">Request.</param>
        /// /apps/{identifier}/search GET
        public object Get(ThematicAppSearchRequestTep request)
        {
            IfyWebContext context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);

            context.Open();
            context.LogInfo(this, string.Format("/apps/search GET -- cache = {0}", request.cache));

            IOpenSearchResultCollection result;
            OpenSearchEngine            ose = MasterCatalogue.OpenSearchEngine;
            HttpRequest httpRequest         = HttpContext.Current.Request;
            Type        responseType        = OpenSearchFactory.ResolveTypeFromRequest(httpRequest.QueryString, httpRequest.Headers, ose);

            //first we get the communities the user can see
            var communities = new EntityList <ThematicCommunity>(context);

            if (context.UserId == 0)
            {
                communities.SetFilter("Kind", (int)DomainKind.Public + "");
            }
            else
            {
                communities.SetFilter("Kind", (int)DomainKind.Public + "," + (int)DomainKind.Hidden + "," + (int)DomainKind.Private);
                communities.AddSort("Kind", SortDirection.Ascending);
            }
            communities.Load();

            if (request.cache)
            {
                List <int> ids = new List <int>();
                foreach (var c in communities)
                {
                    if (c.IsUserJoined(context.UserId))
                    {
                        ids.Add(c.Id);
                    }
                }

                EntityList <ThematicApplicationCached> appsCached = new EntityList <ThematicApplicationCached>(context);
                var filterValues = new List <object>();
                filterValues.Add(string.Join(",", ids));
                filterValues.Add(SpecialSearchValue.Null);
                appsCached.SetFilter("DomainId", filterValues.ToArray());
                appsCached.SetGroupFilter("UId");
                appsCached.AddSort("LastUpdate", SortDirection.Descending);

                result = ose.Query(appsCached, httpRequest.QueryString, responseType);
                OpenSearchFactory.ReplaceOpenSearchDescriptionLinks(appsCached, result);
            }
            else
            {
                List <Terradue.OpenSearch.IOpenSearchable> osentities = new List <Terradue.OpenSearch.IOpenSearchable>();

                var settings     = MasterCatalogue.OpenSearchFactorySettings;
                var specsettings = (OpenSearchableFactorySettings)settings.Clone();
                if (context.UserId != 0)
                {
                    var user     = UserTep.FromId(context, context.UserId);
                    var apikey   = user.GetSessionApiKey();
                    var t2userid = user.TerradueCloudUsername;
                    if (!string.IsNullOrEmpty(apikey))
                    {
                        specsettings.Credentials = new System.Net.NetworkCredential(t2userid, apikey);
                    }
                }

                //get apps link from the communities the user can see
                foreach (var community in communities.Items)
                {
                    if (community.IsUserJoined(context.UserId))
                    {
                        var app = community.GetThematicApplication();
                        if (app != null)
                        {
                            app.LoadItems();
                            foreach (var item in app.Items)
                            {
                                if (!string.IsNullOrEmpty(item.Location))
                                {
                                    try {
                                        var ios = OpenSearchFactory.FindOpenSearchable(specsettings, new OpenSearchUrl(item.Location));
                                        osentities.Add(ios);
                                        context.LogDebug(this, string.Format("Apps search -- Add '{0}'", item.Location));
                                    } catch (Exception e) {
                                        context.LogError(this, e.Message, e);
                                    }
                                }
                            }
                        }
                    }
                }

                //get thematic apps without any domain
                var apps = new EntityList <ThematicApplication>(context);
                apps.SetFilter("DomainId", SpecialSearchValue.Null);
                apps.SetFilter("Kind", ThematicApplication.KINDRESOURCESETAPPS + "");
                apps.Load();
                foreach (var app in apps)
                {
                    app.LoadItems();
                    foreach (var item in app.Items)
                    {
                        if (!string.IsNullOrEmpty(item.Location))
                        {
                            try {
                                var ios = OpenSearchFactory.FindOpenSearchable(specsettings, new OpenSearchUrl(item.Location));
                                osentities.Add(ios);
                                context.LogDebug(this, string.Format("Apps search -- Add '{0}'", item.Location));
                            } catch (Exception e) {
                                context.LogError(this, e.Message, e);
                            }
                        }
                    }
                }

                MultiGenericOpenSearchable multiOSE = new MultiGenericOpenSearchable(osentities, specsettings);
                result = ose.Query(multiOSE, httpRequest.QueryString, responseType);
            }

            var sresult = result.SerializeToString();

            //replace usernames in apps
            try {
                var user = UserTep.FromId(context, context.UserId);
                sresult = sresult.Replace("${USERNAME}", user.Username);
                sresult = sresult.Replace("${T2USERNAME}", user.TerradueCloudUsername);
                sresult = sresult.Replace("${T2APIKEY}", user.GetSessionApiKey());
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
            }

            if (!string.IsNullOrEmpty(httpRequest.QueryString["uid"]))
            {
                try{
                    var user = UserTep.FromId(context, context.UserId);
                    EventUserLoggerTep eventLogger = new EventUserLoggerTep(context);
                    eventLogger.GetLogEvent(user, "portal_user_access_workspace", "User workspace access").ContinueWith <Event>(
                        usrevent => {
                        if (usrevent != null)
                        {
                            var callId = httpRequest.QueryString["uid"];
                            usrevent.Result.Item.Properties.Add("app_id", callId);
                            EventFactory.Log(context, usrevent.Result);
                        }
                        return(usrevent.Result);
                    }
                        );
                }catch (Exception) {}
            }

            context.Close();
            return(new HttpResult(sresult, result.ContentType));
        }
Example #24
0
        /// <summary>
        /// This method allows user to confirm its email adress with a token key
        /// </summary>
        /// <param name="request">Request.</param>
        public object Get(ConfirmUserEmail request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            // Let's try to open context
            try {
                context.LogInfo(this, string.Format("/user/emailconfirm GET"));
                context.Open();
                context.LogError(this, string.Format("Email already confirmed for user {0}", context.Username));
                context.Close();
                return(new HttpError(System.Net.HttpStatusCode.MethodNotAllowed, new InvalidOperationException("Email already confirmed")));
            } catch (Exception e) {
                AuthenticationType authType      = IfyWebContext.GetAuthenticationType(typeof(TokenAuthenticationType));
                AuthenticationType umssoauthType = IfyWebContext.GetAuthenticationType(typeof(UmssoAuthenticationType));

                var umssoUser = umssoauthType.GetUserProfile(context, HttpContext.Current.Request, false);

                if (umssoUser == null)
                {
                    context.LogError(this, string.Format("User not logged in EOSSO"));
                    throw new ResourceNotFoundException("Not logged in EO-SSO");
                }

                if (e is PendingActivationException)
                {
                    context.LogDebug(this, string.Format("Pending activation for user {0}", context.Username));
                    // User is logged, now we confirm the email with the token
                    context.LogDebug(this, string.Format("User now logged -- Confirm email with token"));
                    User tokenUser = ((TokenAuthenticationType)authType).AuthenticateUser(context, request.Token);

                    // We must check that the logged user if the one that received the email
                    // If not, we rollback to previous status
                    if (tokenUser.Email != Request.Headers["Umsso-Person-Email"])
                    {
                        tokenUser.AccountStatus = AccountStatusType.PendingActivation;
                        tokenUser.Store();
                        context.LogError(this, string.Format("Confirmation email and UM-SSO email do not match"));
                        return(new HttpError(System.Net.HttpStatusCode.BadRequest, new UnauthorizedAccessException("Confirmation email and UM-SSO email do not match")));
                    }

                    context.LogDebug(this, string.Format("User now logged -- Email confirmed"));

                    //send an email to Support to warn them
                    try {
                        string emailFrom = context.GetConfigValue("MailSenderAddress");
                        string subject   = string.Format("[{0}] - Email verification for user {1}", context.GetConfigValue("SiteName"), umssoUser.Username);
                        string body      = context.GetConfigValue("EmailConfirmedNotification");
                        body = body.Replace("$(USERNAME)", umssoUser.Username);
                        body = body.Replace("$(EMAIL)", umssoUser.Email);
                        context.SendMail(emailFrom, emailFrom, subject, body);
                    } catch (Exception e1) {
                        context.LogError(this, e1.Message, e1);
                    }
                }
                else
                {
                    context.LogError(this, e.Message, e);
                    throw e;
                }
            }

            context.Close();
            return(new WebResponseBool(true));
        }
Example #25
0
        public object Get(ThematicAppByCommunitySearchRequestTep request)
        {
            IfyWebContext context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);

            context.Open();
            context.LogInfo(this, string.Format("/community/{{domain}}/apps/search GET domain='{0}'", request.Domain));

            var domain = ThematicCommunity.FromIdentifier(context, request.Domain);
            IOpenSearchResultCollection result;
            OpenSearchEngine            ose = MasterCatalogue.OpenSearchEngine;
            HttpRequest httpRequest         = HttpContext.Current.Request;
            Type        responseType        = OpenSearchFactory.ResolveTypeFromRequest(httpRequest.QueryString, httpRequest.Headers, ose);

            if (request.cache)
            {
                bool isjoined = domain.IsUserJoined(context.UserId);

                EntityList <ThematicApplicationCached> appsCached = new EntityList <ThematicApplicationCached>(context);
                if (isjoined)
                {
                    appsCached.SetFilter("DomainId", domain.Id.ToString());
                }
                else
                {
                    appsCached.SetFilter("DomainId", "-1");//if user is not joined we dont want him to see results
                }
                appsCached.AddSort("LastUpdate", SortDirection.Descending);
                result = ose.Query(appsCached, httpRequest.QueryString, responseType);
                OpenSearchFactory.ReplaceOpenSearchDescriptionLinks(appsCached, result);
            }
            else
            {
                if (MasterCatalogue.SearchCache != null)
                {
                    MasterCatalogue.SearchCache.ClearCache(".*", DateTime.Now);
                }

                var apps = new EntityList <DataPackage>(context);
                apps.SetFilter("Kind", ThematicApplication.KINDRESOURCESETAPPS.ToString());
                apps.SetFilter("DomainId", domain.Id.ToString());
                apps.Load();

                // the opensearch cache system uses the query parameters
                // we add to the parameters the filters added to the load in order to avoir wrong cache
                // we use 't2-' in order to not interfer with possibly used query parameters
                var qs = new NameValueCollection(Request.QueryString);
                foreach (var filter in apps.FilterValues)
                {
                    qs.Add("t2-" + filter.Key.FieldName, filter.Value.ToString());
                }

                apps.OpenSearchEngine = ose;

                List <Terradue.OpenSearch.IOpenSearchable> osentities = new List <Terradue.OpenSearch.IOpenSearchable>();
                foreach (var app in apps.Items)
                {
                    app.OpenSearchEngine = ose;
                    osentities.AddRange(app.GetOpenSearchableArray());
                }

                var settings = MasterCatalogue.OpenSearchFactorySettings;
                MultiGenericOpenSearchable multiOSE = new MultiGenericOpenSearchable(osentities, settings);
                result = ose.Query(multiOSE, httpRequest.QueryString, responseType);
            }

            var sresult = result.SerializeToString();

            //replace usernames in apps
            try {
                var user = UserTep.FromId(context, context.UserId);
                sresult = sresult.Replace("${USERNAME}", user.Username);
                sresult = sresult.Replace("${T2USERNAME}", user.TerradueCloudUsername);
                sresult = sresult.Replace("${T2APIKEY}", user.GetSessionApiKey());
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
            }

            context.Close();
            return(new HttpResult(sresult, result.ContentType));
        }
Example #26
0
 /// <summary>
 /// Ends the external session.
 /// </summary>
 /// <param name="context">Context.</param>
 /// <param name="request">Request.</param>
 /// <param name="response">Response.</param>
 public override void EndExternalSession(IfyWebContext context, HttpRequest request, HttpResponse response)
 {
     response.Redirect(context.HostUrl.Replace("http://", "https://") + "/Shibboleth.sso/Logout");
 }
Example #27
0
        /// <summary>
        /// Gets the user profile.
        /// </summary>
        /// <returns>The user profile.</returns>
        /// <param name="context">Context.</param>
        /// <param name="request">Request.</param>
        public override User GetUserProfile(IfyWebContext context, HttpRequest request, bool strict)
        {
            string      ConfigurationFile = context.SiteConfigFolder + Path.DirectorySeparatorChar + "auth.xml";
            XmlDocument authDoc           = new XmlDocument();

            try {
                authDoc.Load(ConfigurationFile);
                foreach (XmlNode typeNode in authDoc.SelectNodes("/externalAuthentication/method[@active='true']/accountType"))
                {
                    XmlElement methodElem = typeNode.ParentNode as XmlElement;
                    XmlElement typeElem   = typeNode as XmlElement;
                    if (typeElem == null || methodElem == null)
                    {
                        continue;
                    }

                    // The received "Host" header must match exactly the value of the "host" attribute.
                    if (methodElem.HasAttribute("host") && methodElem.Attributes["host"].Value != HttpContext.Current.Request.Headers["Host"])
                    {
                        continue;
                    }

                    // The request origin ("REMOTE_HOST" server variable) must have (or be) the same IP address as the hostname (or IP address) in the value of the "remoteHost" attribute.
                    if (methodElem.HasAttribute("remoteHost") && !context.IsRequestFromHost(methodElem.Attributes["remoteHost"].Value))
                    {
                        continue;
                    }

                    bool match = true;
                    foreach (XmlNode conditionNode in typeElem.SelectNodes("condition"))
                    {
                        XmlElement conditionElem = conditionNode as XmlElement;
                        if (conditionElem == null)
                        {
                            continue;
                        }

                        string value = null, pattern = null;
                        if (conditionElem.HasAttribute("header"))
                        {
                            value = HttpContext.Current.Request.Headers[conditionElem.Attributes["header"].Value];
                        }
                        else
                        {
                            continue;
                        }

                        if (conditionElem.HasAttribute("pattern"))
                        {
                            pattern = conditionElem.Attributes["pattern"].Value;
                        }
                        else
                        {
                            continue;
                        }

                        if (value == null || pattern == null)
                        {
                            continue;
                        }

                        if (!Regex.Match(value, pattern).Success)
                        {
                            match = false;
                            break;
                        }
                    }
                    if (!match)
                    {
                        continue;
                    }

                    XmlElement loginElem = typeElem["login"];
                    if (loginElem == null)
                    {
                        continue;
                    }

                    // Get username from <login> element
                    string externalUsername = null;
                    if (loginElem.HasAttribute("header"))
                    {
                        externalUsername = HttpContext.Current.Request.Headers[loginElem.Attributes["header"].Value];
                    }

                    if (externalUsername == null)
                    {
                        continue;
                    }
                    //context.IsUserIdentified = true;

                    AuthenticationType authType = IfyWebContext.GetAuthenticationType(typeof(UmssoAuthenticationType));

                    bool exists = User.DoesUserExist(context, externalUsername, authType);
                    User user   = User.GetOrCreate(context, externalUsername, authType);

                    bool register = !exists && loginElem.HasAttribute("register") && loginElem.Attributes["register"].Value == "true";
                    bool refresh  = exists && loginElem.HasAttribute("refresh") && loginElem.Attributes["refresh"].Value == "true";

                    context.LogInfo(this, string.Format("EO-SSO Get user : {0}", user.Username));
                    context.LogDebug(this, string.Format("EO-SSO Get user : exists = {0} -- refresh = {1}", exists, refresh));

                    // If username was not found and automatic registration is configured, create new user
                    // If username was found return with success

                    //if (register) user.AccountStatus = AccountStatusType.PendingActivation;

                    string email = null;

                    foreach (XmlElement elem in loginElem.ChildNodes)
                    {
                        if (register || refresh)
                        {
                            if (elem == null)
                            {
                                continue;
                            }
                            string value = null;
                            if (elem.HasAttribute("header"))
                            {
                                value = HttpContext.Current.Request.Headers[elem.Attributes["header"].Value];
                            }

                            context.LogDebug(this, string.Format("EO-SSO Get user : {0} = {1}", elem.Name, value));
                            if (!string.IsNullOrEmpty(value))
                            {
                                switch (elem.Name)
                                {
                                case "firstName":
                                    user.FirstName = value;
                                    break;

                                case "lastName":
                                    user.LastName = value;
                                    break;

                                case "email":
                                    email = value;
                                    break;

                                case "affiliation":
                                    user.Affiliation = value;
                                    break;

                                case "country":
                                    user.Country = value;
                                    break;

                                case "credits":
                                    int credits;
                                    int.TryParse(value, out credits);
                                    user.TotalCredits = credits;
                                    break;

                                case "proxyUsername":
                                    //user.ProxyUsername = value;
                                    break;

                                case "proxyPassword":
                                    //user.ProxyPassword = value;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (elem.HasAttribute("header") && elem.Name.Equals("email"))
                            {
                                user.Email = HttpContext.Current.Request.Headers[elem.Attributes["header"].Value];
                                break;
                            }
                        }
                    }
                    if (register && user.Username.Contains("@"))
                    {
                        user.Username = user.Username.Substring(0, user.Username.IndexOf("@")).Replace(".", "");
                    }
                    if (refresh)
                    {
                        user.Store();
                    }
                    //we do not store the email in case of email change
                    if (!string.IsNullOrEmpty(email))
                    {
                        user.Email = email;
                    }
                    return(user);
                }
                return(null);
            } catch (Exception e) {
                throw new Exception("Invalid authentication settings" + " " + e.Message + " " + e.StackTrace);
            }
        }
        /// <summary>
        /// Gets the user profile.
        /// </summary>
        /// <returns>The user profile.</returns>
        /// <param name="context">Context.</param>
        /// <param name="request">Request.</param>
        public override User GetUserProfile(IfyWebContext context, HttpRequest request = null, bool strict = false)
        {
            User usr = null;
            AuthenticationType authType = IfyWebContext.GetAuthenticationType(typeof(TepOauthAuthenticationType));

            var refreshCookie = Client.LoadTokenRefresh();
            var accessCookie  = Client.LoadTokenAccess();
            var refreshToken  = refreshCookie.Value;
            var accessToken   = accessCookie.Value;

            TimeSpan span = accessCookie.Expire.Subtract(DateTime.UtcNow);

            var refresh = (!string.IsNullOrEmpty(refreshToken) && (string.IsNullOrEmpty(accessToken) || span.TotalMinutes < context.GetConfigIntegerValue("AccessTokenExpireMinutes")));

            if (refresh)
            {
                context.LogDebug(this, "Refresh token");
                // refresh the token
                try {
                    Client.RefreshToken(refreshToken, refreshCookie.Username);
                    refreshToken = Client.LoadTokenRefresh().Value;
                    accessToken  = Client.LoadTokenAccess().Value;
                } catch (Exception e) {
                    context.LogError(this, e.Message);
                    return(null);
                }
            }

            if (!string.IsNullOrEmpty(accessToken))
            {
                context.LogDebug(this, "Get user info");
                TepOauthUserInfoResponse usrInfo;
                try {
                    usrInfo = Client.GetUserInfo <TepOauthUserInfoResponse>(accessToken);
                } catch (Exception e) {
                    context.LogError(this, e.Message);
                    return(null);
                }
                if (usrInfo == null)
                {
                    return(null);
                }

                context.LogDebug(this, "Get user info  - sub = " + usrInfo.sub);

                context.AccessLevel = EntityAccessLevel.Administrator;

                //first try to get user from username
                try {
                    usr = User.FromUsername(context, usrInfo.screenname);
                    usr.AccountStatus = AccountStatusType.Enabled;
                } catch (Exception) {
                    try {
                        usr = User.GetOrCreate(context, usrInfo.sub, authType);
                        if (usr.Id == 0)
                        {
                            usr.Username = usrInfo.preferred_username;
                        }
                        usr.AccountStatus = AccountStatusType.Enabled;
                    } catch (Exception e2) {
                        Client.RevokeSessionCookies();
                        throw e2;
                    }
                }
                bool isnew = (usr.Id == 0);

                //update user infos
                if (!string.IsNullOrEmpty(usrInfo.given_name))
                {
                    usr.FirstName = usrInfo.given_name;
                }
                if (!string.IsNullOrEmpty(usrInfo.email))
                {
                    usr.Email = usrInfo.email;
                }
                if (!string.IsNullOrEmpty(usrInfo.family_name))
                {
                    usr.LastName = usrInfo.family_name;
                }
                if (isnew && !string.IsNullOrEmpty(usrInfo.screenname))
                {
                    usr.Username = usrInfo.screenname;
                }
                usr.Store();

                if (isnew)
                {
                    usr.LinkToAuthenticationProvider(authType, usrInfo.sub);
                }

                //roles
                if (usrInfo.roles != null)
                {
                    //for now, if user has a role, he can process
                    if (usr.Level < UserLevel.Manager)
                    {
                        usr.Level = UserLevel.Manager;
                        usr.Store();
                    }

                    UserTep usrtep = UserTep.FromId(context, usr.Id);

                    //Add role to domains
                    // foreach(var rolestring in usrInfo.roles){
                    //     var roleIdentifier = rolestring.Substring(rolestring.LastIndexOf("-") + 1);
                    //     var domainIdentifier = rolestring.Substring(0,rolestring.LastIndexOf("-"));

                    //     var domain = ActivationFactory.GetOrCreateDomainForActivation(context, domainIdentifier);
                    //     var role = ActivationFactory.GetOrCreateRole(context, roleIdentifier);
                    //     role.GrantToUser(usrtep.Id, domain.Id);
                    // }

                    //Remove role if user does not have it anymore
                    // var communities = usrtep.GetUserCommunities();
                    // foreach (var community in communities) {
                    //     try {
                    //         var roles = usrtep.GetUserRoles(community);
                    //         if (roles.Count > 0) {
                    //             foreach (var role in roles){
                    //                 bool exists = false;
                    //                 foreach(var rolestring in usrInfo.roles){
                    //                     var roleIdentifier = rolestring.Substring(rolestring.LastIndexOf("-") + 1);
                    //                     var domainIdentifier = rolestring.Substring(0,rolestring.LastIndexOf("-"));
                    //                     if(community.Identifier == domainIdentifier && role.Identifier == roleIdentifier) exists = true;
                    //                 }
                    //                 if(!exists) role.RevokeFromUser(usr, community);
                    //             }
                    //         }
                    //     } catch (Exception e) {
                    //         context.LogError(this, e.Message);
                    //     }
                    // }
                }

                return(usr);
            }

            return(null);
        }
Example #29
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>Always returns false (method is not applicable to this authentication type).</summary>
        /// <returns><c>false</c> unlike the expected behaviour for authentication types with no external identity provider (<c>true</c>) because SessionlessAuthenticationType instances do not support essions at all.</returns>
        /// <param name="context">The execution environment context.</param>
        /// <param name="request">The current HttpRequest to analyse.</param>
        public override bool IsExternalSessionActive(IfyWebContext context, HttpRequest request)
        {
            return(false);
        }
Example #30
0
        public object Get(CallBackRequest request)
        {
            var redirect = "";

            TepWebContext context = new TepWebContext(PagePrivileges.EverybodyView);
            UserTep       user    = null;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/cb GET"));
                if (!string.IsNullOrEmpty(request.error))
                {
                    context.LogError(this, request.error);
                    context.EndSession();
                    return(OAuthUtils.DoRedirect(context.BaseUrl, false));
                }

                Connect2IdClient client = new Connect2IdClient(context.GetConfigValue("sso-configUrl"));
                client.SSOAuthEndpoint = context.GetConfigValue("sso-authEndpoint");
                client.SSOApiClient    = context.GetConfigValue("sso-clientId");
                client.SSOApiSecret    = context.GetConfigValue("sso-clientSecret");
                client.SSOApiToken     = context.GetConfigValue("sso-apiAccessToken");
                client.RedirectUri     = context.GetConfigValue("sso-callback");
                OauthTokenResponse tokenresponse;
                try {
                    tokenresponse = client.AccessToken(request.Code);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-access"), tokenresponse.access_token, null, tokenresponse.expires_in);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-refresh"), tokenresponse.refresh_token, null);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-id"), tokenresponse.id_token, null, tokenresponse.expires_in);
                } catch (Exception e) {
                    DBCookie.DeleteDBCookie(context, context.GetConfigValue("cookieID-token-access"));
                    DBCookie.DeleteDBCookie(context, context.GetConfigValue("cookieID-token-refresh"));
                    DBCookie.DeleteDBCookie(context, context.GetConfigValue("cookieID-token-id"));
                    throw e;
                }

                TepLdapAuthenticationType auth = (TepLdapAuthenticationType)IfyWebContext.GetAuthenticationType(typeof(TepLdapAuthenticationType));
                auth.SetConnect2IdCLient(client);
                auth.TrustEmail = true;

                user = (UserTep)auth.GetUserProfile(context);
                if (user == null)
                {
                    throw new Exception("Unable to load user");
                }
                context.LogDebug(this, string.Format("Loaded user '{0}'", user.Username));
                if (string.IsNullOrEmpty(user.Email))
                {
                    throw new Exception("Invalid email");
                }

                context.StartSession(auth, user);
                context.SetUserInformation(auth, user);

                DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-access"), tokenresponse.access_token, user.Username, tokenresponse.expires_in);
                DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-refresh"), tokenresponse.refresh_token, user.Username);
                DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-id"), tokenresponse.id_token, user.Username, tokenresponse.expires_in);

                redirect = context.GetConfigValue("dashboard_page");
                if (string.IsNullOrEmpty(redirect))
                {
                    redirect = context.GetConfigValue("BaseUrl");
                }

                if (!string.IsNullOrEmpty(HttpContext.Current.Session["return_to"] as string))
                {
                    redirect = HttpContext.Current.Session["return_to"] as string;
                    HttpContext.Current.Session["return_to"] = null;
                }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(OAuthUtils.DoRedirect(redirect, false));
        }